Netty的AttributeMap

本文介绍了Netty框架中AttributeMap接口的使用方法及其应用场景。AttributeMap用于存储Channel相关的属性,通过AttributeKey获取对应的Attribute对象。文章通过客户端和服务端的例子展示了如何在ChannelHandlerContext中设置和读取ChannelID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty的AttributeMap

AttributeMap接口

public interface AttributeMap {  
    <T> Attribute<T> attr(AttributeKey<T> key);  
}
AttributeMap接口只有一个attr()方法,接收一个AttributeKey类型的key,返回一个Attribute类型的value。按照Javadoc,AttributeMap实现必须是线程安全的。所有的Channel和ChannelHandlerContext实现了AttributeMap接口

简单应用:

public class AttributeMapID {
	public static final AttributeKey<ChannelID> Channel_ID = AttributeKey.valueOf("netty.channel");
}
public class ClienHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
					Attribute<ChannelID> attribute =  ctx.attr(Channel_ID);
					ChannelID channelID = attribute.get();
					if (channelID==null) {
						ChannelID id = new ChannelID("link",new Date());
						channelID = attribute.setIfAbsent(id);
					} else {
						System.out.println("channelActive attributeMap 中是有值的");  
			            System.out.println(channelID.getName() + "=======" + channelID.getDate());  
					}
					  System.out.println("HelloWorldC0ientHandler Active");  
				        ctx.fireChannelActive();   
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Attribute<ChannelID> attribute =  ctx.attr(Channel_ID);
		ChannelID channelID = attribute.get();
		if (channelID==null) {
			ChannelID id = new ChannelID("link",new Date());
			channelID = attribute.setIfAbsent(id);
		} else {
			System.out.println("channelActive attributeMap 中是有值的");  
            System.out.println(channelID.getName() + "=======" + channelID.getDate());  
		}
		
		System.out.println("HelloWorldClientHandler read Message:" + msg);  
        
        ctx.fireChannelRead(msg);  
	}
		
}
public class Server {
	int port;
	public Server(int port) {
				this.port = port;
				start();
	}
	
	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 ServerHandler());  
	                        };  
	                          
	                    }).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) {
			Server server = new Server(7788);
	}

}
public class ServerHandler 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();  
	}
		
}
public class Client {
		
	String host;
	int port;
	
	public Client(String host,int port) throws InterruptedException {
		// TODO Auto-generated constructor stub
		this.host = host;
		this.port =port;
		connect();
	}
	
	public void connect() throws InterruptedException {
		  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 ClienHandler());  
	                    
	                 }  
	             });  
	  
	            ChannelFuture future = b.connect(host,port).sync();  
	            future.channel().writeAndFlush("hello Netty,Test attributeMap");  
	            future.channel().closeFuture().sync();  
	        } finally {  
	            group.shutdownGracefully();  
	        }  
	}
	
	
	public static void main(String[] args) throws InterruptedException {
				Client client = new Client("127.0.0.1", 7788);
	}
}
public class ChannelID {
			
	String name;
	Date date;
	public ChannelID(String name,Date date) {
		// TODO Auto-generated constructor stub
		this.date = date;
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	
	
	
}
### Netty 中 Bootstrap 的使用方法 Bootstrap 类是 Netty 提供的一个便捷工厂类,用于简化客户端和服务端应用程序的配置与启动过程[^3]。通过该类,开发人员能够更高效地管理 I/O 模型、线程池分配、处理器链构建等工作,并最终实现高性能网络应用的快速部署。 #### 创建并配置 Bootstrap 实例 对于客户端而言,`Bootstrap` 可以用来建立连接至远程主机;而对于服务端,则应选用 `ServerBootstrap` 来监听传入请求。以下是关于如何创建和初始化这两个对象的具体说明: ##### 客户端示例 ```java // 初始化一个新的 Bootstrap 对象实例 Bootstrap bootstrap = new Bootstrap(); // 配置 NIO 线程组 (EventLoopGroup),这里我们只指定一个工作线程组即可满足需求 bootstrap.group(new NioEventLoopGroup()); // 设置 Channel 工厂函数为 NIO SocketChannel bootstrap.channel(NioSocketChannel.class); // 添加自定义业务逻辑处理器到管道中 bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 注册一系列编解码器和其他中间件... ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new LineBasedFrameDecoder(80)); ch.pipeline().addLast(new StringDecoder()); // 绑定具体的业务处理 Handler ch.pipeline().addLast(new CustomClientHandler()); } }); ``` 上述代码片段展示了如何利用 `Bootstrap` 构建一个简单的 TCP 客户端,在此过程中完成了对事件循环组的选择、传输层协议的支持以及消息编码/解码机制的设计等一系列重要操作[^5]。 ##### 服务端示例 当涉及到服务器端编程时,除了以上提到的内容外还需要额外考虑接收新连接的能力。因此,此时应该采用 `ServerBootstrap` 而不是普通的 `Bootstrap`: ```java // 同样先准备两个 EventLoopGroups 分别负责接受新的连接和处理已存在的连接 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap serverBootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) // 下面几行是对即将产生的子 Channels 进行进一步定制化设定 .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>(){ @Override public void initChannel(SocketChannel ch){ ch.pipeline().addLast(new StringEncoder(),new LineBasedFrameDecoder(80),new StringDecoder(), new SimpleChannelInboundHandler<String>(){ @Override protected void channelRead0(ChannelHandlerContext ctx,String msg)throws Exception{ System.out.println("收到的消息:"+msg); ctx.writeAndFlush("Echo: "+msg+"\r\n"); } @Override public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){ cause.printStackTrace(); ctx.close(); } }); } }); // 尝试绑定给定地址上的特定端口等待外部访问 ChannelFuture future = serverBootstrap.bind(port).sync(); }catch(Exception e){ throw new RuntimeException(e); }finally{ // 清理资源释放占用 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } ``` 这段例子不仅体现了怎样基于 `ServerBootstrap` 开启 HTTP 或其他类型的 Web 服务,同时也演示了针对不同场景下的灵活调整策略——比如保持活动状态选项 (`SO_KEEPALIVE`) 和异常捕获机制等特性[^1]。 ### 关键概念解析 - **EventLoopGroup**: 表示一组单线程事件循环,每个都包含自己的 Selector 并且可以独立运行。Boss Group 主要关注于接收来自外界的新连接请求,而 Worker Groups 则专注于已经成功建立了通信关系后的数据交换事务。 - **Pipeline & Handlers**: Pipeline 是一条有序的任务队列结构,其中包含了多个 Handler 成员节点。每当有新的输入输出事件发生时就会触发相应位置上所关联的方法调用序列,从而达到异步非阻塞的效果。常见的内置组件包括但不限于 ByteToMessageCodec 编译转换器、DelimiterBasedFrameDecoder 边界分隔符帧拆分器等等。 - **AttributeMap and AttributeKey**: 当面对复杂的分布式系统架构设计或者第三方库集成情况时,可能会遇到某些必要的上下文信息无法直接传递的问题。这时就可以借助 AttributeMap 抽象来存储临时性的元数据记录,并依靠对应的唯一标识符 AttributeKey 获取它们[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值