/**
* Thrif代理客户端
* @author hz_feng
*
*/
public class ThriftProxyClient implements InvocationHandler {
//Client类
private Class clientClass;
//Service类
private Class classs;
private String[] hostPorts;
public Object newInstance(Class classs, String[] hostPorts) {
try {
this.clientClass = Class.forName(classs.getName() + "$Client");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
this.classs = classs;
this.hostPorts = hostPorts;
return Proxy.newProxyInstance(clientClass.getClassLoader(), clientClass.getInterfaces(), this);
}
@Override
public Object invoke(Object obj, Method method, Object[] objs) throws Throwable {
if (null != hostPorts && hostPorts.length > 0) {
for (String hostPort : hostPorts) {
if (null != hostPort && "" != hostPort.trim()) {
TSocket socket = null;
try {
int index = hostPort.indexOf(":");
String host = hostPort.substring(0, index);
String port = hostPort.substring(index+1, hostPort.length());
socket = new TSocket(host, Integer.valueOf(port));
TProtocol tProtocol = new TBinaryProtocol(socket);
TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(tProtocol, classs.getSimpleName());
Class[] classes = new Class[]{TProtocol.class};
socket.open();
return method.invoke(clientClass.getConstructor(classes).newInstance(multiplexedProtocol), objs);
} finally {
if (null != socket) {
socket.close();
}
}
}
}
}
return null;
}
}
/**
* Thrift代理工厂
* @author hz_feng
*
*/
public class ThriftProxyFactory {
public static Object newInstance(Class classT, String[] hostPorts) {
ThriftProxyClient thriftProxy = new ThriftProxyClient();
return thriftProxy.newInstance(classT, hostPorts);
}
}
/**
* 测试
* @author hz_feng
*
*/
public class TestThriftClient {
public static void main(String[] args) {
String[] hostPorts = new String[]{"192.168.10.75:9010"};
Map<String,String> map = new HashMap<String,String>();
map.put("name", "lessly");
UserRMIServices.Iface userService = (Iface) ThriftProxyFactory.newInstance(UserRMIServices.class, hostPorts);
// UserRMIServices.AsyncIface userService = (AsyncIface) ThriftProxyFactory.newInstance(UserRMIServices.class, hostPorts);
try {
ReturnData resultData = userService.userLogin(map);
System.out.println(new Gson().toJson(resultData));
} catch (TException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thrift动态代理客户端
于 2017-04-10 14:52:10 首次发布