使用Spring + Netty的UDP服务器

我正在尝试使用Netty设置一个简单的UDP服务器,遵循此处的示例,但使用Spring进行连接依赖。

我的Spring配置类:

@Configuration @ComponentScan("com.example.netty") public class SpringConfig { @Value("${netty.nThreads}") private int nThreads; @Autowired private MyHandlerA myHandlerA; @Autowired private MyHandlerB myHandlerB; @Bean(name = "bootstrap") public Bootstrap bootstrap() { Bootstrap b = new Bootstrap(); b.group(group()) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ch.pipeline().addLast(myHandlerA, myHandlerB); } }); return b; } @Bean(name = "group", destroyMethod = "shutdownGracefully") public NioEventLoopGroup group() { return new NioEventLoopGroup(nThreads); } @Bean public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } 

我的服务器类:

 @Component public class MyUDPServer { @Autowired private Bootstrap bootstrap; @Value("${host}") private String host; @Value("${port}") private int port; @PostConstruct public void start() throws Exception { bootstrap.bind(host, port).sync().channel().closeFuture().await(); /* Never reached since the main thread blocks due to the call to await() */ } } 

在阻塞调用await()期间,我没有看到我的应用程序在指定的接口上侦听。 我试图运行该示例(直接从主函数设置服务器),它的工作原理。 我没有找到使用Netty和Spring设置UDP服务器的示例。

谢谢,Mickael


编辑:

为了避免阻塞主线程(用于Spring配置),我创建了一个新线程,如下所示:

 @Component public class MyUDPServer extends Thread { @Autowired private Bootstrap bootstrap; @Value("${host}") private String host; @Value("${port}") private int port; public MyUDPServer() { setName("UDP Server"); } @PostConstruct @Override public synchronized void start() { super.start(); } @Override public void run() { try { bootstrap.bind(host, port).sync().channel().closeFuture().await(); } catch (InterruptedException e) { } finally { bootstrap.group().shutdownGracefully(); } } @PreDestroy @Override public void interrupt() { super.interrupt(); } } 

我可以看到新线程被阻塞等待Channel关闭(如示例中所示)。 主线程可以继续Spring配置。 但是,它仍然无效。

无需等待@PostConstruct中的通道终止。 尝试删除await()