@Sharable无效的问题
来源:3-6 服务端启动总结

正义柔情永在
2019-02-18
老师: 我对@Sharable注解的理解就是,如果handler上面没有加这个注解则是,每个channel 对象对应一个pipline对象,每个pipline对象都含有一个新的handler对象,如果在handler上面加入了@Sharable注解,则所有的pipline对象共享一个handler.但是我自己测试发现,就算是标注了@Sharable的handler,每当有一个新的客户端连接进入,就是实例化一个新的handler,并不是我理解的那样. 代码如下:
//-----------------------------------启动类-----------------------------------------
public static void main(String[] args) throws Exception{
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// pipeline.addLast(new ChannelHandler1());
}
});
ChannelFuture channelFuture = bootstrap.bind(8888).sync();
System.out.println(“服务器启动成功”);
channelFuture.channel().closeFuture().sync();//程序在此处阻塞,等待程序退出
}
//-----------------------------------ChannelHandler1 -----------------------------------------
@ChannelHandler.Sharable
class ChannelHandler1 extends SimpleChannelInboundHandler{
public ChannelHandler1(){
System.out.println(“我被实例化了”); //每个客户端都会实例化一个新对象
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {}
}
1回答
-
@Sharable 的意思是这个类创建出来的对象可以被共享,而是否要被共享,是用户代码自己决定的,如果没有@Sharable,那这个类创建出来的同一个对象是肯定不能被多个channel的pipeline共享的
112019-03-03
相似问题