[英]UDP server using Spring+Netty
我试图按照此处的示例使用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<DatagramChannel>() {
@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()的阻塞调用期间,我看不到我的应用程序在指定的接口上侦听。 我尝试运行该示例(直接从main函数设置服务器),并且可以正常运行。 我没有找到使用Netty和Spring设置UDP服务器的示例。
谢谢,Mickael
编辑:
为了避免阻塞Main线程(用于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();
}
}
我可以看到新线程被阻塞,等待通道关闭(如示例中所示)。 Main线程可以继续Spring配置。 但是,它仍然不起作用。
无需等待@PostConstruct
中的通道终止。 尝试删除await()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.