【问题标题】:How to use one single Bootstrap to connect to multiple servers in Netty如何使用一个 Bootstrap 连接到 Netty 中的多个服务器
【发布时间】:2013-12-05 22:06:00
【问题描述】:

如果我每次连接到远程服务器时都创建(新)引导程序,我不知道是否存在性能问题。所以我想使用一个引导实例连接到多个服务器。我的代码如下:

Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup()).handler(new TestHandler()).channel(NioSocketChannel.class)
        .option(ChannelOption.AUTO_READ, false);
ChannelFutureListener listener = new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
            // connection complete start to read first data
            System.out.println("connection established + channel: " + future.channel());
        } else {
            // Close the connection if the connection attempt has failed.
            System.out.println("connection failed");
        }
    }
};

String[] urls = { "www.google.com", "www.stackoverflow.com", "www.yahoo.com" };
for (String s : urls) {
    b = b.clone();
    b.remoteAddress(s, 80);
    b.connect().addListener(listener);
}
System.in.read();

不幸的是,它崩溃了:

connection established + channel: [id: 0x5df86eec, /192.168.126.136:60414 => www.google.com/173.194.127.209:80]
Exception in thread "main" java.lang.IllegalStateException: channel not registered to an event loop
    at io.netty.channel.AbstractChannel.eventLoop(AbstractChannel.java:107)
    at io.netty.channel.nio.AbstractNioChannel.eventLoop(AbstractNioChannel.java:102)
    at io.netty.channel.nio.AbstractNioChannel.eventLoop(AbstractNioChannel.java:41)
    at io.netty.channel.CompleteChannelFuture.executor(CompleteChannelFuture.java:48)
    at io.netty.util.concurrent.CompleteFuture.addListener(CompleteFuture.java:49)
    at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:56)
    at Test3.main(Test3.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

我认为我以错误的方式使用引导程序。如果是这样,我应该每次都创建一个全新的引导程序吗?

至少,我应该使用相同的 NioEventLoopGroup,对吧?

【问题讨论】:

    标签: java netty


    【解决方案1】:

    好吧,这是我的错,我忘记添加 ChannelInitializer。将其更改为以下代码:

    b.group(new NioEventLoopGroup()).handler(new ChannelInitializer<NioSocketChannel>() {
    
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TestHandler());
                }
            })
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 2020-12-12
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多