最近项目在做售货机与后台管理系统实时通信,整合了netty+socket,在重写ChannelInboundHandlerAdapter时,service类注入不进来。直接上解决办法。
这里利用了@Component注解标识,与@PostConstruct标注在加载servlet就初始化该类,解决了注入不了的问题。
@Component
public class ServerChannelInboundHandler extends ChannelInboundHandlerAdapter {
private static Logger logger = LoggerFactory.getLogger(ServerChannelInboundHandler.class);
@Autowired
private SocketService socketService;
@Autowired
private SysAgentService sysAgentService;
// 解决ioc无法正常注入的问题
private static ServerChannelInboundHandler channelInboundHandler;
@PostConstruct
public void init() {
channelInboundHandler = this;
}
/**
* 客户端与服务端连接成功后,该通道即是活跃
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
NettySession.addChannelContext(ctx);
logger.info("连接成功");
}
/**
* 当客户端主动断开服务端,该通道即是不活跃
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
logger.info("远程与服务器连接中断");
NettySession.removeChannelContext(ctx);
}
/**
* 读取发送过来的消息
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
// 转码
String message = new String((byte[])msg, "UTF-8");
channelInboundHandler.socketService.doSocketMessage(ctx, message);
ReferenceCountUtil.release(msg);
//channelInboundHandler.socketService.doResponseMessage(ctx, message);
}
/**
* 读取完毕之后的操作
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
super.channelReadComplete(ctx);
}
/**
* 发生异常的操作
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
logger.debug(cause.getMessage());
}
}
哦吼,欢迎指正。