Netty笔记(七)之AttributeMap

netty版本

  1. netty版本:io.netty:netty-all:4.1.33.Final

AttributeMap

  1. AttributeMap是绑定在Channel或者ChannelHandlerContext上的一个附件(在Netty4.1.X后ChannelHandlerContext.attr(xx) == Channel.attr(xx))。AttributeMap是线程安全的。AttributeMap必须是唯一的,因此最好定义成全局变量(比如static final类型)

  2. ChannelChannelHandlerContext都扩展了AttributeMap接口,因此每一个ChannelChannelHandlerContext实例都可以像Map一样按照key来存取value

代码案例

  1. 启动代码

        public class EchoServer {
        
            private final int port;
        
            public EchoServer(int port) {
                this.port = port;
            }
        
            public void start() throws Exception {
        
                NioEventLoopGroup boss = new NioEventLoopGroup(1);
                NioEventLoopGroup worker = new NioEventLoopGroup();
                try {
                    ServerBootstrap b = new ServerBootstrap();
                    b.group(boss, worker)
                            .channel(NioServerSocketChannel.class)
                            .localAddress(new InetSocketAddress(port))
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel ch) {
                                    ChannelPipeline pipeline = ch.pipeline();
                                    pipeline.addLast(new LineBasedFrameDecoder(1024));
                                    pipeline.addLast(new StringDecoder());
                                    pipeline.addLast(new StringEncoder());
                                    pipeline.addLast(new EchoServerHandlerA());
                                    pipeline.addLast(new EchoServerHandlerB());
        
        
                                }
                            });
                    ChannelFuture f = b.bind().sync();
                    System.out.println(String.format("%s started and listen on %s", EchoServer.class.getName(), f.channel().localAddress()));
                    f.channel().closeFuture().sync();
                } finally {
                    boss.shutdownGracefully().sync();
                    worker.shutdownGracefully().sync();
                }
            }
        
            public static void main(String[] args) throws Exception {
                new EchoServer(8080).start();
            }
        }
    
    
  2. EchoServerHandlerA

        public class EchoServerHandlerA extends SimpleChannelInboundHandler<String> {
            private static final String LINE = System.getProperty("line.separator");
        
            public static final AttributeKey<AtomicLong> CONNECT_COUNT = AttributeKey.valueOf("CONNECT_COUNT");
        
        
            @Override
            public void channelActive(ChannelHandlerContext ctx) {
        
                Attribute<AtomicLong> attr = ctx.channel().attr(CONNECT_COUNT);
                AtomicLong count = attr.get();
                if (count == null) {
                    count = new AtomicLong(1);
                    attr.setIfAbsent(count);
                    System.out.println("A channelActive count is " + count.get());
                } else {
                    count.getAndIncrement();
                    System.out.println("A channelActive count is " + count.get());
                }
                ctx.fireChannelActive();
            }
        
        
            @Override
            public void channelRead0(ChannelHandlerContext ctx, String msg) {
                Attribute<AtomicLong> attr = ctx.channel().attr(CONNECT_COUNT);
                AtomicLong count = attr.get();
                if (count == null) {
                    count = new AtomicLong(1);
                    attr.setIfAbsent(count);
                    System.out.println("A channelRead count is " + count.get());
                } else {
                    count.getAndIncrement();
                    System.out.println("A channelRead count is " + count.get());
                }
        
                ctx.fireChannelRead(msg);
            }
        }
    
    
    
  3. EchoServerHandlerB

        public class EchoServerHandlerB extends SimpleChannelInboundHandler<String> {
            private static final String LINE = System.getProperty("line.separator");
        
        
            @Override
            public void channelActive(ChannelHandlerContext ctx) {
        
                Attribute<AtomicLong> attr = ctx.channel().attr(EchoServerHandlerA.CONNECT_COUNT);
                AtomicLong count = attr.get();
                if (count == null) {
                    count = new AtomicLong(1);
                    attr.setIfAbsent(count);
                    System.out.println("B channelActive count is " + count.get());
                } else {
                    count.getAndIncrement();
                    System.out.println("B channelActive count is " + count.get());
                }
                ctx.fireChannelActive();
            }
        
        
            @Override
            public void channelRead0(ChannelHandlerContext ctx, String msg) {
                Attribute<AtomicLong> attr = ctx.channel().attr(EchoServerHandlerA.CONNECT_COUNT);
                AtomicLong count = attr.get();
                if (count == null) {
                    count = new AtomicLong(1);
                    attr.setIfAbsent(count);
                    System.out.println("B channelRead count is " + count.get());
                } else {
                    count.getAndIncrement();
                    System.out.println("B channelRead count is " + count.get());
                }
        
            }
        }
    
    
    
  4. 输出

        A channelActive count is 1
        B channelActive count is 2
        A channelRead count is 3
        B channelRead count is 4
    
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值