Origin of the problem:
The company has a project to use Netty as the implementation of WebSocket, recently intends to deploy dual-machine, which makes the original memory of the channel information is no longer viable, need to be saved in Redis, The Jedisclient class that was injected through @autowired was found to be unusable in the transformation process, and the outer representation of the Jedisclient object was null
Resolution process:
1. The first thought is the spring configuration introduced the order of the problem, resulting in Netty startup time Jedisclient has not materialized well, adjusted to find that the problem remains
2. After Baidu found that a lot of people encounter this problem, there is a reply that Netty can not use injected beans, need to take the initiative through the Getbean way to obtain, this problem has basically been determined, not the problem of configuration, and Netty itself with the problem
3. Finding a solution after discovering the root cause of the problem is clear, and the final solution needs to use spring's two annotations @component and @postconstruct,
@Component Everyone can be familiar with, is to instantiate the ordinary pojo into the spring container, equivalent to the configuration file <bean id= "" class= "" >. Refer to various components, such as the class does not belong to @controller or @service, and so on, you can use the annotation callout
@PostConstruct This annotation is my first contact, adding the annotation to the method will execute the method when the project is started, that is, when the spring container is initialized, it is executed in the order of constructors and @autowired: constructors >> @ Autowired >> @PostConstruct, it seems that when we want to do some initialization when we build the object, but these initialization operations depend on the injected bean, it cannot be implemented in the constructor. To do this, you can use the @postconstruct annotation an Init method to complete the initialization, which is automatically called after the bean injection is complete.
The final implementation code is as follows:
Public classWebsocketserverhandlerextendsSimplechannelinboundhandler<object>{@AutowiredPrivatejedisclient jedisclient; Private StaticWebsocketserverhandler Websocketserverhandler; @PostConstruct Public voidinit () {Websocketserverhandler= This; } @Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {webSocketServerHandler.jedisClient.set (key,600, Ctx.channel ()); }}
Parameter article:
1.80502684
2.80392867
Netty handler processing class cannot use @autowired to inject bean solution