use of com.bonree.brfs.common.net.tcp.client.TcpClientCloseListener in project BRFS by zhangnianli.
the class ConnectionPool method getConnection.
@SuppressWarnings("unchecked")
public TcpClient<ReadObject, FileContentPart> getConnection(Service service) {
TcpClient<ReadObject, FileContentPart>[] clients = clientCache.get(service.getServiceId());
TcpClient<ReadObject, FileContentPart> client = null;
int index = random.nextInt(connectionPerRoute);
if (clients == null) {
clientCache.putIfAbsent(service.getServiceId(), (TcpClient<ReadObject, FileContentPart>[]) Array.newInstance(TcpClient.class, connectionPerRoute));
clients = clientCache.get(service.getServiceId());
}
client = clients[index];
if (client != null) {
return client;
}
synchronized (clients) {
if (clients[index] != null) {
return clients[index];
}
try {
client = group.createClient(new AsyncFileReaderCreateConfig() {
@Override
public SocketAddress remoteAddress() {
return new InetSocketAddress(service.getHost(), service.getExtraPort());
}
@Override
public int connectTimeoutMillis() {
return 3000;
}
@Override
public int maxPendingRead() {
return 1000 * 100;
}
});
if (client == null) {
return null;
}
client.setClientCloseListener(new TcpClientCloseListener() {
@Override
public void clientClosed() {
TcpClient<ReadObject, FileContentPart>[] clientArray = clientCache.get(service.getServiceId());
synchronized (clientArray) {
clientArray[index] = null;
}
}
});
clients[index] = client;
return client;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
Aggregations