com.lowdad.thrift.client.AbstractThriftClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rpc-client Show documentation
Show all versions of rpc-client Show documentation
RPC client for k8s services
The newest version!
package com.lowdad.thrift.client;
import com.lowdad.thrift.client.config.RpcClientProperties;
import com.lowdad.thrift.client.func.ThriftCallFunc;
import com.lowdad.thrift.client.func.ThriftExecFunc;
import com.lowdad.thrift.client.config.TraceBinaryProtocol.Factory;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.TServiceClientFactory;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import java.util.concurrent.*;
/**
* @author lowdad
*/
@Slf4j
public abstract class AbstractThriftClient implements ThriftClient {
private Class> thriftClass;
private static final Factory protocolFactory = new Factory();
private TServiceClientFactory clientFactory;
// For async call
private ExecutorService threadPool;
public void init() {
try {
clientFactory = getThriftClientFactoryClass().newInstance();
log.info("[RPC] client init");
} catch (Exception e) {
throw new RuntimeException();
}
if (!check()) {
throw new RuntimeException("[RPC] Client config failed check!");
}
threadPool = new ThreadPoolExecutor(
Integer.valueOf(
RpcClientProperties.getInstance().getThreadPool().getCoreSize()),
Integer.valueOf(RpcClientProperties.getInstance().getThreadPool().getMaxSize()),
Integer.valueOf(RpcClientProperties.getInstance().getThreadPool().getKeepAlive()),
TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>());
log.info("[RPC] client threadPool init ");
}
protected boolean check() {
if (thriftClass == null) {
return false;
}
return true;
}
@Override
public Future asyncCall(ThriftCallFunc tcall) {
return threadPool.submit(() -> this.call(tcall));
}
@Override
public Future> asyncExec(ThriftExecFunc texec) {
return threadPool.submit(() -> this.exec(texec));
}
protected TCLIENT createClient(TTransport transport) throws Exception {
// Step 1: get TProtocol
TProtocol protocol = protocolFactory.getProtocol(transport);
// Step 2: get client
return clientFactory.getClient(protocol);
}
private Class> getThriftClientFactoryClass() {
Class clientClazz = getThriftClientClass();
if (clientClazz == null) {
return null;
}
for (Class> clazz : clientClazz.getDeclaredClasses()) {
if (TServiceClientFactory.class.isAssignableFrom(clazz)) {
return (Class>) clazz;
}
}
return null;
}
private Class getThriftClientClass() {
for (Class> clazz : thriftClass.getDeclaredClasses()) {
if (TServiceClient.class.isAssignableFrom(clazz)) {
return (Class) clazz;
}
}
return null;
}
public void setThriftClass(Class> thriftClass) {
this.thriftClass = thriftClass;
}
}