目的
解决springboot程序监听的端口和netty服务监听的端口无法同时开启的问题,以及netty无法较为便利地使用mybatis操作数据库的问题。
背景描述
正在做的一个IM即时通讯项目,springboot服务器负责监听http的CRUD等请求,netty的websocket服务器负责即时聊天消息的签收和推送功能。常见的两种springboot整合netty的方法如下:
1、单独写一个main方法,运行netty server,这样的话需要启动两次,分别启动springboot和netty server启动类,而且此时netty server没办法使用spring容器中的bean用mybatis进行CRUD,只能使用JDBC来操作数据库。
2、在netty server的启动方法上面使用 @PostConstruct 的注解,在bean的依赖注入完成后会自动执行该注解标注的方法,同时netty server类和相关handler类上也需要标注 @component 和 handler类上的 @Sharable注解。
但此时启动springboot,netty服务能正常启动并监听websocket端口,netty server也能正常注入spring容器中的bean,可是springboot监听的端口会被覆盖,无法访问。
@Component
public class WebSockerServer {
@PostConstruct
public void runNettyServer() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
//......
}
}
@Component
@Sharable
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
@Autowired
private ChatChannelHandler chatChannelHandler;
}
解决方法
1、netty server类实现Runnable接口,重写run( ) 方法,在run( ) 方法内部启动netty server。
@Component("WebSocketServer")
public class WebSockerServer implements Runnable {
@Autowired
private NettyChannelInitializer nettyChannelInitializer;
@Override
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
......
}
}
2、在springboot启动类中从spring容器中获取netty server的bean,创建线程池然后执行execute( )方法开启netty server线程。
@EnableOpenApi
@SpringBootApplication
@MapperScan("com.duke.chatapp.dao")
public