Java Netty客户端相对于I/O客户端的优势?
我想知道是否可以通过实现Netty客户端来保存应用程序线程 我写了一个演示客户端,请找到下面的代码。期望一个线程可以连接到不同的端口来有效地处理它们,但我错了。Netty创建每线程连接Java Netty客户端相对于I/O客户端的优势?,java,multithreading,network-programming,netty,Java,Multithreading,Network Programming,Netty,我想知道是否可以通过实现Netty客户端来保存应用程序线程 我写了一个演示客户端,请找到下面的代码。期望一个线程可以连接到不同的端口来有效地处理它们,但我错了。Netty创建每线程连接 public class NettyClient { public static void main(String[] args) { Runnable runA = new Runnable() { public void run() { Connect(
public class NettyClient {
public static void main(String[] args) {
Runnable runA = new Runnable() {
public void run() {
Connect(5544);
}
};
Thread threadA = new Thread(runA, "threadA");
threadA.start();
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
Runnable runB = new Runnable() {
public void run() {
Connect(5544);
}
};
Thread threadB = new Thread(runB, "threadB");
threadB.start();
}
static ClientBootstrap bootstrap = null;
static NettyClient ins = new NettyClient();
public NettyClient() {
bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
/*
* ClientBootstrap A helper class which creates a new client-side
* Channel and makes a connection attempt.
*
* NioClientSocketChannelFactory A ClientSocketChannelFactory which
* creates a client-side NIO-based SocketChannel. It utilizes the
* non-blocking I/O mode which was introduced with NIO to serve many
* number of concurrent connections efficiently
*
* There are two types of threads :Boss thread Worker threads Boss
* Thread passes control to worker thread.
*/
// Configure the client.
ChannelGroup channelGroup = new DefaultChannelGroup(NettyClient.class.getName());
// Only 1 thread configured but still aceepts threadA and Thread B
// connection
OrderedMemoryAwareThreadPoolExecutor pipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor(
1, 1048576, 1073741824, 1, TimeUnit.MILLISECONDS,
new NioDataSizeEstimator(), new NioThreadFactory("NioPipeline"));
bootstrap.setPipelineFactory(new NioCommPipelineFactory(channelGroup,
pipelineExecutor));
// bootstrap.setPipelineFactory(new
// BackfillClientSocketChannelFactory());
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("readWriteFair", true);
}
public static NettyClient getins() {
return ins;
}
public static void Connect(int port) {
ChannelFuture future = bootstrap
.connect(new InetSocketAddress("localhost", port));
Channel channel = future.awaitUninterruptibly().getChannel();
System.out.println(channel.getId());
channel.getCloseFuture().awaitUninterruptibly();
}
}
现在我想知道使用Netty客户端的好处是什么?它能保存线程吗 Netty保存线程。您的NetCyclient在同步等待连接的打开和关闭(调用awaitUnterruptibly())时会浪费线程
顺便问一下,您的客户将有多少个连接?也许使用经典的同步每个连接一个线程的方法就足够了?通常我们必须在服务器端保存线程。Netty允许您使用少量线程处理数千个连接。 在客户端应用程序中使用时,它允许少数线程与服务器建立数千个并发连接 您已将sleep()放在线程中。我们必须决不阻挡烦躁的工人/老板的思路。即使需要执行任何一次性阻塞操作,也必须将其卸载到另一个执行器。Netty使用NIO,同一线程可用于创建新连接,而先前的连接在其输入缓冲区中获取一些数据