我需要开发一个返回通道的 Netty 连接池,这样我就可以避免每次需要时都创建通道。客户端应该每秒通过 Http 发出多个请求,并从一组 10 个线程中执行。目前我已经创建了一个 Netty Channel Pool,它围绕这个机制工作,但它似乎没有连接。
(虽然它产生了频道,但频道无法在网络上成功“写入”。
//Code follows
//get Channel method
public Channel getChannel() throws Exception
{
synchronized (_channels) {
PoolChannel pc = null;
for (int i = 0; i < _channels.size(); i++) {
pc = _channels.get(i);
if (pc.lease()) {
// PoolConnection is available
if (!_checkChannels) {
return pc;
}
else {
// Check the status of the connection
boolean isHealthy = true;
try {
if (!pc.isOpen()) {
// If something wrong with the channel
// then don't use it anymore.
isHealthy = false;
}
}
catch(Exception ex) {
// If we can't even ask for that information, we
// certainly don't want to use it anymore.
isHealthy = false;
}
if (isHealthy) {
return pc;
}
else {
try {
pc.expire();
}
catch(Exception e) {
// ignore
}
_channels.remove(i);
}
}
}
}
}
// Create a new Connection
PoolChannel pc=null;
URI uri = _uri;
String host = _host;
int port = _port;
//create channel
Executor bossPool = Executors.newCachedThreadPool();
Executor workerPool = Executors.newCachedThreadPool();
ClientBootstrap bstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
bossPool, workerPool));
bstrap.setPipelineFactory(new HttpClientPipelineFactory());
ChannelFuture future = bstrap.connect(new InetSocketAddress(host, port));
Channel chann = future.awaitUninterruptibly().getChannel();
if (future.isSuccess()) {
System.out.println("Channel success");
}
System.out.println("Channel = "+chann);
pc = new PoolChannel(chann);
pc.lease();
// Add it to the pool
synchronized (_channels) {
_channels.add(pc);
if (_cleaner == null) {
// Put a new PoolCleaner
_cleaner = new PoolCleaner(_cleaningInterval);
_cleaner.start();
}
}
return pc;
}
//===========================
请问我可以得到帮助吗?另外,当我完成频道后,如何将此频道返回到池中?仅仅关闭频道就足够了吗?提前致谢。