netty(八):AttributeKey和AttributeMap实现不同channelContext中传递数据

1.AttributeMap

在netty4中将数据保存在channel中使用的是AttributeMap,如图,因为AbstractChannelHandlerContext实现了ChannelHandlerContext,而ChannelHandlerContext继承了AttributeMap。

故ChannelInboundHandlerAdapter实现了AttributeMap,可以把数据保存在channel上。
在这里插入图片描述
在这里插入图片描述

2.配置

自定义一个key,保存在常量中,以后去数据就可以直接用NETTY_CHANNEL_KEY拿到一个NettyChannel对象。

package config;

import io.netty.util.AttributeKey;
import pojo.NettyChannel;

/**
 * 常量配置文件
 */
public class AttributeMapConstant {

    public static final AttributeKey<NettyChannel> NETTY_CHANNEL_KEY = AttributeKey.valueOf("netty.channel");
}

自定义的数据类型NettyChannel

package pojo;

import java.util.*;

public class NettyChannel {
    private String name;


    private Date createDate;


    public NettyChannel(String name,Date createDate) {
        this.name = name;
        this.createDate = createDate;
    }

    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

3.server端

主函数只有一个自定义的AttServerHandler用于接收并处理接收到的数据

package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class AttServer {
    private int port;

    public AttServer(int port) {
        this.port = port;
    }

    public void start(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sbs = new ServerBootstrap()
                    .group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("decoder", new StringDecoder());
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            ch.pipeline().addLast(new AttServerHandler());
                        };

                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            // 绑定端口,开始接收进来的连接
            ChannelFuture future = sbs.bind(port).sync();

            System.out.println("Server start listen at " + port );
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8888;
        new AttServer(port).start();
    }

}

AttServerHandler

package server;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class AttServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server channelRead..");
        System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());
        ctx.write("server write"+msg);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

4.client端

AttClientHandler用于向channel中放入<NETTY_CHANNEL_KEY,nettyChannel>。Att2ClientHandler会收到数据并打印。

package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class AttClient {
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8888"));

    public static void main(String[] args) throws Exception {
        initChannel();
    }

    public static void initChannel() throws InterruptedException{
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("decoder", new StringDecoder());
                            p.addLast("encoder", new StringEncoder());
                            p.addLast(new AttClientHandler());
                            p.addLast(new Att2ClientHandler());
                        }
                    });

            ChannelFuture future = b.connect(HOST, PORT).sync();
            future.channel().writeAndFlush("hello Netty,Test attributeMap");
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }

    }
}

AttClientHandler

package client;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import pojo.NettyChannel;

import java.util.*;

import static config.AttributeMapConstant.NETTY_CHANNEL_KEY;

public class AttClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * channelActive在channelRead之前
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Attribute<NettyChannel> att = ctx.attr(NETTY_CHANNEL_KEY);  // 向ChannelHandlerContext中传入AttributeKey<NettyChannel>对象(key),获取Attribute<NettyChannel>(value)
        NettyChannel nettyChannel = att.get();// 获取AttributeKey<NettyChannel>中的nettyChannel
        if (nettyChannel == null) {
            NettyChannel newNChannel = new NettyChannel("Att1Client", new Date());
            att.setIfAbsent(newNChannel); // 给NETTY_CHANNEL_KEY设置一个value
            System.out.println(newNChannel.getName() + "=======channelRead attributeMap 中是没有值的==="+this.getClass().getSimpleName());
        }else {
            System.out.println(nettyChannel.getName() + "=======attributeMap 中是有值的===="+this.getClass().getSimpleName());
            //System.out.println(nettyChannel.getName() + "=======" + nettyChannel.getCreateDate());
        }
        System.out.println("Att1CientHandler Active");
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Attribute<NettyChannel> attr = ctx.attr(NETTY_CHANNEL_KEY);
        NettyChannel nettyChannel = attr.get();
        if (nettyChannel == null) {
            NettyChannel newNChannel = new NettyChannel("Att1Client", new Date());
            attr.setIfAbsent(newNChannel); // 给NETTY_CHANNEL_KEY设置一个value
            System.out.println(newNChannel.getName() + "=======channelRead attributeMap 中是没有值的==="+this.getClass().getSimpleName());
        }else {
            System.out.println(nettyChannel.getName() + "=======attributeMap 中是有值的==="+this.getClass().getSimpleName());
            //System.out.println(nettyChannel.getName() + "=======" + nettyChannel.getCreateDate());
        }
        System.out.println("Att1ClientHandler read Message:" + msg);

        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

Att2ClientHandler

package server;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class AttServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server channelRead..");
        System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());
        ctx.write("server write"+msg);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

5.测试

Att2ClientHandler中收到了Att1ClientHandler的数据。说明收据在channel上发送成功。
在这里插入图片描述

源码: https://github.com/LUK-qianliu/netty

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值