1. 注意在Encoder、Decoder、Handler中使用注入
@Resource
private AuthHandler authHandle
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new NtripDecode());
ch.pipeline().addLast(authHandler);
}
})
在ch.pipeline().addLast的時候,裏面填入的參數不能是交給Spring管理的類,因爲每次連接過來時,都需要重新new,因此該類中的參數也無法使用@Autowired與@Resouce這類註解。
若採用以上的方式,就會報以下錯誤:
io.netty.channel.ChannelPipelineException: com.cnostar.cloud.gateway.ntrip.handler.AuthHandler is not a @Sharable handler, so can't be added or removed multiple times.
若需要在這些類中需要使用到注入的參數怎麼辦,可以採用類似以下方式,用一個靜態類進行管理:
@Configuration
public class SpringBeanManager {
private static AuthFeignService authFeignService;
@Autowired
public void setAuthFeignService(AuthFeignService authFeignService) {
SpringBeanManager.authFeignService = authFeignService;
}
public static AuthFeignService getAuthFeignService() {
return authFeignService;
}
}