前两篇文章 Dubbo的服务导出1之导出到本地、Dubbo的服务导出2之导出到远程 详细分析了服务导出的过程,本篇文章咱们趁热打铁,继续分析服务引用过程。在 Dubbo 中,咱们能够经过两种方式引用远程服务。第一种是使用服务直连的方式引用服务
,第二种方式是基于注册中心进行引用
。服务直连的方式仅适合在调试或测试服务的场景下使用,不适合在线上环境使用。所以,本文我将重点分析经过注册中心引用服务的过程。从注册中心中获取服务配置只是服务引用过程当中的一环,除此以外,服务消费者还须要经历 Invoker 建立、代理类建立等步骤。这些步骤,将在后续章节中一一进行分析。java
Dubbo 服务引用的时机有两个,第一个是在Spring 容器调用 ReferenceBean的afterPropertiesSet方法时引用服务
,第二个是在 ReferenceBean对应的服务被注入到其余类中时引用
。这两个引用服务的时机区别在于,第一个是饿汉式的,第二个是懒汉式的。默认状况下,Dubbo使用懒汉式引用服务
。若是须要使用饿汉式,可经过配置 <dubbo:reference> 的 init 属性开启。下面咱们按照 Dubbo 默认配置进行分析,整个分析过程从 ReferenceBean 的 getObject 方法
开始。当咱们的服务被注入到其余类中时,Spring 会第一时间调用 getObject 方法,并由该方法执行服务引用逻辑。按照惯例,在进行具体工做以前,需先进行配置检查与收集工做。接着根据收集到的信息决定服务用的方式,有三种,第一种是引用本地 (JVM) 服务
,第二是经过直连方式引用远程服务
,第三是经过注册中心引用远程服务
。不论是哪一种引用方式,最后都会获得一个 Invoker 实例。若是有多个注册中心,多个服务提供者,这个时候会获得一组 Invoker 实例,此时须要经过集群管理类 Cluster 将多个 Invoker 合并成一个实例。合并后的 Invoker 实例已经具有调用本地或远程服务的能力了,但并不能将此实例暴露给用户使用,这会对用户业务代码形成侵入。此时框架还须要经过代理工厂类 (ProxyFactory) 为服务接口生成代理类,并让代理类去调用 Invoker 逻辑。避免了 Dubbo 框架代码对业务代码的侵入,同时也让框架更容易使用。
以上就是服务引用的大体原理,下面咱们深刻到代码中,详细分析服务引用细节。apache
// ReferenceBean实现了InitializingBean接口,所以在Spring容器初始化时会调用该方法,这里也对应上述第一个引用时机 // 默认不会走这里的引用服务方法,须要配置init=true @Override public void afterPropertiesSet() throws Exception { // 删除一些代码 // Dubbo服务引用的时机有两个,第一个是在Spring容器调用ReferenceBean的afterPropertiesSet // 方法时引用服务,第二个是在ReferenceBean对应的服务被注入到其余类中时引用.这两个引用服务的时机 // 区别在于,第一个是饿汉式的,第二个是懒汉式的.默认状况下,Dubbo使用懒汉式引用服务.若是须要使用 // 饿汉式,可经过配置<dubbo:reference>的init属性开启. Boolean b = isInit(); if (b == null && getConsumer() != null) { b = getConsumer().isInit(); } if (b != null && b.booleanValue()) { getObject(); } }
/** * 整个分析过程从ReferenceBean的getObject方法开始.当咱们的服务被注入到其余类中时, * Spring会第一时间调用getObject方法,并由该方法执行服务引用逻辑 */ @Override public Object getObject() throws Exception { return get(); } public synchronized T get() { if (destroyed) { throw new IllegalStateException("Already destroyed!"); } // 检测ref是否为空,为空则经过init方法建立 if (ref == null) { // init方法主要用于处理配置,以及调用createProxy生成代理类 init(); } return ref; }
init方法比较长,为了排版,分红几段,并删除异常捕捉、日志记录等代码,核心代码是ref = createProxy(map)
。segmentfault
private void init() { // 避免重复初始化 if (initialized) { return; } initialized = true; // 检查接口合法性 if (interfaceName == null || interfaceName.length() == 0) { throw new IllegalStateException("xxx"); } // 获取consumer的全局配置 checkDefault(); appendProperties(this); if (getGeneric() == null && getConsumer() != null) { setGeneric(getConsumer().getGeneric()); }
// 检测是否为泛化接口 if (ProtocolUtils.isGeneric(getGeneric())) { interfaceClass = GenericService.class; } else { try { // 加载类 interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() .getContextClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } checkInterfaceAndMethods(interfaceClass, methods); }
// 从系统变量中获取与接口名对应的属性值 String resolve = System.getProperty(interfaceName); String resolveFile = null; if (resolve == null || resolve.length() == 0) { // 从系统属性中获取解析文件路径 resolveFile = System.getProperty("dubbo.resolve.file"); // 从指定位置加载配置文件 if (resolveFile == null || resolveFile.length() == 0) { File userResolveFile = new File(new File(System.getProperty("user.home")), "dubbo-resolve.properties"); if (userResolveFile.exists()) { // 获取文件绝对路径 resolveFile = userResolveFile.getAbsolutePath(); } }
if (resolveFile != null && resolveFile.length() > 0) { Properties properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(new File(resolveFile)); // 从文件中加载配置 properties.load(fis); } // 获取与接口名对应的配置 resolve = properties.getProperty(interfaceName); } } if (resolve != null && resolve.length() > 0) { // 将resolve赋值给url,用于点对点直连 url = resolve; }
if (consumer != null) { if (application == null) { application = consumer.getApplication(); } if (module == null) { module = consumer.getModule(); } if (registries == null) { registries = consumer.getRegistries(); } if (monitor == null) { monitor = consumer.getMonitor(); } } if (module != null) { if (registries == null) { registries = module.getRegistries(); } if (monitor == null) { monitor = module.getMonitor(); } }
if (application != null) { if (registries == null) { registries = application.getRegistries(); } if (monitor == null) { monitor = application.getMonitor(); } } // 检测Application合法性 checkApplication(); // 检测本地存根配置合法性 checkStubAndMock(interfaceClass); // 添加side、协议版本信息、时间戳和进程号等信息到map中,side表示处于哪一侧,目前是处于服务消费者侧 Map<String, String> map = new HashMap<String, String>(); Map<Object, Object> attributes = new HashMap<Object, Object>(); map.put(Constants.SIDE_KEY, Constants.CONSUMER_SIDE); map.put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion()); map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); }
// 非泛化服务 if (!isGeneric()) { // 获取版本 String revision = Version.getVersion(interfaceClass, version); if (revision != null && revision.length() > 0) { map.put("revision", revision); } // 获取接口方法列表,并添加到map中 String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); if (methods.length == 0) { map.put("methods", Constants.ANY_VALUE); } else { map.put("methods", StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ",")); } } map.put(Constants.INTERFACE_KEY, interfaceName); // 将ApplicationConfig、ConsumerConfig、ReferenceConfig等对象的字段信息添加到map中 appendParameters(map, application); appendParameters(map, module); appendParameters(map, consumer, Constants.DEFAULT_KEY); appendParameters(map, this);
// 形如com.alibaba.dubbo.demo.DemoService String prefix = StringUtils.getServiceKey(map); if (methods != null && !methods.isEmpty()) { // 遍历MethodConfig列表 for (MethodConfig method : methods) { appendParameters(map, method, method.getName()); String retryKey = method.getName() + ".retry"; // 检测map是否包含methodName.retry if (map.containsKey(retryKey)) { String retryValue = map.remove(retryKey); if ("false".equals(retryValue)) { // 添加剧试次数配置methodName.retries map.put(method.getName() + ".retries", "0"); } } // 添加MethodConfig中的“属性”字段到attributes // 好比onreturn、onthrow、oninvoke等 appendAttributes(attributes, method, prefix + "." + method.getName()); checkAndConvertImplicitConfig(method, map, attributes); } }
// 获取服务消费者ip地址 String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); if (hostToRegistry == null || hostToRegistry.length() == 0) { hostToRegistry = NetUtils.getLocalHost(); } else if (isInvalidLocalHost(hostToRegistry)) { throw new IllegalArgumentException(""); } map.put(Constants.REGISTER_IP_KEY, hostToRegistry); // 存储attributes到系统上下文中 StaticContext.getSystemContext().putAll(attributes); // 建立代理类,核心 ref = createProxy(map); // 根据服务名,ReferenceConfig,代理类构建ConsumerModel, // 并将ConsumerModel存入到ApplicationModel中 ConsumerModel consumerModel = new ConsumerModel(getUniqueServiceName(), this, ref, interfaceClass.getMethods()); ApplicationModel.initConsumerModel(getUniqueServiceName(), consumerModel); }
上述init()方法的核心代码是ref = createProxy(map),下面分析这个方法。缓存
// 从字面意思上来看,createProxy彷佛只是用于建立代理对象的,但实际上并不是如此, // 该方法还会调用其余方法构建以及合并Invoker实例 private T createProxy(Map<String, String> map) { URL tmpUrl = new URL("temp", "localhost", 0, map); final boolean isJvmRefer; if (isInjvm() == null) { // url配置被指定,则不作本地引用,我理解该url是用来作直连的 if (url != null && url.length() > 0) { isJvmRefer = false; } // 根据url的协议、scope以及injvm等参数检测是否须要本地引用 // 好比若是用户显式配置了scope=local,此时isInjvmRefer返回true else if (InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl)) { isJvmRefer = true; } else { isJvmRefer = false; } } else { // 获取injvm配置值 isJvmRefer = isInjvm().booleanValue(); }
// 本地引用 if (isJvmRefer) { // 生成本地引用URL,协议为injvm URL url = new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0, interfaceClass.getName()).addParameters(map); // 调用refer方法构建InjvmInvoker实例 invoker = refprotocol.refer(interfaceClass, url); }
// 远程引用 else { // url不为空,代表用户可能想进行点对点调用 if (url != null && url.length() > 0) { String[] us = Constants.SEMICOLON_SPLIT_PATTERN.split(url); if (us != null && us.length > 0) { for (String u : us) { URL url = URL.valueOf(u); if (url.getPath() == null || url.getPath().length() == 0) { url = url.setPath(interfaceName); } if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { urls.add(url.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } else { urls.add(ClusterUtils.mergeUrl(url, map)); } } } }
else { // 加载注册中心url List<URL> us = loadRegistries(false); if (us != null && !us.isEmpty()) { for (URL u : us) { URL monitorUrl = loadMonitor(u); if (monitorUrl != null) { map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString())); } // 添加refer参数到url中,并将url添加到urls中 urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map))); } } // 未配置注册中心,抛出异常 if (urls.isEmpty()) { // 抛异常 } }
// 单个注册中心或服务提供者(服务直连,下同) if (urls.size() == 1) { // 1. 调用RegistryProtocol的refer构建Invoker实例,普通状况下走这个逻辑 invoker = refprotocol.refer(interfaceClass, urls.get(0)); }
// 多个注册中心或多个服务提供者,或者二者混合 else { List<Invoker<?>> invokers = new ArrayList<Invoker<?>>(); URL registryURL = null; for (URL url : urls) { // 获取全部的Invoker,经过refprotocol调用refer构建Invoker,refprotocol会在运行时 // 根据url协议头加载指定的Protocol实例,并调用实例的refer方法 invokers.add(refprotocol.refer(interfaceClass, url)); if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { registryURL = url; } } // 若是注册中心连接不为空,则将使用AvailableCluster if (registryURL != null) { URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME); // 建立StaticDirectory实例,并由Cluster对多个Invoker进行合并 invoker = cluster.join(new StaticDirectory(u, invokers)); } else { invoker = cluster.join(new StaticDirectory(invokers)); } } }
Boolean c = check; if (c == null && consumer != null) { c = consumer.isCheck(); } if (c == null) { // default true c = true; } // invoker可用性检查 if (c && !invoker.isAvailable()) { // 抛异常 } // 2. 生成代理类,核心 // Invoker建立完毕后,接下来要作的事情是为服务接口生成代理对象.有了代理对象, // 便可进行远程调用.代理对象生成的入口方法为ProxyFactory的getProxy return (T) proxyFactory.getProxy(invoker); }
// 下面分析建立Invoker,单个注册中心或服务提供者(服务直连,下同) if (urls.size() == 1) { // 1. 调用RegistryProtocol的refer构建Invoker实例,普通状况下走这个逻辑 // 这里实际还会先走ProtocolFilterWrapper和ProtocolListenerWrapper的refer方法,不过总的逻辑不影响 invoker = refprotocol.refer(interfaceClass, urls.get(0)); }
// ProtocolFilterWrapper public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { // 走这里 return protocol.refer(type, url); } return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, Constants.CONSUMER); } // ProtocolListenerWrapper public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { // 走这里 return protocol.refer(type, url); } return new ListenerInvokerWrapper<T>(protocol.refer(type, url), Collections.unmodifiableList( ExtensionLoader.getExtensionLoader(InvokerListener.class) .getActivateExtension(url, Constants.INVOKER_LISTENER_KEY))); }
// 最终走到RegistryProtocol的refer方法 public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { // protocol为zookeeper,调试加的 String protocol = url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY); url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY); // 获取注册中心实例 Registry registry = registryFactory.getRegistry(url); // 这里的type是"" if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); }
// 将url查询字符串转为Map Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); // 获取group配置 String group = qs.get(Constants.GROUP_KEY); if (group != null && group.length() > 0) { if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { // 经过SPI加载MergeableCluster实例,并调用doRefer继续执行服务引用逻辑 return doRefer(getMergeableCluster(), registry, type, url); } } // 调用doRefer继续执行服务引用逻辑 return doRefer(cluster, registry, type, url); }
/** * doRefer方法建立一个RegistryDirectory实例,而后生成服务者消费者连接,并向注册中心进行注册. * 注册完毕后,紧接着订阅providers、configurators、routers 等节点下的数据.完成订阅后, * RegistryDirectory会收到这几个节点下的子节点信息.因为一个服务可能部署在多台服务器上, * 这样就会在providers产生多个节点,这个时候就须要Cluster将多个服务节点合并为一个, * 并生成一个Invoker. */ private <T> Invoker<T> doRefer(Cluster cluster, Registry registry, Class<T> type, URL url) { // 建立RegistryDirectory实例 RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url); // 设置注册中心和协议 directory.setRegistry(registry); directory.setProtocol(protocol); // all attributes of REFER_KEY Map<String, String> parameters = new HashMap<String, String>(directory.getUrl().getParameters()); // 生成服务消费者连接 URL subscribeUrl = new URL(Constants.CONSUMER_PROTOCOL, parameters.remove(Constants.REGISTER_IP_KEY), 0, type.getName(), parameters);
// 注册服务消费者,在consumers目录下新节点 if (!Constants.ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(Constants.REGISTER_KEY, true)) { registry.register( subscribeUrl.addParameters(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY, Constants.CHECK_KEY, String.valueOf(false))); } // 订阅providers、configurators、routers等节点数据 directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY + "," + Constants.CONFIGURATORS_CATEGORY + "," + Constants.ROUTERS_CATEGORY)); // 一个注册中心可能有多个服务提供者,所以这里须要将多个服务提供者合并为一个 Invoker invoker = cluster.join(directory); ProviderConsumerRegTable.registerConsumer(invoker, url, subscribeUrl, directory); return invoker; }
// cluster.join(directory)该方法会走进MockClusterWrapper的join方法中 public class MockClusterWrapper implements Cluster { private Cluster cluster; public MockClusterWrapper(Cluster cluster) { this.cluster = cluster; } /** * 它是一个Wrapper类,对其余如FailoverCluster包装了一层 */ @Override public <T> Invoker<T> join(Directory<T> directory) throws RpcException { return new MockClusterInvoker<T>(directory, this.cluster.join(directory)); } }
public class FailoverCluster implements Cluster { public final static String NAME = "failover"; @Override public <T> Invoker<T> join(Directory<T> directory) throws RpcException { // 接着走到这里,这里就会建立FailoverClusterInvoker,接下去没什么关键逻辑,这里就返回了一个Invoker return new FailoverClusterInvoker<T>(directory); } }
注意,最终返回的invoker是MockClusterInvoker服务器
// 一个注册中心可能有多个服务提供者,所以这里须要将多个服务提供者合并为一个 Invoker invoker = cluster.join(directory);
// 生成代理类,核心 // Invoker建立完毕后,接下来要作的事情是为服务接口生成代理对象.有了代理对象, // 便可进行远程调用.代理对象生成的入口方法为ProxyFactory的getProxy return (T) proxyFactory.getProxy(invoker);
// 先走到StubProxyFactoryWrapper的getProxy方法,它也是一个Wrapper public <T> T getProxy(Invoker<T> invoker) throws RpcException { T proxy = proxyFactory.getProxy(invoker); // 若是是非泛化 if (GenericService.class != invoker.getInterface()) { // 处理本地存根 String stub = invoker.getUrl().getParameter(Constants.STUB_KEY, invoker.getUrl().getParameter(Constants.LOCAL_KEY)); // 删去处理本地存根代码,不是本次分析重点 } return proxy; }
public abstract class AbstractProxyFactory implements ProxyFactory { // 接着走到AbstractProxyFactor的getProxy方法 @Override public <T> T getProxy(Invoker<T> invoker) throws RpcException { return getProxy(invoker, false); }
@Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { Class<?>[] interfaces = null; // 获取接口列表 String config = invoker.getUrl().getParameter("interfaces"); if (config != null && config.length() > 0) { // 切分接口列表 String[] types = Constants.COMMA_SPLIT_PATTERN.split(config); if (types != null && types.length > 0) { interfaces = new Class<?>[types.length + 2]; // 设置服务接口类和EchoService.class到interfaces中 interfaces[0] = invoker.getInterface(); interfaces[1] = EchoService.class; for (int i = 0; i < types.length; i++) { // 加载接口类 interfaces[i + 1] = ReflectUtils.forName(types[i]); } } } if (interfaces == null) { interfaces = new Class<?>[]{invoker.getInterface(), EchoService.class}; }
// 为http和hessian协议提供泛化调用支持 if (!invoker.getInterface().equals(GenericService.class) && generic) { int len = interfaces.length; Class<?>[] temp = interfaces; interfaces = new Class<?>[len + 1]; System.arraycopy(temp, 0, interfaces, 0, len); interfaces[len] = GenericService.class; } // 调用重载方法 return getProxy(invoker, interfaces); } public abstract <T> T getProxy(Invoker<T> invoker, Class<?>[] types); }
public class JavassistProxyFactory extends AbstractProxyFactory { // 最终走到JavassistProxyFactory的getProxy方法 public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { // 生成Proxy子类(Proxy是抽象类),并调用Proxy子类的newInstance方法建立Proxy实例 // 首先是经过Proxy的getProxy方法获取Proxy子类,而后建立InvokerInvocationHandler // 对象,并将该对象传给newInstance生成Proxy实例. InvokerInvocationHandler实现自 // JDK的InvocationHandler接口,具体的用途是拦截接口类调用 return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker)); } }
// 上述代码分红两步,显示Proxy.getProxy获取Proxy子类 public static Proxy getProxy(Class<?>... ics) { // 调用重载方法 return getProxy(ClassHelper.getClassLoader(Proxy.class), ics); }
public static Proxy getProxy(ClassLoader cl, Class<?>... ics) { if (ics.length > 65535) throw new IllegalArgumentException("interface limit exceeded"); StringBuilder sb = new StringBuilder();
// 遍历接口列表 for (int i = 0; i < ics.length; i++) { String itf = ics[i].getName(); // 检测类型是否为接口 if (!ics[i].isInterface()) throw new RuntimeException(itf + " is not a interface."); Class<?> tmp = null; try { // 从新加载接口类 tmp = Class.forName(itf, false, cl); } catch (ClassNotFoundException e) { } if (tmp != ics[i]) throw new IllegalArgumentException(ics[i] + " is not visible from class loader"); // 拼接接口全限定名,分隔符为; sb.append(itf).append(';'); }
// 使用拼接后的接口名做为key String key = sb.toString(); Map<String, Object> cache; synchronized (ProxyCacheMap) { cache = ProxyCacheMap.get(cl); if (cache == null) { cache = new HashMap<String, Object>(); ProxyCacheMap.put(cl, cache); } }
Proxy proxy = null; synchronized (cache) { do { // 从缓存中获取Reference<Proxy>实例 Object value = cache.get(key); if (value instanceof Reference<?>) { proxy = (Proxy) ((Reference<?>) value).get(); if (proxy != null) return proxy; } // 并发控制,保证只有一个线程能够进行后续操做 if (value == PendingGenerationMarker) { try { // 其余线程在此处进行等待 cache.wait(); } } else { // 放置标志位到缓存中,并跳出while循环进行后续操做 cache.put(key, PendingGenerationMarker); break; } } while (true); }
long id = PROXY_CLASS_COUNTER.getAndIncrement(); String pkg = null; ClassGenerator ccp = null, ccm = null; try { // 建立ClassGenerator对象 ccp = ClassGenerator.newInstance(cl); Set<String> worked = new HashSet<String>(); List<Method> methods = new ArrayList<Method>(); for (int i = 0; i < ics.length; i++) { // 检测接口访问级别是否为protected或privete if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); if (pkg == null) { pkg = npkg; } else { if (!pkg.equals(npkg)) // 非public级别的接口必须在同一个包下,否者抛出异常 throw new IllegalArgumentException("xxx"); } }
// 添加接口到ClassGenerator中 ccp.addInterface(ics[i]); // 遍历接口方法 for (Method method : ics[i].getMethods()) { // 获取方法描述,可理解为方法签名 String desc = ReflectUtils.getDesc(method); // 若是方法描述字符串已在worked中,则忽略,考虑这种状况, // A接口和B接口中包含一个彻底相同的方法 if (worked.contains(desc)) continue; worked.add(desc); int ix = methods.size(); // 获取方法返回值类型和参数列表 Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes(); // 生成 Object[] args = new Object[1...N] StringBuilder code = new StringBuilder("Object[] args = new Object[") .append(pts.length).append("];");
for (int j = 0; j < pts.length; j++) // 生成 args[1...N] = ($w)$1...N; code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";"); // 生成InvokerHandler接口的invoker方法调用语句,以下: // Object ret = handler.invoke(this, methods[1...N], args); code.append(" Object ret = handler.invoke(this, methods[" + ix + "], args);"); // 返回值不为void if (!Void.TYPE.equals(rt)) // 生成返回语句,形如 return (java.lang.String) ret; code.append(" return ").append(asArgument(rt, "ret")).append(";"); methods.add(method); // 添加方法名、访问控制符、参数列表、方法代码等信息到ClassGenerator中 ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); } }
if (pkg == null) pkg = PACKAGE_NAME; // 构建接口代理类名称: pkg + ".proxy" + id,好比org.apache.dubbo.proxy0 String pcn = pkg + ".proxy" + id; // 设置类名 ccp.setClassName(pcn); ccp.addField("public static java.lang.reflect.Method[] methods;"); // 生成 private java.lang.reflect.InvocationHandler handler; ccp.addField("private " + InvocationHandler.class.getName() + " handler;"); // 为接口代理类添加带有InvocationHandler参数的构造方法,好比: // porxy0(java.lang.reflect.InvocationHandler arg0) { // handler=$1; // } ccp.addConstructor(Modifier.PUBLIC, new Class<?>[]{InvocationHandler.class}, new Class<?>[0], "handler=$1;");
// 为接口代理类添加默认构造方法 ccp.addDefaultConstructor(); // 生成接口代理类 Class<?> clazz = ccp.toClass(); clazz.getField("methods").set(null, methods.toArray(new Method[0])); // 构建Proxy子类名称,好比Proxy1,Proxy2等 String fcn = Proxy.class.getName() + id; ccm = ClassGenerator.newInstance(cl); ccm.setClassName(fcn); ccm.addDefaultConstructor(); ccm.setSuperClass(Proxy.class); // 为Proxy的抽象方法newInstance生成实现代码,形如: // public Object newInstance(java.lang.reflect.InvocationHandler h) { // return new org.apache.dubbo.proxy0($1); // } ccm.addMethod("public Object newInstance(" + InvocationHandler.class.getName() + " h){ return new " + pcn + "($1); }"); // 生成Proxy实现类 Class<?> pc = ccm.toClass(); // 经过反射建立Proxy实例 proxy = (Proxy) pc.newInstance();
} catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) ccp.release(); if (ccm != null) ccm.release(); synchronized (cache) { if (proxy == null) cache.remove(key); else // 写缓存 cache.put(key, new WeakReference<Proxy>(proxy)); // 唤醒其余等待线程 cache.notifyAll(); } } return proxy; }
上面代码比较复杂,咱们写了大量的注释。你们在阅读这段代码时,要搞清楚 ccp 和 ccm 的用途,否则会被搞晕。ccp 用于为服务接口生成代理类,好比咱们有一个 DemoService 接口,这个接口代理类就是由 ccp 生成的。ccm 则是用于为 org.apache.dubbo.common.bytecode.Proxy 抽象类生成子类,主要是实现 Proxy 类的抽象方法。生成的两个类以下,你们能够对照着看代码会方便一些,如何获取这两个生成的类请参考 Dubbo中JavaAssist的Wrapper.getWrapper生成代理分析并发
public class Proxy0 extends Proxy implements ClassGenerator.DC { public Object newInstance(InvocationHandler invocationHandler) { return new proxy0(invocationHandler); } }
public class proxy0 implements ClassGenerator.DC, EchoService, DemoService { public static Method[] methods; private InvocationHandler handler; public String sayHello(String string) { Object[] arrobject = new Object[]{string}; // 经过proxy0中维护的handler就能够实现调用 Object object = this.handler.invoke(this, methods[0], arrobject); return (String)object; } public Object $echo(Object object) { Object[] arrobject = new Object[]{object}; Object object2 = this.handler.invoke(this, methods[1], arrobject); return object2; } public proxy0() {} public proxy0(InvocationHandler invocationHandler) { this.handler = invocationHandler; } }
public class JavassistProxyFactory extends AbstractProxyFactory { public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { // 如今已经分析完了第一步Proxy.getProxy // 接着分析第二步Proxy.newInstance() return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker)); } }
// Proxy.getProxy(interfaces)生成的是Proxy0实例对象,因此会走这里的 // newInstance(InvocationHandler invocationHandler)方法 public class Proxy0 extends Proxy implements ClassGenerator.DC { public Object newInstance(InvocationHandler invocationHandler) { return new proxy0(invocationHandler); } }
public proxy0(InvocationHandler invocationHandler) { // 最终走到这里并保存handler this.handler = invocationHandler; }
最终咱们的获得的ref以下,和咱们分析的同样,ref一个proxy0对象(注意和Proxy0区分,注意大小写),里面维护了一个InvokerInvocationHandler,它里面维护了咱们以前建立好的MockClusterInvokerapp
// 建立代理类,核心 ref = createProxy(map);