netty建立數萬客戶端連線,並主動發訊息

陈鸿圳發表於2024-05-27
@Slf4j
public class NettyClientTest
{
    public static void main(String[] args) throws Exception
    {
        EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerEventLoopGroup)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .channel(NioSocketChannel.class)
                    .handler(new MyClientChannelInitializer());

            List<Channel> channels = new ArrayList<>();
            for( int i=0; i<60000; i++ ){    // 這裡建立60000個連線,實驗時建立了兩萬多個連線就報錯了
                log.info("count: {}", i);
                channels.add(bootstrap.connect("localhost", 8080).sync().channel());
            }

            schedule(channels);

            for( Channel channel : channels ){
                channel.closeFuture().sync();
            }
        } finally {
            // 6. 關閉工作執行緒組
            workerEventLoopGroup.shutdownGracefully();
        }
    }

    private static void schedule(List<Channel> channels){
        // 啟動一個執行緒來不斷讓客戶發訊息給服務端
        new Thread(new MyScheduleRunnable(channels)).start();
    }

    private static class MyScheduleRunnable implements Runnable {

        private List<Channel> channels;
        private Random random = new Random();

        public MyScheduleRunnable(List<Channel> channels)
        {
            this.channels = channels;
        }

        @Override
        public void run() {
            int seq = 0;
            while(true){
                try {
                    Thread.sleep(1000L);

                    int index = random.nextInt(channels.size());
                    Channel channel = channels.get(index);
                    // 呼叫channel.pipeline的方法寫資料出去,channel是執行緒安全的
                    channel.pipeline().writeAndFlush(""+(seq++));    

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

相關文章