is not a @Sharable handler解決方法
昨天在寫編碼器的時候,因為是和spring整合,因此在使用編碼的時候用Autowired自動注入
@Autowired private ProtocolDecoder protocolDecoder ; @Autowired private ProtocolEncoder protocolEncoder;
結果在多個客戶端連接(其實不是多客戶端的問題)的時候導致一直在報錯,如下
io.netty.channel.ChannelPipelineException: com.mzj.ProtocolDecoder is not a @Sharable handler, so can't be added or removed multiple times.
於是我就自作聰明的將ProtocolDecoder上加了個@Sharable注解,結果在啟動的時候就報錯了。
Caused by: java.lang.IllegalStateException: ChannelHandler com.mzj.ProtocolDecoder is not allowed to be shared
最后的解決方法是,不要使用單例了,每次添加handler的時候直接new
pipeline.addLast("decoder",new ProtocolDecoder() ); pipeline.addLast("encoder",new ProtocolEncoder()) ;
當然如果是在ChannelInitializer的子類報錯說is not a @Sharable handler,一般情況加上@Sharable注解即可