服务发布分析完了,下面让我们开始服务消费端。首先看下官方的时序图,有个总体印象
根据上一篇服务发布的逻辑,先看我们配置文件的使用
根据spring自定义配置文件的规则,我们一样可以找到入口ReferenceBean
public class DubboNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
......
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
......
}
}
先看ReferenceBean的定义
public class ReferenceBean extends ReferenceConfig implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean {
发现其实现了 FactoryBean和InitializingBean接口,想必和服务发布一样InitializingBean对应的afterPropertiesSet用来服务注入,FactoryBean对应的getObject一定是去实现代理实现的。首先大家一看看下我最初到代码分析流水图(代码分析到一种方法),有个总体印象:
按图索骥,我们找到afterPropertiesSet中进行参数设置
public void afterPropertiesSet() throws Exception {
if (getConsumer() == null) {
Map consumerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ConsumerConfig.class, false, false);
if (consumerConfigMap != null && consumerConfigMap.size() > 0) {
ConsumerConfig consumerConfig = null;
.......
}
if (getApplication() == null
&& (getConsumer() == null || getConsumer().getApplication() == null)) {
........
}
if (getModule() == null
&& (getConsumer() == null || getConsumer().getModule() == null)) {
........
}
if ((getRegistries() == null || getRegistries().size() == 0)
&& (getConsumer() == null || getConsumer().getRegistries() == null || getConsumer().getRegistries().size() == 0)
&& (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().size() == 0)) {
.......
}
if (getMonitor() == null
&& (getConsumer() == null || getConsumer().getMonitor() == null)
&& (getApplication() == null || getApplication().getMonitor() == null)) {
........
}
Boolean b = isInit();
if (b == null && getConsumer() != null) {
b = getConsumer().isInit();
}
if (b != null && b.booleanValue()) {
getObject();
}
}
发现实际入口的确在getObject方法,而此时b又不会等于true,所以此时不会进入次方法,则实际进入getObject的一定是通过FactoryBean的特性。下面开始重点分析怎么获取到的这个引用对象
public synchronized T get() {
if (destroyed) {
throw new IllegalStateException("Already destroyed!");
}
if (ref == null) {
init();
}
return ref;
}
进去init方法
private void init() {
//和服务端对应赋值
.....
// 获取消费者全局配置
checkDefault();
appendProperties(this);
if (getGeneric() == null && getConsumer() != null) {
setGeneric(getConsumer().getGeneric());
}
if (ProtocolUtils.isGeneric(getGeneric())) {
.....
}
String resolve = System.getProperty(interfaceName);
String resolveFile = null;
if (resolve == null || resolve.length() == 0) {
.....
}
if (consumer != null) {
...
}
if (module != null) {
...
}
checkApplication();
checkStubAndMock(interfaceClass);
....
//attributes通过系统context进行存储.
StaticContext.getSystemContext().putAll(attributes);
//重点,去创建引用代理
ref = createProxy(map);
}
此方法中重点是把相关参数加载到paramterMap中(服务端也又类似操作),然后进入createProxy核心方法
private T createProxy(Map map) {
URL tmpUrl = new URL("temp", "localhost", 0, map);
final boolean isJvmRefer;
......
if (isJvmRefer) {
//同一jvm引用,不是分析重点
....
} else {
if (url != null && url.length() > 0) {
// 用户指定URL,指定的URL可能是对点对直连地址,也可能是注册中心URL
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 us = loadRegistries(false);
if (us != null && us.size() > 0) {
for (URL u : us) {
URL monitorUrl = loadMonitor(u);
if (monitorUrl != null) {
map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString()));
}
urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)));
}
}
if (urls == null || urls.size() == 0) {
throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config to your spring config.");
}
}
if (urls.size() == 1) {
invoker = refprotocol.refer(interfaceClass, urls.get(0));
} else {
List> invokers = new ArrayList>();
URL registryURL = null;
for (URL url : urls) {
invokers.add(refprotocol.refer(interfaceClass, url));
if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
registryURL = url; // 用了最后一个registry url
}
}
if (registryURL != null) { // 有 注册中心协议的URL
// 对有注册中心的Cluster 只用 AvailableCluster
URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME);
invoker = cluster.join(new StaticDirectory(u, invokers));
} else { // 不是 注册中心的URL
invoker = cluster.join(new StaticDirectory(invokers));
}
}
}
.......
// 创建服务代理
return (T) proxyFactory.getProxy(invoker);
}
(略过tempUrl对应的injvm逻辑,此处是同一jvm内引用情况)首先检查用户是否在此引用上单独设置对端(或在多个注册中心情况下指定哪个url)url,如果配置则直接用此url,否则加载配置文件所有配置的注册中心生成url
List us = loadRegistries(false);
此方法在服务发布已经分析过一次,只是此时入参为false(服务端为true),区别在哪呢?
protected List loadRegistries(boolean provider) {
......
if ((provider && url.getParameter(Constants.REGISTER_KEY, true))
|| (!provider && url.getParameter(Constants.SUBSCRIBE_KEY, true))) {
registryList.add(url);
}
}
return registryList;
大致意思是当服务端且没有禁用register或当客户端且没有禁用订阅时添加到注册url列表中。
loadRegistries方法会返回所有
registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?application=dubbo-client&dubbo=2.0.0&pid=19028®istry=zookeeper×tamp=1540603677848
然后进行了一段和服务端类似端操作,将刚才生成的参数map生成string,存入map中,以refer为key(服务端key为exporter)。
if (us != null && us.size() > 0) {
for (URL u : us) {
....
//监控相关省略,有机会分享
urls.add(u.addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)));
}
}
获取到注册中心url后,值大概样子是:
registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?application=dubbo-client&dubbo=2.0.0&pid=20267&refer=application%3Ddubbo-client%26check%3Dtrue%26dubbo%3D2.0.0%26interface%3Dcom.alibaba.dubbo.kai.api.TestApi%26methods%3Dgo%26pid%3D20267%26protocol%3Ddubbo%26register.ip%3D192.168.199.130%26revision%3D0.0%26side%3Dconsumer%26timeout%3D10000%26timestamp%3D1540622309609%26version%3D0.0®istry=zookeeper×tamp=1540622309684
下面到重点是什么呢?当然应该是从注册中心中订阅到对应服务
if (urls.size() == 1) {
invoker = refprotocol.refer(interfaceClass, urls.get(0));
} else {
List> invokers = new ArrayList>();
URL registryURL = null;
for (URL url : urls) {
invokers.add(refprotocol.refer(interfaceClass, url));
if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
registryURL = url; // 用了最后一个registry url
}
}
if (registryURL != null) { // 有 注册中心协议的URL
// 对有注册中心的Cluster 只用 AvailableCluster
URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME);
invoker = cluster.join(new StaticDirectory(u, invokers));
} else { // 不是 注册中心的URL
invoker = cluster.join(new StaticDirectory(invokers));
}
他先判断了注册中心是否只有一个,如果只有一个则会直接发布赋值invoker,如果又多个,会生成个invokerList,将每个注册中心订阅到到url添加进去,最后生成一个新到clusterInvoker(具体是什么后边会讲)。
那么我们只需要先分析完单个注册中心发布的过程,多个注册中心的发布过程就只是在上面又套了一层StaticDirectory而已了。
好了,让我们看每个url是怎么发布的:
- refprotocol.refer(interfaceClass, url)
这是服务发布生成invoker的重点了,首先refprotocol这个是什么?
//根据spi机制,此处适配protocol为ProtocolAdaptive
private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
根据我们spi的知识,已经找到此类
public class Protocol$Adaptive implements com.alibaba.dubbo.rpc.Protocol {
.......
public com.alibaba.dubbo.rpc.Invoker refer(Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {
if (arg1 == null) throw new IllegalArgumentException("url == null");
com.alibaba.dubbo.common.URL url = arg1;
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
return extension.refer(arg0, arg1);
}
........
}
适配逻辑和服务端一样,主要还是看url中的protocol,回头看下url发现此时协议为registry,所以最终会进入RegistryProtocol的refer方法中,
public Invoker refer(Class type, URL url) throws RpcException {
//还原最初的注册中心协议头zookeeper
url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY);
//从工厂中获取registry对象,此处根据spi机制肯定获取到ZookeeperRegistry
Registry registry = registryFactory.getRegistry(url);
if (RegistryService.class.equals(type)) {
return proxyFactory.getInvoker((T) registry, type, url);
}
// group="a,b" or group="*" 分组逻辑,暂时不考虑,不影响主流程
Map qs = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY));
String group = qs.get(Constants.GROUP_KEY);
if (group != null && group.length() > 0) {
if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1
|| "*".equals(group)) {
return doRefer(getMergeableCluster(), registry, type, url);
}
}
//核心引用逻辑
return doRefer(cluster, registry, type, url);
}
我们看到此时获取到了ZookeeperRegistry,再调用了doRefer(cluster, registry, type, url)方法
private Invoker doRefer(Cluster cluster, Registry registry, Class type, URL url) {
// 创建RegistryDirectory对象,此为注册中心目录对象,重点对象
RegistryDirectory directory = new RegistryDirectory(type, url);
directory.setRegistry(registry);
directory.setProtocol(protocol);
// 获取REFER_KEY的所有属性
Map parameters = new HashMap(directory.getUrl().getParameters());
//生成自身的消费端urlconsumer://192.168.199.130/com.alibaba.dubbo.kai.api.TestApi?application=dubbo-client&check=true&dubbo=2.0.0&interface=com.alibaba.dubbo.kai.api.TestApi&methods=go&pid=20496&protocol=dubbo&revision=0.0&side=consumer&timeout=10000×tamp=1540623417681&version=0.0
URL subscribeUrl = new URL(Constants.CONSUMER_PROTOCOL, parameters.remove(Constants.REGISTER_IP_KEY), 0, type.getName(), parameters);
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三个目录下信息,生成一个复合的invoker
directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY,
Constants.PROVIDERS_CATEGORY
+ "," + Constants.CONFIGURATORS_CATEGORY
+ "," + Constants.ROUTERS_CATEGORY));
//cluster进行join联合,根据cluster适配选择不同的集群调用策略
return cluster.join(directory);
}
这里提出了引用端重要的一个对象RegistryDirectory,顾名思义是注册中心的一个文件目录,里边应该包含了当前注册中心的所有内容。方法中先是创建了ci对象,然后将当前消费者自身注册到注册中心,以便别人能看到自己。然后重点是通过 directory.subscribe方法去订阅providers、configurators、routers三个文件的目录,看下此方法:
public void subscribe(URL url) {
setConsumerUrl(url);
registry.subscribe(url, this);
}
落到了 registry.subscribe(url, this)方法上,此方法我们是不是很眼熟?对了,分析服务发布时,也曾分析过此段代码,看下当时那张大图端这块
大致意思是,服务端订阅了configurtors目录,此目录内发生改变时,zookeeper回调监听器端通知方法notify(),然后判断新端url和旧的url是否一致,不一致则重新发布服务。那消费端呢?
我们看到添加监听逻辑和服务端一样最终都会落到zookeeperRegistry的doSubscribe(final URL url, final NotifyListener listener) 的方法上(具体跳转流程,可看服务发布)
protected void doSubscribe(final URL url, final NotifyListener listener) {
.............
. List urls = new ArrayList();
for (String path : toCategoriesPath(url)) {
ConcurrentMap listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
listeners.putIfAbsent(listener, new ChildListener() {
public void childChanged(String parentPath, List currentChilds) {
ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds));
}
});
zkListener = listeners.get(listener);
}
zkClient.create(path, false);
List children = zkClient.addChildListener(path, zkListener);
if (children != null) {
urls.addAll(toUrlsWithEmpty(url, path, children));
}
}
notify(url, listener, urls);
}
.........
}
此处和服务端不同端是服务端 toCategoriesPath(url)返回只有
/dubbo/com.alibaba.dubbo.kai.api.TestApi/configurators,而消费端有/dubbo/com.alibaba.dubbo.kai.api.TestApi/configurators、/dubbo/com.alibaba.dubbo.kai.api.TestApi/routers和/dubbo/com.alibaba.dubbo.kai.api.TestApi/providers三个目录。
创建完订阅目录,消费端一样会调用监听器端notify方法,而此时端listener为RegistryDirectory
public synchronized void notify(List urls) {
List invokerUrls = new ArrayList();
List routerUrls = new ArrayList();
List configuratorUrls = new ArrayList();
for (URL url : urls) {
String protocol = url.getProtocol();
String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
if (Constants.ROUTERS_CATEGORY.equals(category)
|| Constants.ROUTE_PROTOCOL.equals(protocol)) {
routerUrls.add(url);
} else if (Constants.CONFIGURATORS_CATEGORY.equals(category)
|| Constants.OVERRIDE_PROTOCOL.equals(protocol)) {
configuratorUrls.add(url);
} else if (Constants.PROVIDERS_CATEGORY.equals(category)) {
invokerUrls.add(url);
} else {
logger.warn("Unsupported category " + category + " in notified url: " + url + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost());
}
}
// configurators
if (configuratorUrls != null && configuratorUrls.size() > 0) {
this.configurators = toConfigurators(configuratorUrls);
}
// routers
if (routerUrls != null && routerUrls.size() > 0) {
List routers = toRouters(routerUrls);
if (routers != null) { // null - do nothing
setRouters(routers);
}
}
List localConfigurators = this.configurators; // local reference
// 合并override参数,更该配置时刷新invoker
this.overrideDirectoryUrl = directoryUrl;
if (localConfigurators != null && localConfigurators.size() > 0) {
for (Configurator configurator : localConfigurators) {
this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl);
}
}
// providers
refreshInvoker(invokerUrls);
}
前边是对configurator和router的合并,更新overrideDirectoryUrl,此时初次引用过程configurator和router都没空,直接调用refreshInvoker(invokerUrls)
/**
* 根据invokerURL列表转换为invoker列表。转换规则如下:
* 1.如果url已经被转换为invoker,则不在重新引用,直接从缓存中获取,注意如果url中任何一个参数变更也会重新引用
* 2.如果传入的invoker列表不为空,则表示最新的invoker列表
* 3.如果传入的invokerUrl列表是空,则表示只是下发的override规则或route规则,需要重新交叉对比,决定是否需要重新引用。
*
* @param invokerUrls 传入的参数不能为null
*/
private void refreshInvoker(List invokerUrls) {
if (invokerUrls != null && invokerUrls.size() == 1 && invokerUrls.get(0) != null
&& Constants.EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
this.forbidden = true; // 禁止访问
this.methodInvokerMap = null; // 置空列表
destroyAllInvokers(); // 关闭所有Invoker
} else {
this.forbidden = false; // 允许访问
Map> oldUrlInvokerMap = this.urlInvokerMap; // local reference
if (invokerUrls.size() == 0 && this.cachedInvokerUrls != null) {
invokerUrls.addAll(this.cachedInvokerUrls);
} else {
this.cachedInvokerUrls = new HashSet();
this.cachedInvokerUrls.addAll(invokerUrls);//缓存invokerUrls列表,便于交叉对比
}
if (invokerUrls.size() == 0) {
return;
}
// 将URL列表转成Invoker列表
Map> newUrlInvokerMap = toInvokers(invokerUrls);
// 换方法名映射Invoker列表
Map>> newMethodInvokerMap = toMethodInvokers(newUrlInvokerMap);
// state change
//如果计算错误,则不进行处理.
if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) {
logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls.toString()));
return;
}
this.methodInvokerMap = multiGroup ? toMergeMethodInvokerMap(newMethodInvokerMap) : newMethodInvokerMap;
this.urlInvokerMap = newUrlInvokerMap;
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // 关闭未使用的Invoker
} catch (Exception e) {
logger.warn("destroyUnusedInvokers error. ", e);
}
}
}
我们看到主流程重点在
// 将URL列表转成Invoker列表
Map> newUrlInvokerMap = toInvokers(invokerUrls);
// 换方法名映射Invoker列表
Map>> newMethodInvokerMap = toMethodInvokers(newUrlInvokerMap);
这两个方法,第一个将url生成对应都invoker,第二将生成都invoker改成对应目的方法名对应都invoker,看下toInvokers(invokerUrls)生成逻辑
private Map> toInvokers(List urls) {
Map> newUrlInvokerMap = new HashMap>();
if (urls == null || urls.size() == 0) {
return newUrlInvokerMap;
}
Set keys = new HashSet();
String queryProtocols = this.queryMap.get(Constants.PROTOCOL_KEY);
for (URL providerUrl : urls) {
//如果reference端配置了protocol,则只选择匹配的protocol
if (queryProtocols != null && queryProtocols.length() > 0) {
boolean accept = false;
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (providerUrl.getProtocol().equals(acceptProtocol)) {
accept = true;
break;
}
}
if (!accept) {
continue;
}
}
//对于空目录,没有配置都直接跳过
if (Constants.EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) {
continue;
}
if (!ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(providerUrl.getProtocol())) {
logger.error(new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()
+ ", supported protocol: " + ExtensionLoader.getExtensionLoader(Protocol.class).getSupportedExtensions()));
continue;
}
//合并consumer和provider两面都url生成新都url
URL url = mergeUrl(providerUrl);
String key = url.toFullString(); // URL参数是排序的
if (keys.contains(key)) { // 重复URL
continue;
}
keys.add(key);
// 缓存key为没有合并消费端参数的URL,不管消费端如何合并参数,如果服务端URL发生变化,则重新refer
Map> localUrlInvokerMap = this.urlInvokerMap; // local reference
Invoker invoker = localUrlInvokerMap == null ? null : localUrlInvokerMap.get(key);
if (invoker == null) { // 缓存中没有,重新refer
try {
boolean enabled = true;
if (url.hasParameter(Constants.DISABLED_KEY)) {
enabled = !url.getParameter(Constants.DISABLED_KEY, false);
} else {
enabled = url.getParameter(Constants.ENABLED_KEY, true);
}
if (enabled) {
//重点生成invoker逻辑
//url为合并后地址dubbo://172.18.166.201:20880/com.alibaba.dubbo.kai.api.TestApi?anyhost=true&application=dubbo-client&check=false&dubbo=2.0.0&generic=false&interface=com.alibaba.dubbo.kai.api.TestApi&methods=go&pid=9629&protocol=dubbo®ister.ip=172.18.166.201&remote.timestamp=1540454917247&revision=0.0&server=netty4&side=consumer&timeout=10000×tamp=1540456251008&version=0.0
//providerUrl为服务端地址dubbo://172.18.166.201:20880/com.alibaba.dubbo.kai.api.TestApi?anyhost=true&application=kai-nina-server&dubbo=2.0.0&generic=false&interface=com.alibaba.dubbo.kai.api.TestApi&methods=go&pid=9346&revision=0.0&server=netty4&side=provider×tamp=1540454917247&version=0.0
invoker = new InvokerDelegete(protocol.refer(serviceType, url), url, providerUrl);
}
} catch (Throwable t) {
logger.error("Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t);
}
if (invoker != null) { // 将新的引用放入缓存
newUrlInvokerMap.put(key, invoker);
}
} else {
newUrlInvokerMap.put(key, invoker);
}
}
keys.clear();
return newUrlInvokerMap;
}
还是先做了url合并检查逻辑(毕竟修改和新增都是通过此方法),当缓存中没有此invoker时通过消费端的invokerDelegete委派器生成新的invoker,看其入参再此调用了protocol.refer(serviceType, url)方法进行发布,此时的url是什么呢?
dubbo://192.168.199.130:20880/com.alibaba.dubbo.kai.api.TestApi?anyhost=true&application=dubbo-client&check=false&client=netty4&dubbo=2.0.0&generic=false&interface=com.alibaba.dubbo.kai.api.TestApi&methods=go&pid=21873&protocol=dubbo®ister.ip=192.168.199.130&remote.timestamp=1540603631243&revision=0.0&server=netty4&side=consumer&timeout=10000×tamp=1540632189708&version=0.0
因为上边 mergeUrl(providerUrl)方法,已将服务端url进行合并,改为dubbo协议头地址,此时发布将会调用DubboProtocol的refer方法(是不是和服务发布的逻辑类似)
public Invoker refer(Class serviceType, URL url) throws RpcException {
// create rpc invoker.
DubboInvoker invoker = new DubboInvoker(serviceType, url, getClients(url), invokers);
invokers.add(invoker);
return invoker;
}
生成了DubboInvoker对象,想必这就是最终返回的invoker对象,我们注意到其入参有个getClients(url)
private ExchangeClient[] getClients(URL url) {
//是否共享连接
boolean service_share_connect = false;
int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0);
//如果connections不配置,则共享连接,否则每服务每连接
if (connections == 0) {
service_share_connect = true;
connections = 1;
}
//对服务端链接端封装
ExchangeClient[] clients = new ExchangeClient[connections];
for (int i = 0; i < clients.length; i++) {
if (service_share_connect) {
clients[i] = getSharedClient(url);
} else {
clients[i] = initClient(url);
}
}
return clients;
}
看到这个方法感觉终于看到曙光了,又是一个Exchange,显然是在对应着服务端端socket服务,生成端客户端。此处有个connections参数,表示dubbo可以配置客户端是否所有invoker用同一条netty通道,我们没配置端化默认就是共享,进入getSharedClient(url)方法
private ExchangeClient getSharedClient(URL url) {
String key = url.getAddress();
ReferenceCountExchangeClient client = referenceClientMap.get(key);
if (client != null) {
if (!client.isClosed()) {
client.incrementAndGetCount();
return client;
} else {
referenceClientMap.remove(key);
}
}
synchronized (key.intern()) {
ExchangeClient exchangeClient = initClient(url);
client = new ReferenceCountExchangeClient(exchangeClient, ghostClientMap);
referenceClientMap.put(key, client);
ghostClientMap.remove(key);
return client;
}
}
发现dubbo是用了个缓存来保证唯一,缓存有则移除原有,然后重新生成一个,最后还是通过initClient(url)生成一个新的客户端
private ExchangeClient initClient(URL url) {
// client type setting.
String str = url.getParameter(Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_CLIENT));
String version = url.getParameter(Constants.DUBBO_VERSION_KEY);
boolean compatible = (version != null && version.startsWith("1.0."));
url = url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME);
//默认开启heartbeat
url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT));
// BIO存在严重性能问题,暂时不允许使用
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
throw new RpcException("Unsupported client type: " + str + "," +
" supported client type is " + StringUtils.join(ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(), " "));
}
ExchangeClient client;
try {
//设置连接应该是lazy的
if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)) {
client = new LazyConnectExchangeClient(url, requestHandler);
} else {
client = Exchangers.connect(url, requestHandler);
}
} catch (RemotingException e) {
throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e);
}
return client;
}
初始化client通过 client = Exchangers.connect(url, requestHandler)方法进行,Exchangers类就是我们上一篇看到的发布类,此处服务引用一样用的这个类(肯定都是一一对应的)。再看看这个类
public static ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange");
return getExchanger(url).connect(url, handler);
}
一样还是调用getExchanger(url)获取Exhanger对象,不重复解释,这里获取到到HeaderExchanger
public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
return new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler))), true);
}
生成了一个HeaderExchangeClient,内部一样包装了一个Transporters进行管道连接
public static Client connect(URL url, ChannelHandler... handlers) throws RemotingException {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
ChannelHandler handler;
if (handlers == null || handlers.length == 0) {
handler = new ChannelHandlerAdapter();
} else if (handlers.length == 1) {
handler = handlers[0];
} else {
handler = new ChannelHandlerDispatcher(handlers);
}
return getTransporter().connect(url, handler);
}
这里包装了一个ChannelHandlerDispatcher作为委派器,里边不过时当handler有多个handler循环进行处理,最后一样getTransporter()肯定获得当还是和服务对应的NettyTransporter
public Client connect(URL url, ChannelHandler listener) throws RemotingException {
return new NettyClient(url, listener);
}
诶,找到了,终于看到了熟悉的NettyClient,进去看一眼
public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException {
super(url, wrapChannelHandler(url, handler));
}
@Override
protected void doOpen() throws Throwable {
NettyHelper.setNettyLoggerFactory();
final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
bootstrap = new Bootstrap();
bootstrap.group(nioEventLoopGroup)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
//.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
.channel(NioSocketChannel.class);
if (getTimeout() < 3000) {
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
} else {
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
}
bootstrap.handler(new ChannelInitializer() {
protected void initChannel(Channel ch) throws Exception {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
.addLast("decoder", adapter.getDecoder())//
.addLast("encoder", adapter.getEncoder())//
.addLast("handler", nettyClientHandler);
}
});
}
protected void doConnect() throws Throwable {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(getConnectAddress());
try {
boolean ret = future.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.channel();
try {
// 关闭旧的连接
Channel oldChannel = NettyClient.this.channel; // copy reference
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.cause() != null) {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + ", error message is:" + future.cause().getMessage(), future.cause());
} else {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + " client-side timeout "
+ getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
}
} finally {
if (!isConnected()) {
//future.cancel(true);
}
}
}
一样的套路,构造方法调用父类,然后两个do方法进行实际操作,父类方法肯定还是个模版模式,调用实际的do方法,不过调用之前和服务端一样都是有一个包装的操作wrapChannelHandler(url, handler)
protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) {
url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME);
url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL);
return ChannelHandlers.wrap(handler, url);
}
和服务端一样了,最后都生成了
new MultiMessageHandler(new HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispatcher.class)
.getAdaptiveExtension().dispatch(handler, url)))
这个和服务端做功能的一一对应。
两个do方法就简单了doOpen常规的Netty客户端代码,doConnect进行服务链接获取通道进行缓存。而其处理消息的核心handler还是一样是通过DubboProtocol传过来的requestHandler
private ExchangeHandler requestHandler = new ExchangeHandlerAdapter() {
public Object reply(ExchangeChannel channel, Object message) throws RemotingException {
if (message instanceof Invocation) {
Invocation inv = (Invocation) message;
Invoker> invoker = getInvoker(channel, inv);
//如果是callback 需要处理高版本调用低版本的问题
if (Boolean.TRUE.toString().equals(inv.getAttachments().get(IS_CALLBACK_SERVICE_INVOKE))) {
String methodsStr = invoker.getUrl().getParameters().get("methods");
boolean hasMethod = false;
if (methodsStr == null || methodsStr.indexOf(",") == -1) {
hasMethod = inv.getMethodName().equals(methodsStr);
} else {
String[] methods = methodsStr.split(",");
for (String method : methods) {
if (inv.getMethodName().equals(method)) {
hasMethod = true;
break;
}
}
}
if (!hasMethod) {
logger.warn(new IllegalStateException("The methodName " + inv.getMethodName() + " not found in callback service interface ,invoke will be ignored. please update the api interface. url is:" + invoker.getUrl()) + " ,invocation is :" + inv);
return null;
}
}
RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress());
return invoker.invoke(inv);
}
throw new RemotingException(channel, "Unsupported request: " + message == null ? null : (message.getClass().getName() + ": " + message) + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress());
}
.........
};
所以消费端和客户端对消息处理的handler一致,收消息一定最后调用这个reply方法,那发消息呢?
还记得NettyClient的这段代码吗?
Channel oldChannel = NettyClient.this.channel; // copy reference
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
这里边有个NettyChannel每次有废弃通道时,为什么会调用这个方法呢?原来dubbo中的netty通道都缓存在此类中
final class NettyChannel extends AbstractChannel {
private static final Logger logger = LoggerFactory.getLogger(NettyChannel.class);
private static final ConcurrentMap channelMap = new ConcurrentHashMap();
private final org.jboss.netty.channel.Channel channel;
channelMap缓存了所有正在使用都channel,并包装成dubbo内部都NettyChannel,在此类中对netty对channel进行了些包装,主要处理状态检查等等操作。当需要发送消息时,也是从NettyChannel对静态方法getOrAddChannel中获取到通道进行发送的。
好了,到这里client终于连接上服务端了。回到起点,生成了
ExchangeClient exchangeClient = initClient(url)
这个client对象,会被client = new ReferenceCountExchangeClient(exchangeClient, ghostClientMap)包装一层,和服务端的ExporterChangeableWrapper类型,一个可变的引用包装。完成后,生成我们的DubboInvoker(还记得吧,可以结合大图看),看眼大图
回到上文的RegistryDirectory订阅后的notify逻辑
通过此refreshInvoker方法将所有服务端url转换为invoker对象,
//转换起点在这
Map> newUrlInvokerMap = toInvokers(invokerUrls);
此时订阅的主流程就完成了,当然还有一写废弃以前就invoker等等操作,都是为了更新时使用的。
流程回到RegistryProtocol的refer中
directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY,
Constants.PROVIDERS_CATEGORY
+ "," + Constants.CONFIGURATORS_CATEGORY
+ "," + Constants.ROUTERS_CATEGORY));
return cluster.join(directory);
directory已经包含了此接口对应的所有invoker对象,又引入了另外一个概念cluster。
顾名思义,cluster是集群的意思,必然是dubbo对集群处理的不同实现,看看这个cluster对象
private Cluster cluster;
是个成员变量,那么一定是通过spi依赖注入来的
public class Cluster$Adaptive implements com.alibaba.dubbo.rpc.cluster.Cluster {
public com.alibaba.dubbo.rpc.Invoker join(com.alibaba.dubbo.rpc.cluster.Directory arg0) throws com.alibaba.dubbo.rpc.RpcException {
if (arg0 == null)
throw new IllegalArgumentException("com.alibaba.dubbo.rpc.cluster.Directory argument == null");
if (arg0.getUrl() == null)
throw new IllegalArgumentException("com.alibaba.dubbo.rpc.cluster.Directory argument getUrl() == null");
com.alibaba.dubbo.common.URL url = arg0.getUrl();
String extName = url.getParameter("cluster", "failover");
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.cluster.Cluster) name from url(" + url.toString() + ") use keys([cluster])");
com.alibaba.dubbo.rpc.cluster.Cluster extension = (com.alibaba.dubbo.rpc.cluster.Cluster) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.cluster.Cluster.class).getExtension(extName);
return extension.join(arg0);
}
}
看到字节码生成的动态类默认用的是failover扩展名,我们找到对应的类是public class FailoverCluster implements Cluster {
public final static String NAME = "failover";
public Invoker join(Directory directory) throws RpcException {
return new FailoverClusterInvoker(directory);
}
}
调用其join方法,会返回一个对应其策略的FailoverClusterInvoker。
那么知识点来了:
-
Failover Cluster(默认)
失败自动切换,当出现失败,重试其它服务器 。通常用于读操作,但重试会带来更长延迟。可通过 retries="2" 来设置重试次数(不含第一次)。重试次数配置如下:
- Failfast Cluster
快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录 - Failsafe Cluster
失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。 - Failback Cluster
失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。 - Forking Cluster
并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks="2" 来设置最大并行数。 - Broadcast Cluster
广播调用所有提供者,逐个调用,任意一台报错则报错 [2]。通常用于通知所有提供者更新缓存或日志等本地资源信息
dubbo一共主要又这六种集群处理机制(没有算mock,和多注册中心的AvailableCluster操作),每个都实现了一种调用,通过父类的AbstractClusterInvoker的select和doSelect进行负载均衡算法,然后通过自己实现doInvoke方法,每个ClusterInvoker进行不同的容错处理机制,欲知详情,请看下章调用过程讲解。
生成了clusterInvoker,基本的引用创建invoker过程就基本完了。
回到ReferenceConfig的 createProxy(Mapmap)方法中,生成完invoker,如果是多注册中心,会进行一次AvailableCluster包装
if (urls.size() == 1) {
invoker = refprotocol.refer(interfaceClass, urls.get(0));
} else {
List> invokers = new ArrayList>();
URL registryURL = null;
for (URL url : urls) {
invokers.add(refprotocol.refer(interfaceClass, url));
if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
registryURL = url; // 用了最后一个registry url
}
}
if (registryURL != null) { // 有 注册中心协议的URL
// 对有注册中心的Cluster 只用 AvailableCluster
URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME);
invoker = cluster.join(new StaticDirectory(u, invokers));
} else { // 不是 注册中心的URL
invoker = cluster.join(new StaticDirectory(invokers));
}
}
这逻辑就大同小异了,总之最后获得了clusterinvoker。
再往下
return (T) proxyFactory.getProxy(invoker);
通过proxyFactory生成对应invoker的代理类,看下实现,最后都回到
public T getProxy(Invoker invoker, Class>[] interfaces) {
return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
}
生成了一个动态代理,当然此处proxyFactory又两个实现一个JdkProxyFactory和JavassistProxyFactory。前者使用jdk的动态代码实现,后者则通过javasssist的方法先手写一个的class文件,然后去创建对象
public static Proxy getProxy(ClassLoader cl, Class>... ics) {
.......
long id = PROXY_CLASS_COUNTER.getAndIncrement();
String pkg = null;
ClassGenerator ccp = null, ccm = null;
try {
ccp = ClassGenerator.newInstance(cl);
Set worked = new HashSet();
List methods = new ArrayList();
for (int i = 0; i < ics.length; i++) {
if (!Modifier.isPublic(ics[i].getModifiers())) {
String npkg = ics[i].getPackage().getName();
if (pkg == null) {
pkg = npkg;
} else {
if (!pkg.equals(npkg))
throw new IllegalArgumentException("non-public interfaces from different packages");
}
}
ccp.addInterface(ics[i]);
for (Method method : ics[i].getMethods()) {
String desc = ReflectUtils.getDesc(method);
if (worked.contains(desc))
continue;
worked.add(desc);
int ix = methods.size();
Class> rt = method.getReturnType();
Class>[] pts = method.getParameterTypes();
StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];");
for (int j = 0; j < pts.length; j++)
code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";");
code.append(" Object ret = handler.invoke(this, methods[" + ix + "], args);");
if (!Void.TYPE.equals(rt))
code.append(" return ").append(asArgument(rt, "ret")).append(";");
methods.add(method);
ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString());
}
}
if (pkg == null)
pkg = PACKAGE_NAME;
// create ProxyInstance class.
String pcn = pkg + ".proxy" + id;
ccp.setClassName(pcn);
ccp.addField("public static java.lang.reflect.Method[] methods;");
ccp.addField("private " + InvocationHandler.class.getName() + " handler;");
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]));
// create Proxy class.
String fcn = Proxy.class.getName() + id;
ccm = ClassGenerator.newInstance(cl);
ccm.setClassName(fcn);
ccm.addDefaultConstructor();
ccm.setSuperClass(Proxy.class);
ccm.addMethod("public Object newInstance(" + InvocationHandler.class.getName() + " h){ return new " + pcn + "($1); }");
Class> pc = ccm.toClass();
proxy = (Proxy) pc.newInstance();
..........
return proxy;
}
此处会生成一个通过javassist生成一个代理类继承Proxy且实现你的接口,最终调用时通过定义的InvokerInvocationHandler进行实际调用(和jdk动态代理实际机制一样)。我们看一眼InvokerInvocationHandler类
public class InvokerInvocationHandler implements InvocationHandler {
private final Invoker> invoker;
public InvokerInvocationHandler(Invoker> handler) {
this.invoker = handler;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
Class>[] parameterTypes = method.getParameterTypes();
if (method.getDeclaringClass() == Object.class) {
return method.invoke(invoker, args);
}
if ("toString".equals(methodName) && parameterTypes.length == 0) {
return invoker.toString();
}
if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
return invoker.hashCode();
}
if ("equals".equals(methodName) && parameterTypes.length == 1) {
return invoker.equals(args[0]);
}
return invoker.invoke(new RpcInvocation(method, args)).recreate();
}
}
内容很少,最主要的就是最后通过刚才生成invoker进行最终调用。
好了,到这里最终的代理对象终于生成完了,让我们总体看下类图
(上图中的HeaderExchangeChannel是在HeaderExchangeClient的一个属性,NettyClient将被包装在此channel中,而DubboProtocol$requestHandler并没有在此图最下面展示,因为消费端接收消息并没有用到,下章会细讲)
总结下,dubbo最终生成代理类,把生成的invoker集合以目录类Directory的形式存入代理类的handler中,并通过cluster层包装来实现集群调用策略。不过我们分析过程中少了一部分 DubboProtocol调用时肯定会经过对应的wrapper类,此时会将invoker进行层层包装形成图中的filtersInvoker,此处和服务端一样,不再赘述。
好了到此,服务引用分析完了,要想看怎么调用的,请看下节吧!
下一篇 dubbo调用源码之消费端
首页 dubbo源码欣赏简介