你是不是启动 netty 阻塞了 main 啊,用一个新的线程启动 netty 就好了。我之前在 spring boot 中集成 netty 做 websocket 聊天,是在 spring 容器刷新后,再用新线程启动 netty 服务。下面的事例代码可以参考下:
/**
* spring 容器刷新时启动 netty 的 WebSocket 服务
*
* Created by xuan on 2018/3/5
*/
@
Componentpublic class ApplicationRefreshListener implements ApplicationListener<ContextStartedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationRefreshListener.class);
private ExecutorService webSocketSinglePool;
@
PostConstruct public void setup() {
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("webSocketSinglePool-%d").build();
webSocketSinglePool = new ThreadPoolExecutor(1, 1, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),
namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
LOG.info("webSocketSinglePool init.");
}
@
Override public void onApplicationEvent(ContextRefreshedEvent event) {
runWebSocketServer(event.getApplicationContext());
}
private void runWebSocketServer(ApplicationContext applicationContext) {
final WebSocketServer webSocketServer = applicationContext.getBean(WebSocketServer.class);
webSocketSinglePool.execute(() -> {
try {
webSocketServer.listenAndServe();
} catch (Exception e) {
LOG.error("webSocket listen and serve error.", e);
}
});
}
@
PreDestroy public void cleanup() {
webSocketSinglePool.shutdown();
LOG.info("webSocketSinglePool destroyed.");
}
}