A thrift client pool implementation with AutoClosable, make easy for returning client to pool by using try-catch-resource.
- Client which disconnected to server will be released from pool. A new client will be created if getObjectFromPool() is called.
- Thread-safe: If you use method 2 belows, client objects are thread-safe. Pool object is always thread-safe.
Gradle:
//for thrift ver 0.9.3
dependencies {
compile group: 'com.github.minhlong293', name: 'clientpool', version: '0.9.3-3'
}
//for thrift ver 0.11.0
dependencies {
compile group: 'com.github.minhlong293', name: 'clientpool', version: '0.11.0-3'
}
(see method1() in demo.client.DemoClientPool)
STEP 1: You must to implement BaseClient class to make it can be use with the pool. In CalcClientImpl.java:
public class CalcClientImpl extends BaseClient {
// this class has its own internal client which used to call thrift server
}
...
STEP 2: Use ClientPool for create a new pool instance. In DemoClientPool.java:
ClientPool<CalcClientImpl> pool = new ClientPool<>("localhost", 8888, CalcClientImpl::new);
STEP 3: Call pool.getObjectFromPool() in try-catch-resource block to get the client. In DemoClientPool.java:
//the pool object is thread-safe so you can use only one instance in your program
try (CalcClientImpl calcClient = pool.getObjectFromPool()) {
calcClient.sayHello();
}
(see method2() in demo.client.DemoClientPool)
Class com.github.minhlong293.thrift.clientwrapper.ClientWrapper takes care all implementation of methods from BaseClient. It uses a Java Proxy object for wrapping the real client, so we can handle all exceptions and make all methods synchronized.
//Create pool
ClientPool<ClientWrapper<Iface, Client>> clientPool = new ClientPool<>(
() -> new ClientWrapper<>(
() -> new TFramedTransport(new TSocket(HOST, PORT)),
tTransport -> new Client(new TBinaryProtocol(tTransport)),
Iface.class
));
// Get client
try (ClientWrapper<Iface, Client> clientWrapper = clientPool.getObjectFromPool()) {
Iface client = clientWrapper.getClient();
// the client object is an Iface, so you can call all functions define in Iface interface.
// it is thread-safe as wrapped by InvocationHandler, all methods is synchronized
}