spring整合netty无法注入bean的问题解决

转载:https://blog.csdn.net/qq_29807745/article/details/82779884

作者在使用netty集成spring注入调用时普通的@Autowired一直bean注入为null,这里我只是记录针对netty注入spring无法注入bean的解决发放,具体底层实现,希望大神不吝赐教

首先上解决代码块,copy过去就可以直接用

@Component
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
 
 
    public static NettyWebSocketServerHandler nettyWebSocketServerHandler;
 
    //1.正常注入[记得主类也需要使用@Component注解]
    @Autowired
    private IUserInfoService appUserService;
    @Autowired
    private IUserCoinRecordService userCoinRecordService;
 
    //2.初始化构造方法一定要有
    public NettyWebSocketServerHandler() {
 
    }
 
    //3.容器初始化的时候进行执行-这里是重点
    @PostConstruct
    public void init() {
        nettyWebSocketServerHandler = this;
        nettyWebSocketServerHandler.appUserService = this.appUserService;
        nettyWebSocketServerHandler.userCoinRecordService = this.userCoinRecordService;
    }
 
    /**
     * 管道初始化
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到消息: " + msg.text());
        String info = DataParamsComm.analysisData(msg.text());
        System.out.println("解密数据:" + info);
        //4.这里是调用方法需要通过另一个bean去调用,你真正使用的bean
System.out.println(nettyWebSocketServerHandler.appUserService.findByUserId(500001L));
        ctx.channel().writeAndFlush(new TextWebSocketFrame("接收到的内容: " + JSON.toJSONString(nettyWebSocketServerHandler.appUserService.findByUserId(500001L))));
 
    }
}
这样就解决了spring整合netty无法注入bean的问题,现在bean在netty中正常的业务调用了
 

SpringNetty都是非常流行的Java框架,它们可以很好地结合使用。Spring提供了依赖注入和面向切面编程等功能,而Netty则提供了高性能的网络通信能力。下面是SpringNetty整合的步骤: 1. 引入Netty依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> ``` 2. 创建Netty服务器 创建一个Netty服务器,监听指定端口,接收客户端请求,并将请求转发给Spring容器处理。以下是一个简单的Netty服务器示例: ``` public class NettyServer { private int port; private ApplicationContext context; public NettyServer(int port, ApplicationContext context) { this.port = port; this.context = context; } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ObjectEncoder()); pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); pipeline.addLast(new NettyServerHandler(context)); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 3. 创建Netty服务器处理器 创建一个Netty服务器处理器,用于接收客户端请求并将请求转发给Spring容器处理。以下是一个简单的Netty服务器处理器示例: ``` public class NettyServerHandler extends ChannelInboundHandlerAdapter { private ApplicationContext context; public NettyServerHandler(ApplicationContext context) { this.context = context; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Request) { Request request = (Request) msg; Object result = handleRequest(request); ctx.write(result); } } private Object handleRequest(Request request) { // 将请求转发给Spring容器处理 // ... } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 4. 创建Spring容器 创建一个Spring容器,用于处理客户端请求。以下是一个简单的Spring容器示例: ``` @Configuration @ComponentScan("com.example") public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } ``` 5. 启动Netty服务器和Spring容器 在应用程序的入口处,启动Netty服务器和Spring容器。以下是一个简单的应用程序示例: ``` public class App { public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); NettyServer server = new NettyServer(8080, context); server.start(); } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值