NettyClientHandler.java 2.1 KB
Newer Older
1
package github.javaguide.transport.netty.client;
S
shuang.kou 已提交
2 3 4 5

import github.javaguide.dto.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
6
import io.netty.channel.SimpleChannelInboundHandler;
S
shuang.kou 已提交
7 8 9 10 11 12
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
13 14
 * 自定义客户端 ChannelHandler 来处理服务端发过来的数据
 *
15 16 17 18
 * <p>
 * 如果继承自 SimpleChannelInboundHandler 的话就不要考虑 ByteBuf 的释放 ,{@link SimpleChannelInboundHandler} 内部的
 * channelRead 方法会替你释放 ByteBuf ,避免可能导致的内存泄露问题。详见《Netty进阶之路 跟着案例学 Netty》
 *
S
shuang.kou 已提交
19
 * @author shuang.kou
20
 * @createTime 2020年05月25日 20:50:00
S
shuang.kou 已提交
21 22 23 24
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

25 26 27
    /**
     * 读取服务端传输的消息
     */
S
shuang.kou 已提交
28 29 30
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
31
            logger.info(String.format("client receive msg: %s", msg));
S
shuang.kou 已提交
32
            RpcResponse rpcResponse = (RpcResponse) msg;
33
            // 声明一个 AttributeKey 对象,类似于 Map 中的 key
34
            AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse" + rpcResponse.getRequestId());
35 36 37 38 39
            /*
             * AttributeMap 可以看作是一个Channel的共享数据源
             * AttributeMap 的 key 是 AttributeKey,value 是 Attribute
             */
            // 将服务端的返回结果保存到 AttributeMap 上
S
shuang.kou 已提交
40 41 42 43 44 45 46
            ctx.channel().attr(key).set(rpcResponse);
            ctx.channel().close();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

47 48 49
    /**
     * 处理客户端消息发生异常的时候被调用
     */
S
shuang.kou 已提交
50 51
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
52
        logger.error("client catch exception:", cause);
S
shuang.kou 已提交
53 54 55 56 57
        cause.printStackTrace();
        ctx.close();
    }
}