【问题标题】:UDP server using Spring+Netty使用 Spring+Netty 的 UDP 服务器
【发布时间】: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 配置。但是还是不行。

【问题讨论】:

    标签: java spring netty


    【解决方案1】:

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

    【讨论】:

    • 请看我的编辑。请注意,它在我运行示例时有效。好像有什么东西在阻止绑定。
    • 在我的编辑之后,我尝试直接在 MyUDPServer 构造函数中创建引导程序,它现在可以工作了。我还是不明白为什么。
    猜你喜欢
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2019-03-26
    • 2012-11-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多