package cn.hhj.proxy.remote; import cn.hhj.disovery.IServiceDiscovery; import cn.hhj.request.RpcRequest; import cn.hhj.rpcsend.RpcNetTransport; import org.springframework.util.StringUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.List; public class RemoteInvocationHandler implements InvocationHandler { private IServiceDiscovery serviceDiscovery; private String version; public RemoteInvocationHandler(IServiceDiscovery serviceDiscovery, String version) { this.serviceDiscovery = serviceDiscovery; this.version = version; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 进行请求数据的包装 RpcRequest request=new RpcRequest(); request.setClassName(method.getDeclaringClass().getName()); request.setMethodName(method.getName()); request.setParamTypes(method.getParameterTypes()); request.setParameters(args); request.setVersion(version); String serviceName=request.getClassName(); if(!StringUtils.isEmpty(version)){ serviceName=serviceName+"-"+version; } List serviceAddress=serviceDiscovery.discovery(serviceName); RpcNetTransport rnt=new RpcNetTransport(serviceAddress); Object result=rnt.send(request); System.err.println("【client】:远程通信,需要调用的接口是:"+serviceName); return result; } }