最近在做一个springboot的项目
然后集成了netty在里面用来推送或聊天的。
写代码的时候想把用户连接成功后的channelid 存到redis里面,结果有了下面代码
public class NettyLoginHandler implements NettyMessageHandler{
@Autowired
private RedisCache redisCache;
@Override
public void handleMsg(NettyRequestDto message) {
redisCache.setCacheObject(NettyConstants.CHANNEL_REDIS_KEY+message.getUserId(),message.getCtx().channel().id());
NettyResponseDto dto = new NettyResponseDto();
dto.setType(0);
dto.setData("登陆成功");
byte[] bytes = dto.toString().getBytes(CharsetUtil.UTF_8);
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
message.getCtx().channel().writeAndFlush(new TextWebSocketFrame(buf));
}
}
我注入的redisCache一直报空指针
一直没想明白,查阅资料后代码修改为如下
**
*
* Created by tcw on 2020/7/30.
*/
@Component//把这个类交给spring管理
public class NettyLoginHandler implements NettyMessageHandler{
@Autowired
private RedisCache redisCache;
private static NettyLoginHandler nettyLoginHandler;
@PostConstruct
public void init(){
nettyLoginHandler = this;
}
@Override
public void handleMsg(NettyRequestDto message) {
nettyLoginHandler.redisCache.setCacheObject(NettyConstants.CHANNEL_REDIS_KEY+message.getUserId(),message.getCtx().channel().id());
NettyResponseDto dto = new NettyResponseDto();
dto.setType(0);
dto.setData("登陆成功");
byte[] bytes = dto.toString().getBytes(CharsetUtil.UTF_8);
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
message.getCtx().channel().writeAndFlush(new TextWebSocketFrame(buf));
}
}
大概意思是,这个类我spring不管了?
因为netty是新线程跑的吗?
参考:
https://blog.csdn.net/qq_39851704/article/details/80392867
网友评论