com.lowdad.thrift.client.NormalThriftClient 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.error.RpcServiceExcepiton;
import com.lowdad.thrift.client.func.ThriftCallFunc;
import com.lowdad.thrift.client.func.ThriftExecFunc;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
/**
* @author lowdad
*/
public class NormalThriftClient extends AbstractThriftClient {
protected String thriftServerHost;
protected int thriftServerPort;
@Override
protected boolean check() {
if (thriftServerHost == null || thriftServerHost.isEmpty()) {
return false;
}
if (thriftServerPort <= 0) {
return false;
}
return super.check();
}
private TTransport borrowTransport() throws Exception {
TSocket socket = new TSocket(thriftServerHost, thriftServerPort, Integer.valueOf(RpcClientProperties.getInstance().getTimeOut()));
TTransport transport = new TFramedTransport(
socket, Integer.valueOf(RpcClientProperties.getInstance().getMaxFrameSize()));
transport.open();
return transport;
}
private void returnTransport(TTransport transport) {
if (transport != null && transport.isOpen()) {
transport.close();
}
}
private void returnBrokenTransport(TTransport transport) {
if (transport != null && transport.isOpen()) {
transport.close();
}
}
@Override
public TRET call(ThriftCallFunc tcall) {
// Step 1: get TTransport
TTransport tpt = null;
try {
tpt = borrowTransport();
} catch (Exception e) {
throw new RpcServiceExcepiton(e);
}
// Step 2: get client & call
try {
TCLIENT tcli = createClient(tpt);
TRET ret = tcall.call(tcli);
returnTransport(tpt);
return ret;
} catch (Exception e) {
returnBrokenTransport(tpt);
throw new RpcServiceExcepiton(e);
}
}
@Override
public void exec(ThriftExecFunc texec) {
// Step 1: get TTransport
TTransport tpt = null;
try {
tpt = borrowTransport();
} catch (Exception e) {
throw new RpcServiceExcepiton(e);
}
// Step 2: get client & exec
try {
TCLIENT tcli = createClient(tpt);
texec.exec(tcli);
returnTransport(tpt);
} catch (Exception e) {
returnBrokenTransport(tpt);
throw new RpcServiceExcepiton(e);
}
}
public String getThriftServerHost() {
return thriftServerHost;
}
public void setThriftServerHost(String thriftServerHost) {
this.thriftServerHost = thriftServerHost;
}
public int getThriftServerPort() {
return thriftServerPort;
}
public void setThriftServerPort(int thriftServerPort) {
this.thriftServerPort = thriftServerPort;
}
}