使用 Netty 的多线程 UDP 服务器

2023-12-28

我正在尝试使用 Netty 实现 UDP 服务器。这个想法是只绑定一次(因此只创建一个Channel). This Channel仅使用一个处理程序进行初始化,该处理程序通过一个线程在多个线程之间分派传入数据报的处理ExecutorService.

@Configuration
public class SpringConfig {

    @Autowired
    private Dispatcher dispatcher;

    private String host;

    private int port;

    @Bean
    public Bootstrap bootstrap() throws Exception {
        Bootstrap bootstrap = new Bootstrap()
            .group(new NioEventLoopGroup(1))
            .channel(NioDatagramChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(dispatcher);

        ChannelFuture future = bootstrap.bind(host, port).await();
        if(!future.isSuccess())
            throw new Exception(String.format("Fail to bind on [host = %s , port = %d].", host, port), future.cause());

        return bootstrap;
    }
}

@Component
@Sharable
public class Dispatcher extends ChannelInboundHandlerAdapter implements InitializingBean {

    private int workerThreads;

    private ExecutorService executorService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        DatagramPacket packet = (DatagramPacket) msg;

        final Channel channel = ctx.channel();

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                //Process the packet and produce a response packet (below)              
                DatagramPacket responsePacket = ...;

                ChannelFuture future;
                try {
                    future = channel.writeAndFlush(responsePacket).await();
                } catch (InterruptedException e) {
                    return;
                }
                if(!future.isSuccess())
                    log.warn("Failed to write response packet.");
            }
        });
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        executorService = Executors.newFixedThreadPool(workerThreads);
    }
}

我有以下问题:

  1. 应该DatagramPacket收到的channelRead的方法Dispatcher类在被工作线程使用之前被复制?我想知道这个包在之后是否被销毁channelRead即使工作线程保留了引用,方法也会返回。
  2. 分享安全吗Channel在所有工作线程中并让它们调用writeAndFlush同时?

Thanks!


  1. 没有。如果您需要该物体寿命更长,您可以将其变成其他东西或使用ReferenceCountUtil.retain(datagram)进而ReferenceCountUtil.release(datagram)一旦你完成了它。你也不应该这样做await()同样在执行程序服务中,您应该为发生的任何情况注册一个处理程序。

  2. 是的,通道对象是线程安全的,可以从许多不同的线程调用它们。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Netty 的多线程 UDP 服务器 的相关文章

随机推荐