netty4——is not a @Sharable handler
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====
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。