【发布时间】:2014-05-28 22:48:53
【问题描述】:
我正在尝试按照示例 here 使用 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() 的阻塞调用期间,我没有看到我的应用程序正在侦听指定的接口。我尝试运行示例(直接从主函数设置服务器)并且它可以工作。我没有找到使用 Netty 和 Spring 设置 UDP 服务器的示例。
谢谢,米凯尔
编辑:
为了避免阻塞主线程(用于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 配置。但是还是不行。
【问题讨论】: