带有 Netty 的多线程 UDP 服务器

Mic*_*che 4 java multithreading udp netty

我正在尝试用 Netty 实现一个 UDP 服务器。这个想法是只绑定一次(因此只创建一个Channel)。这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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有以下问题:

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

谢谢!

Mau*_*res 5

  1. 不。如果您需要使对象寿命更长,您可以将其变成其他东西或使用ReferenceCountUtil.retain(datagram),然后ReferenceCountUtil.release(datagram)在完成后使用。你也不应该await()在 executor 服务上做,你应该为发生的任何事情注册一个处理程序。

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