注解

@Sharable

说明

1.用来说明ChannelHandler是否可以在多个channel直接共享使用。
2.netty为了安全考虑,有一个约束就是同个ChannelHandler不能在Channel的pipeline重复添加,如果ChannelHandler已经有做线程安全的处理,那么我们就可以为ChannelHandler添加@Sharable摆脱这个限制。

有没有做线程安全的处理只是一个编写代码自行的约束,纵使假如没做线程安全的处理,添加@Sharable一样可以在Channel的pipeline重复添加。

约束只作用于同个ChannelHandler对象,如果addLast每次都是一个new的新的ChannelHandler,则不影响。

3.不是所有的Channel都可以加@Sharable,单例解码器相关的添加@Sharable一样会被限制。

代码演示

@Sharable
@Component
public class AdapterHandler extends SimpleChannelInboundHandler<AdapterMessage>{
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, AdapterMessage msg) throws Exception {
	//...
    }
}
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup work = new NioEventLoopGroup();

ServerBootstrap bootstrap =  new ServerBootstrap();
try {
	bootstrap.group(boss, work)
	.channel(NioServerSocketChannel.class)
	.childHandler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel sc) throws Exception {
			sc.pipeline()
			.addLast(adapterHandler);	//同个AdapterHandler没有@Sharable不能在Channel的pipeline重复添加
		}
	})
	.option(ChannelOption.SO_BACKLOG, 128)
	.childOption(ChannelOption.TCP_NODELAY, true)
	.childOption(ChannelOption.SO_KEEPALIVE,true)
	.childOption(ChannelOption.SO_REUSEADDR, true)
	.childOption(ChannelOption.SO_LINGER,null);
	ChannelFuture future;
	future = bootstrap.bind("0.0.0.0",port);
	future.channel().closeFuture().sync();
} catch (InterruptedException e) {
	e.printStackTrace();
}finally {
	boss.shutdownGracefully();
	work.shutdownGracefully();
}

参考

关于netty的@Sharable注解含义,你可bie瞎说了
https://blog.csdn.net/wb_snail/article/details/106263470?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~default-5-106263470-blog-120483682.pc_relevant_multi_platform_whitelistv3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~default-5-106263470-blog-120483682.pc_relevant_multi_platform_whitelistv3&utm_relevant_index=10