码迷,mamicode.com
首页 > Web开发 > 详细

netty4——is not a @Sharable handler

时间:2014-07-29 16:22:59      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:style   java   os   strong   io   for   cti   ar   

State management(handler的状态管理)

A ChannelHandler often needs to store some stateful information. The simplest and recommended approach is to use member variables:

public interface Message {
     // your methods here
 }
 public class DataServerHandler extends SimpleChannelInboundHandler<Message> {
     private boolean loggedIn;
     @Override
     public void channelRead0(ChannelHandlerContext ctx, Message message) {
         Channel ch = e.getChannel();
         if (message instanceof LoginMessage) {
             authenticate((LoginMessage) message);
             loggedIn = true;
         } else (message instanceof GetDataMessage) {
             if (loggedIn) {
                 ch.write(fetchSecret((GetDataMessage) message));
             } else {
                 fail();
             }
         }
     }
     ...
 }

 

Because the handler instance has a state variable(状态变量) which is dedicated(专用) to one connection, you have to create a new handler instance for each new channel to avoid a race condition(竞态条件) where a unauthenticated(未验证的) client can get the confidential(机密的) information:

 // Create a new handler instance per channel.
 // See ChannelInitializer.initChannel(Channel).
 public class DataServerInitializer extends ChannelInitializer<Channel> {
     @Override
     public void initChannel(Channel channel) {
         channel.pipeline().addLast("handler", new DataServerHandler());
     }
 }


is not a @Sharable handler 

当出现这样的错误提示时,有两种解决方法,要么就是加上注解@Sharable,要么就是每次都new一个新的handler的实例

====END====



netty4——is not a @Sharable handler,布布扣,bubuko.com

netty4——is not a @Sharable handler

标签:style   java   os   strong   io   for   cti   ar   

原文地址:http://my.oschina.net/xinxingegeya/blog/295577

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!