Thrift动态代理客户端

/**
 * 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();
		}
	}
	
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值