Hello,请教一下ByteBuf的释放问题
iSenninha opened this issue · comments
终于看到Netty版的服务器了,想请教一个ByteBuf的问题,我的毕业设计撸了个类似这个项目的编解码工具,遇到了释放ByteBuf的问题,在你的项目里解码是这样的:
private Message readMessage(short module, short cmd, ByteBuf in) {
Class<?> msgClazz = SpringContext.getMessageFactory().createMessage(module, cmd);
try {
Serializer messageCodec = Serializer.getSerializer(msgClazz);
Message message = (Message) messageCodec.decode(in, msgClazz, null);
return message;
} catch (Exception e) {
LoggerUtils.error("读取消息出错,模块号{},类型{},异常{}", new Object[]{module, cmd ,e});
}
return null;
}
然后在decode里是这样:
@Override
public Object decode(ByteBuf in, Class<?> type, Class<?> wrapper) {
try {
Object bean = type.newInstance();
for (FieldCodecMeta fieldMeta:fieldsMeta) {
Field field = fieldMeta.getField();
Serializer fieldCodec = fieldMeta.getSerializer();
Object value = fieldCodec.decode(in, fieldMeta.getType(), fieldMeta.getWrapper());
field.set(bean, value);
}
return bean;
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
这两部就从ByteBuf-->POJO,但是有个问题,这里的ByteBuf需要释放吗?因为return null了,那么TailContext就无法去自动释放这个ByteBuf了吧??是需要在解码结束后手动调用这个吧?
@Override
public Object decode(ByteBuf in, Class<?> type, Class<?> wrapper) {
try {
Object bean = type.newInstance();
for (FieldCodecMeta fieldMeta:fieldsMeta) {
Field field = fieldMeta.getField();
Serializer fieldCodec = fieldMeta.getSerializer();
Object value = fieldCodec.decode(in, fieldMeta.getType(), fieldMeta.getWrapper());
field.set(bean, value);
}
//手动释放ByteBuf
ReferenceCountUtil.release(buf);
return bean;
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
谢谢~
感谢提醒,虽然这里的ByteBuff用的是非池化的UnpooledDirectByteBuf,但当数据不往下个节点传的话,还是尽量手动释放下引用