From f43d9caae443eb5ef04fa7ccbde14252a9bd5b45 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 26 Oct 2016 22:59:57 +0800 Subject: [PATCH 01/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9curator=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=EF=BC=8C=E8=A7=A3=E5=86=B3zookeeper=E5=AE=95?= =?UTF-8?q?=E6=9C=BA=E9=87=8D=E5=90=AF=E6=97=A0=E6=B3=95=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E9=87=8D=E8=BF=9E=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../remoting/zookeeper/curator/CuratorZookeeperClient.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index 6011e91c892..ff9203fd060 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -19,6 +19,7 @@ import com.alibaba.dubbo.remoting.zookeeper.ChildListener; import com.alibaba.dubbo.remoting.zookeeper.StateListener; import com.alibaba.dubbo.remoting.zookeeper.support.AbstractZookeeperClient; +import org.apache.zookeeper.Watcher; public class CuratorZookeeperClient extends AbstractZookeeperClient { @@ -114,7 +115,7 @@ public void unwatch() { } public void process(WatchedEvent event) throws Exception { - if (listener != null) { + if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged && listener != null) { listener.childChanged(event.getPath(), client.getChildren() .usingWatcher(this).forPath(event.getPath())); } From 99b124245cda34d61cc329bd22b281c2824cc99a Mon Sep 17 00:00:00 2001 From: YanXs Date: Thu, 22 Dec 2016 22:01:12 +0800 Subject: [PATCH 02/69] =?UTF-8?q?=E4=B8=BAApplicationConfig=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0close=E6=96=B9=E6=B3=95=EF=BC=8C=E5=9C=A8spring=20cont?= =?UTF-8?q?ext=E5=AE=B9=E5=99=A8=E9=94=80=E6=AF=81=E6=97=B6=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E8=AF=A5=E6=96=B9=E6=B3=95=E9=87=8A=E6=94=BE=E8=B5=84?= =?UTF-8?q?=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../support/AbstractClusterInvoker.java | 154 +- .../dubbo/config/ApplicationConfig.java | 79 +- .../schema/DubboBeanDefinitionParser.java | 186 +- .../src/main/resources/META-INF/dubbo.xsd | 2319 +++++++++-------- .../curator/CuratorZookeeperClient.java | 240 +- .../rpc/protocol/dubbo/DubboProtocol.java | 2 +- .../com/caucho/hessian/io/Hessian2Output.java | 5 +- 7 files changed, 1494 insertions(+), 1491 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index bb895faf4c7..c3017c7ed24 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.rpc.cluster.support; -import java.util.ArrayList; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -33,35 +30,38 @@ import com.alibaba.dubbo.rpc.cluster.LoadBalance; import com.alibaba.dubbo.rpc.support.RpcUtils; +import java.util.ArrayList; +import java.util.List; + /** * AbstractClusterInvoker - * + * * @author william.liangf * @author chao.liuc */ public abstract class AbstractClusterInvoker implements Invoker { - private static final Logger logger = LoggerFactory - .getLogger(AbstractClusterInvoker.class); - protected final Directory directory; + private static final Logger logger = LoggerFactory.getLogger(AbstractClusterInvoker.class); - protected final boolean availablecheck; - - private volatile boolean destroyed = false; + protected final Directory directory; - private volatile Invoker stickyInvoker = null; + protected final boolean availablecheck; + + private volatile boolean destroyed = false; + + private volatile Invoker stickyInvoker = null; public AbstractClusterInvoker(Directory directory) { this(directory, directory.getUrl()); } - + public AbstractClusterInvoker(Directory directory, URL url) { if (directory == null) throw new IllegalArgumentException("service directory == null"); - - this.directory = directory ; + + this.directory = directory; //sticky 需要检测 avaliablecheck - this.availablecheck = url.getParameter(Constants.CLUSTER_AVAILABLE_CHECK_KEY, Constants.DEFAULT_CLUSTER_AVAILABLE_CHECK) ; + this.availablecheck = url.getParameter(Constants.CLUSTER_AVAILABLE_CHECK_KEY, Constants.DEFAULT_CLUSTER_AVAILABLE_CHECK); } public Class getInterface() { @@ -88,39 +88,38 @@ public void destroy() { /** * 使用loadbalance选择invoker.
* a)先lb选择,如果在selected列表中 或者 不可用且做检验时,进入下一步(重选),否则直接返回
- * b)重选验证规则:selected > available .保证重选出的结果尽量不在select中,并且是可用的 - * + * b)重选验证规则:selected > available .保证重选出的结果尽量不在select中,并且是可用的 + * * @param availablecheck 如果设置true,在选择的时候先选invoker.available == true - * @param selected 已选过的invoker.注意:输入保证不重复 - * + * @param selected 已选过的invoker.注意:输入保证不重复 */ protected Invoker select(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); - - boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName,Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY) ; + + boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { //ignore overloaded method - if ( stickyInvoker != null && !invokers.contains(stickyInvoker) ){ + if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } //ignore cucurrent problem - if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))){ - if (availablecheck && stickyInvoker.isAvailable()){ + if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { + if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } - Invoker invoker = doselect(loadbalance, invocation, invokers, selected); - - if (sticky){ + Invoker invoker = doSelect(loadbalance, invocation, invokers, selected); + + if (sticky) { stickyInvoker = invoker; } return invoker; } - - private Invoker doselect(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { + + private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; if (invokers.size() == 1) @@ -130,33 +129,34 @@ private Invoker doselect(LoadBalance loadbalance, Invocation invocation, List return selected.get(0) == invokers.get(0) ? invokers.get(1) : invokers.get(0); } Invoker invoker = loadbalance.select(invokers, getUrl(), invocation); - + //如果 selected中包含(优先判断) 或者 不可用&&availablecheck=true 则重试. - if( (selected != null && selected.contains(invoker)) - ||(!invoker.isAvailable() && getUrl()!=null && availablecheck)){ - try{ + if ((selected != null && selected.contains(invoker)) + || (!invoker.isAvailable() && getUrl() != null && availablecheck)) { + try { Invoker rinvoker = reselect(loadbalance, invocation, invokers, selected, availablecheck); - if(rinvoker != null){ - invoker = rinvoker; - }else{ + if (rinvoker != null) { + invoker = rinvoker; + } else { //看下第一次选的位置,如果不是最后,选+1位置. int index = invokers.indexOf(invoker); - try{ + try { //最后在避免碰撞 - invoker = index doselect(LoadBalance loadbalance, Invocation invocation, List * @return * @throws RpcException */ - private Invoker reselect(LoadBalance loadbalance,Invocation invocation, - List> invokers, List> selected ,boolean availablecheck) + private Invoker reselect(LoadBalance loadbalance, Invocation invocation, + List> invokers, List> selected, boolean availablecheck) throws RpcException { - + //预先分配一个,这个列表是一定会用到的. - List> reselectInvokers = new ArrayList>(invokers.size()>1?(invokers.size()-1):invokers.size()); - + List> reselectInvokers = new ArrayList>(invokers.size() > 1 ? (invokers.size() - 1) : invokers.size()); + //先从非select中选 - if( availablecheck ){ //选isAvailable 的非select - for(Invoker invoker : invokers){ - if(invoker.isAvailable()){ - if(selected ==null || !selected.contains(invoker)){ + if (availablecheck) { //选isAvailable 的非select + for (Invoker invoker : invokers) { + if (invoker.isAvailable()) { + if (selected == null || !selected.contains(invoker)) { reselectInvokers.add(invoker); } } } - if(reselectInvokers.size()>0){ - return loadbalance.select(reselectInvokers, getUrl(), invocation); + if (reselectInvokers.size() > 0) { + return loadbalance.select(reselectInvokers, getUrl(), invocation); } - }else{ //选全部非select - for(Invoker invoker : invokers){ - if(selected ==null || !selected.contains(invoker)){ + } else { //选全部非select + for (Invoker invoker : invokers) { + if (selected == null || !selected.contains(invoker)) { reselectInvokers.add(invoker); } } - if(reselectInvokers.size()>0){ - return loadbalance.select(reselectInvokers, getUrl(), invocation); + if (reselectInvokers.size() > 0) { + return loadbalance.select(reselectInvokers, getUrl(), invocation); } } //最后从select中选可用的. { - if(selected != null){ - for(Invoker invoker : selected){ - if((invoker.isAvailable()) //优先选available - && !reselectInvokers.contains(invoker)){ + if (selected != null) { + for (Invoker invoker : selected) { + if ((invoker.isAvailable()) //优先选available + && !reselectInvokers.contains(invoker)) { reselectInvokers.add(invoker); } } } - if(reselectInvokers.size()>0){ - return loadbalance.select(reselectInvokers, getUrl(), invocation); + if (reselectInvokers.size() > 0) { + return loadbalance.select(reselectInvokers, getUrl(), invocation); } } return null; } - + public Result invoke(final Invocation invocation) throws RpcException { checkWheatherDestoried(); LoadBalance loadbalance; - + List> invokers = list(invocation); if (invokers != null && invokers.size() > 0) { loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl() - .getMethodParameter(invocation.getMethodName(),Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE)); + .getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE)); } else { loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE); } @@ -229,7 +229,7 @@ public Result invoke(final Invocation invocation) throws RpcException { protected void checkWheatherDestoried() { - if(destroyed){ + if (destroyed) { throw new RpcException("Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + " is now destroyed! Can not invoke any more."); @@ -240,13 +240,13 @@ protected void checkWheatherDestoried() { public String toString() { return getInterface() + " -> " + getUrl().toString(); } - + protected void checkInvokers(List> invokers, Invocation invocation) { if (invokers == null || invokers.size() == 0) { throw new RpcException("Failed to invoke the method " - + invocation.getMethodName() + " in the service " + getInterface().getName() + + invocation.getMethodName() + " in the service " + getInterface().getName() + ". No provider available for the service " + directory.getUrl().getServiceKey() - + " from registry " + directory.getUrl().getAddress() + + " from registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Please check if the providers have been started and registered."); @@ -255,9 +255,9 @@ protected void checkInvokers(List> invokers, Invocation invocation) { protected abstract Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException; - - protected List> list(Invocation invocation) throws RpcException { - List> invokers = directory.list(invocation); - return invokers; + + protected List> list(Invocation invocation) throws RpcException { + List> invokers = directory.list(invocation); + return invokers; } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java index 5f535e8a3e9..605fe34f8dd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java @@ -15,65 +15,67 @@ */ package com.alibaba.dubbo.config; -import java.util.ArrayList; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.compiler.support.AdaptiveCompiler; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.config.support.Parameter; +import java.util.ArrayList; +import java.util.List; + /** * ApplicationConfig - * + * * @author william.liangf * @export */ public class ApplicationConfig extends AbstractConfig { - private static final long serialVersionUID = 5508512956753757169L; + private static final long serialVersionUID = 5508512956753757169L; // 应用名称 - private String name; + private String name; // 模块版本 - private String version; + private String version; // 应用负责人 - private String owner; + private String owner; // 组织名(BU或部门) - private String organization; + private String organization; // 分层 - private String architecture; + private String architecture; // 环境,如:dev/test/run - private String environment; + private String environment; // Java代码编译器 - private String compiler; + private String compiler; // 日志输出方式 - private String logger; + private String logger; // 注册中心 private List registries; // 服务监控 - private MonitorConfig monitor; + private MonitorConfig monitor; // 是否为缺省 - private Boolean isDefault; + private Boolean isDefault; + + private boolean closed; public ApplicationConfig() { } - + public ApplicationConfig(String name) { setName(name); } - + @Parameter(key = Constants.APPLICATION_KEY, required = true) public String getName() { return name; @@ -105,16 +107,16 @@ public void setOwner(String owner) { this.owner = owner; } - public String getOrganization() { - return organization; - } + public String getOrganization() { + return organization; + } - public void setOrganization(String organization) { - checkName("organization", organization); - this.organization = organization; - } + public void setOrganization(String organization) { + checkName("organization", organization); + this.organization = organization; + } - public String getArchitecture() { + public String getArchitecture() { return architecture; } @@ -124,18 +126,18 @@ public void setArchitecture(String architecture) { } public String getEnvironment() { - return environment; - } + return environment; + } - public void setEnvironment(String environment) { - checkName("environment", environment); - if(environment != null) { - if (! ("develop".equals(environment) || "test".equals(environment) || "product".equals(environment))) { + public void setEnvironment(String environment) { + checkName("environment", environment); + if (environment != null) { + if (!("develop".equals(environment) || "test".equals(environment) || "product".equals(environment))) { throw new IllegalStateException("Unsupported environment: " + environment + ", only support develop/test/product, default is product."); } } - this.environment = environment; - } + this.environment = environment; + } public RegistryConfig getRegistry() { return registries == null || registries.size() == 0 ? null : registries.get(0); @@ -151,9 +153,9 @@ public List getRegistries() { return registries; } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public void setRegistries(List registries) { - this.registries = (List)registries; + this.registries = (List) registries; } public MonitorConfig getMonitor() { @@ -194,4 +196,11 @@ public void setDefault(Boolean isDefault) { this.isDefault = isDefault; } + public synchronized void close() { + if (closed) { + return; + } + ProtocolConfig.destroyAll(); + closed = true; + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java index c95f8c51546..9b842f04663 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java @@ -15,13 +15,16 @@ */ package com.alibaba.dubbo.config.spring.schema; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.regex.Pattern; - +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ReflectUtils; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.config.*; +import com.alibaba.dubbo.config.spring.ReferenceBean; +import com.alibaba.dubbo.config.spring.ServiceBean; +import com.alibaba.dubbo.rpc.Protocol; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; @@ -33,39 +36,28 @@ import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.ReflectUtils; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.config.ArgumentConfig; -import com.alibaba.dubbo.config.ConsumerConfig; -import com.alibaba.dubbo.config.MethodConfig; -import com.alibaba.dubbo.config.MonitorConfig; -import com.alibaba.dubbo.config.ProtocolConfig; -import com.alibaba.dubbo.config.ProviderConfig; -import com.alibaba.dubbo.config.RegistryConfig; -import com.alibaba.dubbo.config.spring.ReferenceBean; -import com.alibaba.dubbo.config.spring.ServiceBean; -import com.alibaba.dubbo.rpc.Protocol; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Pattern; /** * AbstractBeanDefinitionParser - * + * * @author william.liangf * @export */ public class DubboBeanDefinitionParser implements BeanDefinitionParser { - + private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class); - + private final Class beanClass; - + private final boolean required; public DubboBeanDefinitionParser(Class beanClass, boolean required) { @@ -76,7 +68,7 @@ public DubboBeanDefinitionParser(Class beanClass, boolean required) { public BeanDefinition parse(Element element, ParserContext parserContext) { return parse(element, parserContext, beanClass, required); } - + @SuppressWarnings("unchecked") private static BeanDefinition parse(Element element, ParserContext parserContext, Class beanClass, boolean required) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); @@ -84,30 +76,34 @@ private static BeanDefinition parse(Element element, ParserContext parserContext beanDefinition.setLazyInit(false); String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { - String generatedBeanName = element.getAttribute("name"); - if (generatedBeanName == null || generatedBeanName.length() == 0) { - if (ProtocolConfig.class.equals(beanClass)) { - generatedBeanName = "dubbo"; - } else { - generatedBeanName = element.getAttribute("interface"); - } - } - if (generatedBeanName == null || generatedBeanName.length() == 0) { - generatedBeanName = beanClass.getName(); - } - id = generatedBeanName; + String generatedBeanName = element.getAttribute("name"); + if (generatedBeanName == null || generatedBeanName.length() == 0) { + if (ProtocolConfig.class.equals(beanClass)) { + generatedBeanName = "dubbo"; + } else { + generatedBeanName = element.getAttribute("interface"); + } + } + if (generatedBeanName == null || generatedBeanName.length() == 0) { + generatedBeanName = beanClass.getName(); + } + id = generatedBeanName; int counter = 2; - while(parserContext.getRegistry().containsBeanDefinition(id)) { - id = generatedBeanName + (counter ++); + while (parserContext.getRegistry().containsBeanDefinition(id)) { + id = generatedBeanName + (counter++); } } if (id != null && id.length() > 0) { - if (parserContext.getRegistry().containsBeanDefinition(id)) { - throw new IllegalStateException("Duplicate spring bean id " + id); - } + if (parserContext.getRegistry().containsBeanDefinition(id)) { + throw new IllegalStateException("Duplicate spring bean id " + id); + } parserContext.getRegistry().registerBeanDefinition(id, beanDefinition); beanDefinition.getPropertyValues().addPropertyValue("id", id); } + String destroyMethodName = element.getAttribute("destroy-method"); + if (!StringUtils.isEmpty(destroyMethodName)) { + beanDefinition.setDestroyMethodName(destroyMethodName); + } if (ProtocolConfig.class.equals(beanClass)) { for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); @@ -121,7 +117,7 @@ private static BeanDefinition parse(Element element, ParserContext parserContext } } else if (ServiceBean.class.equals(beanClass)) { String className = element.getAttribute("class"); - if(className != null && className.length() > 0) { + if (className != null && className.length() > 0) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass(ReflectUtils.forName(className)); classDefinition.setLazyInit(false); @@ -145,20 +141,23 @@ private static BeanDefinition parse(Element element, ParserContext parserContext props.add(property); Method getter = null; try { - getter = beanClass.getMethod("get" + name.substring(3), new Class[0]); + getter = beanClass.getMethod("get" + name.substring(3)); } catch (NoSuchMethodException e) { try { - getter = beanClass.getMethod("is" + name.substring(3), new Class[0]); - } catch (NoSuchMethodException e2) { + getter = beanClass.getMethod("is" + name.substring(3)); + } catch (NoSuchMethodException ignored) { } } - if (getter == null - || ! Modifier.isPublic(getter.getModifiers()) - || ! type.equals(getter.getReturnType())) { + if (getter == null + || !Modifier.isPublic(getter.getModifiers()) + || !type.equals(getter.getReturnType())) { continue; } if ("parameters".equals(property)) { parameters = parseParameters(element.getChildNodes(), beanDefinition); + if (parameters != null) { + beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters); + } } else if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), beanDefinition, parserContext); } else if ("arguments".equals(property)) { @@ -166,16 +165,16 @@ private static BeanDefinition parse(Element element, ParserContext parserContext } else { String value = element.getAttribute(property); if (value != null) { - value = value.trim(); - if (value.length() > 0) { - if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { - RegistryConfig registryConfig = new RegistryConfig(); - registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); - beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig); + value = value.trim(); + if (value.length() > 0) { + if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); + beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig); } else if ("registry".equals(property) && value.indexOf(',') != -1) { - parseMultiRef("registries", value, beanDefinition, parserContext); + parseMultiRef("registries", value, beanDefinition, parserContext); } else if ("provider".equals(property) && value.indexOf(',') != -1) { - parseMultiRef("providers", value, beanDefinition, parserContext); + parseMultiRef("providers", value, beanDefinition, parserContext); } else if ("protocol".equals(property) && value.indexOf(',') != -1) { parseMultiRef("protocols", value, beanDefinition, parserContext); } else { @@ -191,10 +190,10 @@ private static BeanDefinition parse(Element element, ParserContext parserContext value = null; } reference = value; - } else if ("protocol".equals(property) + } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) - && (! parserContext.getRegistry().containsBeanDefinition(value) - || ! ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { + && (!parserContext.getRegistry().containsBeanDefinition(value) + || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { if ("dubbo:provider".equals(element.getTagName())) { logger.warn("Recommended replace to "); } @@ -202,9 +201,9 @@ private static BeanDefinition parse(Element element, ParserContext parserContext ProtocolConfig protocol = new ProtocolConfig(); protocol.setName(value); reference = protocol; - } else if ("monitor".equals(property) - && (! parserContext.getRegistry().containsBeanDefinition(value) - || ! MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { + } else if ("monitor".equals(property) + && (!parserContext.getRegistry().containsBeanDefinition(value) + || !MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { // 兼容旧版本配置 reference = convertMonitor(value); } else if ("onreturn".equals(property)) { @@ -222,40 +221,24 @@ private static BeanDefinition parse(Element element, ParserContext parserContext } else { if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); - if (! refBean.isSingleton()) { - throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: "); + if (!refBean.isSingleton()) { + throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: "); } } reference = new RuntimeBeanReference(value); } - beanDefinition.getPropertyValues().addPropertyValue(property, reference); + beanDefinition.getPropertyValues().addPropertyValue(property, reference); } - } + } } } } } - NamedNodeMap attributes = element.getAttributes(); - int len = attributes.getLength(); - for (int i = 0; i < len; i++) { - Node node = attributes.item(i); - String name = node.getLocalName(); - if (! props.contains(name)) { - if (parameters == null) { - parameters = new ManagedMap(); - } - String value = node.getNodeValue(); - parameters.put(name, new TypedStringValue(value, String.class)); - } - } - if (parameters != null) { - beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters); - } return beanDefinition; } private static final Pattern GROUP_AND_VERION = Pattern.compile("^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$"); - + protected static MonitorConfig convertMonitor(String monitor) { if (monitor == null || monitor.length() == 0) { return null; @@ -278,31 +261,30 @@ protected static MonitorConfig convertMonitor(String monitor) { } return null; } - + private static boolean isPrimitive(Class cls) { return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class || cls == Character.class || cls == Short.class || cls == Integer.class || cls == Long.class || cls == Float.class || cls == Double.class || cls == String.class || cls == Date.class || cls == Class.class; } - + @SuppressWarnings("unchecked") - private static void parseMultiRef(String property, String value, RootBeanDefinition beanDefinition, - ParserContext parserContext) { - String[] values = value.split("\\s*[,]+\\s*"); - ManagedList list = null; - for (int i = 0; i < values.length; i++) { - String v = values[i]; + private static void parseMultiRef(String property, String value, RootBeanDefinition beanDefinition, + ParserContext parserContext) { + String[] values = value.split("\\s*[,]+\\s*"); + ManagedList list = null; + for (String v : values) { if (v != null && v.length() > 0) { - if (list == null) { + if (list == null) { list = new ManagedList(); } - list.add(new RuntimeBeanReference(v)); + list.add(new RuntimeBeanReference(v)); } } beanDefinition.getPropertyValues().addPropertyValue(property, list); } - + private static void parseNested(Element element, ParserContext parserContext, Class beanClass, boolean required, String tag, String property, String ref, BeanDefinition beanDefinition) { NodeList nodeList = element.getChildNodes(); if (nodeList != null && nodeList.getLength() > 0) { @@ -383,7 +365,7 @@ private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition @SuppressWarnings("unchecked") private static void parseMethods(String id, NodeList nodeList, RootBeanDefinition beanDefinition, - ParserContext parserContext) { + ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList methods = null; for (int i = 0; i < nodeList.getLength(); i++) { @@ -412,10 +394,10 @@ private static void parseMethods(String id, NodeList nodeList, RootBeanDefinitio } } } - + @SuppressWarnings("unchecked") private static void parseArguments(String id, NodeList nodeList, RootBeanDefinition beanDefinition, - ParserContext parserContext) { + ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList arguments = null; for (int i = 0; i < nodeList.getLength(); i++) { diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index d0168856cd4..93f1ae5eac3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -1,783 +1,800 @@ - - - - + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:beans="http://www.springframework.org/schema/beans" + xmlns:tool="http://www.springframework.org/schema/tool" + targetNamespace="http://code.alibabatech.com/schema/dubbo"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -796,387 +813,391 @@ - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index ff9203fd060..dc091f954cf 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -1,8 +1,10 @@ package com.alibaba.dubbo.remoting.zookeeper.curator; -import java.util.List; - import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.zookeeper.ChildListener; +import com.alibaba.dubbo.remoting.zookeeper.StateListener; +import com.alibaba.dubbo.remoting.zookeeper.support.AbstractZookeeperClient; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorFrameworkFactory.Builder; @@ -14,132 +16,122 @@ import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.WatchedEvent; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.zookeeper.ChildListener; -import com.alibaba.dubbo.remoting.zookeeper.StateListener; -import com.alibaba.dubbo.remoting.zookeeper.support.AbstractZookeeperClient; import org.apache.zookeeper.Watcher; -public class CuratorZookeeperClient extends - AbstractZookeeperClient { +import java.util.List; + +public class CuratorZookeeperClient extends AbstractZookeeperClient { - private final CuratorFramework client; + private final CuratorFramework client; - public CuratorZookeeperClient(URL url) { - super(url); - Builder builder = CuratorFrameworkFactory.builder() - .connectString(url.getBackupAddress()) - .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)) - .connectionTimeoutMs(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT)) + public CuratorZookeeperClient(URL url) { + super(url); + Builder builder = CuratorFrameworkFactory.builder() + .connectString(url.getBackupAddress()) + .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)) + .connectionTimeoutMs(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT)) .sessionTimeoutMs(url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT)); - String authority = url.getAuthority(); - if (authority != null && authority.length() > 0) { - builder = builder.authorization("digest", authority.getBytes()); - } - client = builder.build(); - client.getConnectionStateListenable().addListener( - new ConnectionStateListener() { - public void stateChanged(CuratorFramework client, - ConnectionState state) { - if (state == ConnectionState.LOST) { - CuratorZookeeperClient.this - .stateChanged(StateListener.DISCONNECTED); - } else if (state == ConnectionState.CONNECTED) { - CuratorZookeeperClient.this - .stateChanged(StateListener.CONNECTED); - } else if (state == ConnectionState.RECONNECTED) { - CuratorZookeeperClient.this - .stateChanged(StateListener.RECONNECTED); - } - } - }); - client.start(); - } - - public void createPersistent(String path) { - try { - client.create().forPath(path); - } catch (NodeExistsException e) { - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void createEphemeral(String path) { - try { - client.create().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (NodeExistsException e) { - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void delete(String path) { - try { - client.delete().forPath(path); - } catch (NoNodeException e) { - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public List getChildren(String path) { - try { - return client.getChildren().forPath(path); - } catch (NoNodeException e) { - return null; - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public boolean isConnected() { - return client.getZookeeperClient().isConnected(); - } - - public void doClose() { - client.close(); - } - - private class CuratorWatcherImpl implements CuratorWatcher { - - private volatile ChildListener listener; - - public CuratorWatcherImpl(ChildListener listener) { - this.listener = listener; - } - - public void unwatch() { - this.listener = null; - } - - public void process(WatchedEvent event) throws Exception { - if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged && listener != null) { - listener.childChanged(event.getPath(), client.getChildren() - .usingWatcher(this).forPath(event.getPath())); - } - } - } - - public CuratorWatcher createTargetChildListener(String path, - ChildListener listener) { - return new CuratorWatcherImpl(listener); - } - - public List addTargetChildListener(String path, - CuratorWatcher listener) { - try { - return client.getChildren().usingWatcher(listener).forPath(path); - } catch (NoNodeException e) { - return null; - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void removeTargetChildListener(String path, CuratorWatcher listener) { - ((CuratorWatcherImpl) listener).unwatch(); - } + String authority = url.getAuthority(); + if (authority != null && authority.length() > 0) { + builder = builder.authorization("digest", authority.getBytes()); + } + client = builder.build(); + client.getConnectionStateListenable().addListener( + new ConnectionStateListener() { + public void stateChanged(CuratorFramework client, ConnectionState state) { + if (state == ConnectionState.LOST) { + CuratorZookeeperClient.this.stateChanged(StateListener.DISCONNECTED); + } else if (state == ConnectionState.CONNECTED) { + CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED); + } else if (state == ConnectionState.RECONNECTED) { + CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED); + } + } + }); + client.start(); + } + + public void createPersistent(String path) { + try { + client.create().forPath(path); + } catch (NodeExistsException e) { + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public void createEphemeral(String path) { + try { + client.create().withMode(CreateMode.EPHEMERAL).forPath(path); + } catch (NodeExistsException e) { + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public void delete(String path) { + try { + client.delete().forPath(path); + } catch (NoNodeException e) { + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public List getChildren(String path) { + try { + return client.getChildren().forPath(path); + } catch (NoNodeException e) { + return null; + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public boolean isConnected() { + return client.getZookeeperClient().isConnected(); + } + + public void doClose() { + client.close(); + } + + private class CuratorWatcherImpl implements CuratorWatcher { + + private volatile ChildListener listener; + + public CuratorWatcherImpl(ChildListener listener) { + this.listener = listener; + } + + public void unwatch() { + this.listener = null; + } + + public void process(WatchedEvent event) throws Exception { + if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged && listener != null) { + listener.childChanged(event.getPath(), client.getChildren() + .usingWatcher(this).forPath(event.getPath())); + } + } + } + + public CuratorWatcher createTargetChildListener(String path, ChildListener listener) { + return new CuratorWatcherImpl(listener); + } + + public List addTargetChildListener(String path, CuratorWatcher listener) { + try { + return client.getChildren().usingWatcher(listener).forPath(path); + } catch (NoNodeException e) { + return null; + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + public void removeTargetChildListener(String path, CuratorWatcher listener) { + ((CuratorWatcherImpl) listener).unwatch(); + } } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index b90cd1274db..79c2d451e38 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -93,7 +93,7 @@ public Object reply(ExchangeChannel channel, Object message) throws RemotingExce 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){ + if (methodsStr == null || !methodsStr.contains(",")){ hasMethod = inv.getMethodName().equals(methodsStr); } else { String[] methods = methodsStr.split(","); diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java index 657d4d2edde..663a78dfc0e 100644 --- a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java @@ -130,9 +130,8 @@ public void call(String method, Object []args) int length = args != null ? args.length : 0; startCall(method, length); - - for (int i = 0; i < args.length; i++) - writeObject(args[i]); + + for (Object arg : args) writeObject(arg); completeCall(); } From 8c7c008685966b38a0a68a7fce7996cb0b5947f5 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 2 Jan 2017 23:03:36 +0800 Subject: [PATCH 03/69] okhttpclient --- .../com/alibaba/dubbo/common/Constants.java | 537 +++---- .../dubbo/config/spring/AnnotationBean.java | 128 +- .../dubbo/config/spring/ReferenceBean.java | 12 +- .../dubbo/config/spring/ServiceBean.java | 26 +- .../dubbo/remoting/exchange/Request.java | 28 +- .../exchange/codec/ExchangeCodec.java | 71 +- .../support/header/HeaderExchangeServer.java | 81 +- .../support/header/HeartBeatTask.java | 66 +- .../remoting/transport/AbstractClient.java | 211 ++- .../remoting/transport/AbstractEndpoint.java | 22 +- .../http/servlet/DispatcherServlet.java | 82 +- .../http/tomcat/TomcatHttpServer.java | 10 +- .../remoting/transport/netty/NettyServer.java | 45 +- .../com/alibaba/dubbo/rpc/RpcInvocation.java | 56 +- .../java/com/alibaba/dubbo/rpc/RpcResult.java | 22 +- .../rpc/listener/ListenerInvokerWrapper.java | 20 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 114 +- .../dubbo/DecodeableRpcInvocation.java | 20 +- .../rpc/protocol/dubbo/DubboProtocol.java | 179 +-- .../dubbo/LazyConnectExchangeClient.java | 188 +-- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 4 + .../hessian/AbstractHessianConnection.java | 33 + .../rpc/protocol/hessian/HessianProtocol.java | 133 +- .../hessian/HttpClientConnection.java | 33 +- .../protocol/hessian/OkHttpConnection.java | 53 + .../hessian/OkHttpConnectionFactory.java | 43 + .../protocol/hessian/HessianProtocolTest.java | 19 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 70 +- .../rpc/protocol/rest/DubboHttpServer.java | 9 +- .../rpc/protocol/rest/RestServerFactory.java | 10 +- .../protocol/rest/support/LoggingFilter.java | 9 +- .../rpc/protocol/thrift/ThriftCodec.java | 560 +++---- dubbo-tracker/dubbo-tracker-api/pom.xml | 23 + .../com/alibaba/dubbo/tracker/RpcTracker.java | 10 + dubbo-tracker/pom.xml | 18 + pom.xml | 1332 +++++++++-------- 36 files changed, 2247 insertions(+), 2030 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/AbstractHessianConnection.java create mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnection.java create mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-api/pom.xml create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java create mode 100644 dubbo-tracker/pom.xml diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 2c712237bc6..4ce3a7a4de9 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -20,425 +20,425 @@ /** * Constants - * + * * @author william.liangf */ public class Constants { - public static final String PROVIDER = "provider"; + public static final String PROVIDER = "provider"; - public static final String CONSUMER = "consumer"; + public static final String CONSUMER = "consumer"; - public static final String REGISTER = "register"; + public static final String REGISTER = "register"; - public static final String UNREGISTER = "unregister"; + public static final String UNREGISTER = "unregister"; - public static final String SUBSCRIBE = "subscribe"; + public static final String SUBSCRIBE = "subscribe"; - public static final String UNSUBSCRIBE = "unsubscribe"; - - public static final String CATEGORY_KEY = "category"; + public static final String UNSUBSCRIBE = "unsubscribe"; - public static final String PROVIDERS_CATEGORY = "providers"; + public static final String CATEGORY_KEY = "category"; - public static final String CONSUMERS_CATEGORY = "consumers"; + public static final String PROVIDERS_CATEGORY = "providers"; - public static final String ROUTERS_CATEGORY = "routers"; + public static final String CONSUMERS_CATEGORY = "consumers"; - public static final String CONFIGURATORS_CATEGORY = "configurators"; + public static final String ROUTERS_CATEGORY = "routers"; - public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; + public static final String CONFIGURATORS_CATEGORY = "configurators"; - public static final String ENABLED_KEY = "enabled"; + public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; - public static final String DISABLED_KEY = "disabled"; + public static final String ENABLED_KEY = "enabled"; - public static final String VALIDATION_KEY = "validation"; + public static final String DISABLED_KEY = "disabled"; - public static final String CACHE_KEY = "cache"; + public static final String VALIDATION_KEY = "validation"; - public static final String DYNAMIC_KEY = "dynamic"; + public static final String CACHE_KEY = "cache"; - public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; + public static final String DYNAMIC_KEY = "dynamic"; - public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; + public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; - public static final String SENT_KEY = "sent"; + public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; - public static final boolean DEFAULT_SENT = false; + public static final String SENT_KEY = "sent"; - public static final String REGISTRY_PROTOCOL = "registry"; + public static final boolean DEFAULT_SENT = false; - public static final String $INVOKE = "$invoke"; + public static final String REGISTRY_PROTOCOL = "registry"; - public static final String $ECHO = "$echo"; + public static final String $INVOKE = "$invoke"; - public static final int DEFAULT_IO_THREADS = Runtime.getRuntime() - .availableProcessors() + 1; + public static final String $ECHO = "$echo"; - public static final String DEFAULT_PROXY = "javassist"; + public static final int DEFAULT_IO_THREADS = Runtime.getRuntime() + .availableProcessors() + 1; - public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; // 8M + public static final String DEFAULT_PROXY = "javassist"; - public static final String DEFAULT_CLUSTER = "failover"; + public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; // 8M - public static final String DEFAULT_DIRECTORY = "dubbo"; + public static final String DEFAULT_CLUSTER = "failover"; - public static final String DEFAULT_LOADBALANCE = "random"; + public static final String DEFAULT_DIRECTORY = "dubbo"; - public static final String DEFAULT_PROTOCOL = "dubbo"; + public static final String DEFAULT_LOADBALANCE = "random"; - public static final String DEFAULT_EXCHANGER = "header"; + public static final String DEFAULT_PROTOCOL = "dubbo"; - public static final String DEFAULT_TRANSPORTER = "netty"; + public static final String DEFAULT_EXCHANGER = "header"; - public static final String DEFAULT_REMOTING_SERVER = "netty"; + public static final String DEFAULT_TRANSPORTER = "netty"; - public static final String DEFAULT_REMOTING_CLIENT = "netty"; + public static final String DEFAULT_REMOTING_SERVER = "netty"; - public static final String DEFAULT_REMOTING_CODEC = "dubbo"; + public static final String DEFAULT_REMOTING_CLIENT = "netty"; - public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; + public static final String DEFAULT_REMOTING_CODEC = "dubbo"; - public static final String DEFAULT_HTTP_SERVER = "servlet"; + public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; - public static final String DEFAULT_HTTP_CLIENT = "jdk"; + public static final String DEFAULT_HTTP_SERVER = "servlet"; - public static final String DEFAULT_HTTP_SERIALIZATION = "json"; + public static final String DEFAULT_HTTP_CLIENT = "jdk"; - public static final String DEFAULT_CHARSET = "UTF-8"; + public static final String DEFAULT_HTTP_SERIALIZATION = "json"; - public static final int DEFAULT_WEIGHT = 100; + public static final String DEFAULT_CHARSET = "UTF-8"; - public static final int DEFAULT_FORKS = 2; + public static final int DEFAULT_WEIGHT = 100; - public static final String DEFAULT_THREAD_NAME = "Dubbo"; + public static final int DEFAULT_FORKS = 2; - public static final int DEFAULT_CORE_THREADS = 0; + public static final String DEFAULT_THREAD_NAME = "Dubbo"; - public static final int DEFAULT_THREADS = 200; + public static final int DEFAULT_CORE_THREADS = 0; + + public static final int DEFAULT_THREADS = 200; public static final boolean DEFAULT_KEEP_ALIVE = true; - public static final int DEFAULT_QUEUES = 0; + public static final int DEFAULT_QUEUES = 0; - public static final int DEFAULT_ALIVE = 60 * 1000; + public static final int DEFAULT_ALIVE = 60 * 1000; - public static final int DEFAULT_CONNECTIONS = 0; + public static final int DEFAULT_CONNECTIONS = 0; - public static final int DEFAULT_ACCEPTS = 0; + public static final int DEFAULT_ACCEPTS = 0; - public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; + public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; - public static final int DEFAULT_HEARTBEAT = 60 * 1000; + public static final int DEFAULT_HEARTBEAT = 60 * 1000; - public static final int DEFAULT_TIMEOUT = 1000; + public static final int DEFAULT_TIMEOUT = 1000; - public static final int DEFAULT_CONNECT_TIMEOUT = 3000; + public static final int DEFAULT_CONNECT_TIMEOUT = 3000; - public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; + public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; - public static final int DEFAULT_RETRIES = 2; + public static final int DEFAULT_RETRIES = 2; // default buffer size is 8k. - public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; + public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; - public static final int MAX_BUFFER_SIZE = 16 * 1024; + public static final int MAX_BUFFER_SIZE = 16 * 1024; - public static final int MIN_BUFFER_SIZE = 1 * 1024; + public static final int MIN_BUFFER_SIZE = 1 * 1024; - public static final String REMOVE_VALUE_PREFIX = "-"; + public static final String REMOVE_VALUE_PREFIX = "-"; - public static final String HIDE_KEY_PREFIX = "."; + public static final String HIDE_KEY_PREFIX = "."; - public static final String DEFAULT_KEY_PREFIX = "default."; + public static final String DEFAULT_KEY_PREFIX = "default."; - public static final String DEFAULT_KEY = "default"; + public static final String DEFAULT_KEY = "default"; - public static final String LOADBALANCE_KEY = "loadbalance"; + public static final String LOADBALANCE_KEY = "loadbalance"; // key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME - public static final String ROUTER_KEY = "router"; + public static final String ROUTER_KEY = "router"; - public static final String CLUSTER_KEY = "cluster"; + public static final String CLUSTER_KEY = "cluster"; - public static final String REGISTRY_KEY = "registry"; + public static final String REGISTRY_KEY = "registry"; - public static final String MONITOR_KEY = "monitor"; + public static final String MONITOR_KEY = "monitor"; - public static final String SIDE_KEY = "side"; + public static final String SIDE_KEY = "side"; - public static final String PROVIDER_SIDE = "provider"; + public static final String PROVIDER_SIDE = "provider"; - public static final String CONSUMER_SIDE = "consumer"; + public static final String CONSUMER_SIDE = "consumer"; - public static final String DEFAULT_REGISTRY = "dubbo"; + public static final String DEFAULT_REGISTRY = "dubbo"; - public static final String BACKUP_KEY = "backup"; + public static final String BACKUP_KEY = "backup"; - public static final String DIRECTORY_KEY = "directory"; + public static final String DIRECTORY_KEY = "directory"; - public static final String DEPRECATED_KEY = "deprecated"; + public static final String DEPRECATED_KEY = "deprecated"; - public static final String ANYHOST_KEY = "anyhost"; + public static final String ANYHOST_KEY = "anyhost"; - public static final String ANYHOST_VALUE = "0.0.0.0"; + public static final String ANYHOST_VALUE = "0.0.0.0"; - public static final String LOCALHOST_KEY = "localhost"; + public static final String LOCALHOST_KEY = "localhost"; - public static final String LOCALHOST_VALUE = "127.0.0.1"; + public static final String LOCALHOST_VALUE = "127.0.0.1"; - public static final String APPLICATION_KEY = "application"; + public static final String APPLICATION_KEY = "application"; - public static final String LOCAL_KEY = "local"; + public static final String LOCAL_KEY = "local"; - public static final String STUB_KEY = "stub"; + public static final String STUB_KEY = "stub"; - public static final String MOCK_KEY = "mock"; + public static final String MOCK_KEY = "mock"; - public static final String PROTOCOL_KEY = "protocol"; + public static final String PROTOCOL_KEY = "protocol"; - public static final String PROXY_KEY = "proxy"; + public static final String PROXY_KEY = "proxy"; - public static final String WEIGHT_KEY = "weight"; + public static final String WEIGHT_KEY = "weight"; - public static final String FORKS_KEY = "forks"; + public static final String FORKS_KEY = "forks"; - public static final String DEFAULT_THREADPOOL = "limited"; + public static final String DEFAULT_THREADPOOL = "limited"; - public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; + public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; - public static final String THREADPOOL_KEY = "threadpool"; + public static final String THREADPOOL_KEY = "threadpool"; - public static final String THREAD_NAME_KEY = "threadname"; + public static final String THREAD_NAME_KEY = "threadname"; - public static final String IO_THREADS_KEY = "iothreads"; + public static final String IO_THREADS_KEY = "iothreads"; - public static final String CORE_THREADS_KEY = "corethreads"; + public static final String CORE_THREADS_KEY = "corethreads"; - public static final String THREADS_KEY = "threads"; + public static final String THREADS_KEY = "threads"; - public static final String QUEUES_KEY = "queues"; + public static final String QUEUES_KEY = "queues"; - public static final String ALIVE_KEY = "alive"; + public static final String ALIVE_KEY = "alive"; - public static final String EXECUTES_KEY = "executes"; + public static final String EXECUTES_KEY = "executes"; - public static final String BUFFER_KEY = "buffer"; + public static final String BUFFER_KEY = "buffer"; - public static final String PAYLOAD_KEY = "payload"; + public static final String PAYLOAD_KEY = "payload"; - public static final String REFERENCE_FILTER_KEY = "reference.filter"; + public static final String REFERENCE_FILTER_KEY = "reference.filter"; - public static final String INVOKER_LISTENER_KEY = "invoker.listener"; + public static final String INVOKER_LISTENER_KEY = "invoker.listener"; - public static final String SERVICE_FILTER_KEY = "service.filter"; + public static final String SERVICE_FILTER_KEY = "service.filter"; - public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; + public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; - public static final String ACCESS_LOG_KEY = "accesslog"; + public static final String ACCESS_LOG_KEY = "accesslog"; - public static final String ACTIVES_KEY = "actives"; + public static final String ACTIVES_KEY = "actives"; - public static final String CONNECTIONS_KEY = "connections"; + public static final String CONNECTIONS_KEY = "connections"; - public static final String ACCEPTS_KEY = "accepts"; + public static final String ACCEPTS_KEY = "accepts"; - public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; + public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; - public static final String HEARTBEAT_KEY = "heartbeat"; + public static final String HEARTBEAT_KEY = "heartbeat"; - public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; + public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; - public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; + public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; - public static final String TIMEOUT_KEY = "timeout"; + public static final String TIMEOUT_KEY = "timeout"; - public static final String RETRIES_KEY = "retries"; + public static final String RETRIES_KEY = "retries"; - public static final String PROMPT_KEY = "prompt"; + public static final String PROMPT_KEY = "prompt"; - public static final String DEFAULT_PROMPT = "dubbo>"; + public static final String DEFAULT_PROMPT = "dubbo>"; - public static final String CODEC_KEY = "codec"; + public static final String CODEC_KEY = "codec"; - public static final String SERIALIZATION_KEY = "serialization"; + public static final String SERIALIZATION_KEY = "serialization"; // modified by lishen public static final String EXTENSION_KEY = "extension"; // modified by lishen - public static final String KEEP_ALIVE_KEY = "keepalive"; + public static final String KEEP_ALIVE_KEY = "keepalive"; // modified by lishen // TODO change to a better name - public static final String OPTIMIZER_KEY = "optimizer"; + public static final String OPTIMIZER_KEY = "optimizer"; + + public static final String EXCHANGER_KEY = "exchanger"; - public static final String EXCHANGER_KEY = "exchanger"; + public static final String TRANSPORTER_KEY = "transporter"; - public static final String TRANSPORTER_KEY = "transporter"; + public static final String SERVER_KEY = "server"; - public static final String SERVER_KEY = "server"; + public static final String CLIENT_KEY = "client"; - public static final String CLIENT_KEY = "client"; + public static final String ID_KEY = "id"; - public static final String ID_KEY = "id"; + public static final String ASYNC_KEY = "async"; - public static final String ASYNC_KEY = "async"; + public static final String RETURN_KEY = "return"; - public static final String RETURN_KEY = "return"; + public static final String TOKEN_KEY = "token"; - public static final String TOKEN_KEY = "token"; + public static final String METHOD_KEY = "method"; - public static final String METHOD_KEY = "method"; + public static final String METHODS_KEY = "methods"; - public static final String METHODS_KEY = "methods"; + public static final String CHARSET_KEY = "charset"; - public static final String CHARSET_KEY = "charset"; + public static final String RECONNECT_KEY = "reconnect"; - public static final String RECONNECT_KEY = "reconnect"; + public static final String SEND_RECONNECT_KEY = "send.reconnect"; - public static final String SEND_RECONNECT_KEY = "send.reconnect"; + public static final int DEFAULT_RECONNECT_PERIOD = 2000; - public static final int DEFAULT_RECONNECT_PERIOD = 2000; + public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; - public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; + public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; - public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; + public static final String PID_KEY = "pid"; - public static final String PID_KEY = "pid"; + public static final String TIMESTAMP_KEY = "timestamp"; - public static final String TIMESTAMP_KEY = "timestamp"; - - public static final String WARMUP_KEY = "warmup"; + public static final String WARMUP_KEY = "warmup"; - public static final int DEFAULT_WARMUP = 10 * 60 * 1000; + public static final int DEFAULT_WARMUP = 10 * 60 * 1000; - public static final String CHECK_KEY = "check"; + public static final String CHECK_KEY = "check"; - public static final String REGISTER_KEY = "register"; + public static final String REGISTER_KEY = "register"; - public static final String SUBSCRIBE_KEY = "subscribe"; + public static final String SUBSCRIBE_KEY = "subscribe"; - public static final String GROUP_KEY = "group"; + public static final String GROUP_KEY = "group"; - public static final String PATH_KEY = "path"; + public static final String PATH_KEY = "path"; - public static final String INTERFACE_KEY = "interface"; + public static final String INTERFACE_KEY = "interface"; - public static final String GENERIC_KEY = "generic"; + public static final String GENERIC_KEY = "generic"; - public static final String FILE_KEY = "file"; + public static final String FILE_KEY = "file"; - public static final String WAIT_KEY = "wait"; + public static final String WAIT_KEY = "wait"; - public static final String CLASSIFIER_KEY = "classifier"; + public static final String CLASSIFIER_KEY = "classifier"; - public static final String VERSION_KEY = "version"; + public static final String VERSION_KEY = "version"; - public static final String REVISION_KEY = "revision"; + public static final String REVISION_KEY = "revision"; - public static final String DUBBO_VERSION_KEY = "dubbo"; + public static final String DUBBO_VERSION_KEY = "dubbo"; - public static final String HESSIAN_VERSION_KEY = "hessian.version"; + public static final String HESSIAN_VERSION_KEY = "hessian.version"; - public static final String DISPATCHER_KEY = "dispatcher"; + public static final String DISPATCHER_KEY = "dispatcher"; - public static final String CHANNEL_HANDLER_KEY = "channel.handler"; + public static final String CHANNEL_HANDLER_KEY = "channel.handler"; - public static final String DEFAULT_CHANNEL_HANDLER = "default"; + public static final String DEFAULT_CHANNEL_HANDLER = "default"; - public static final String ANY_VALUE = "*"; + public static final String ANY_VALUE = "*"; - public static final String COMMA_SEPARATOR = ","; + public static final String COMMA_SEPARATOR = ","; - public static final Pattern COMMA_SPLIT_PATTERN = Pattern - .compile("\\s*[,]+\\s*"); + public static final Pattern COMMA_SPLIT_PATTERN = Pattern + .compile("\\s*[,]+\\s*"); - public final static String PATH_SEPARATOR = "/"; + public final static String PATH_SEPARATOR = "/"; - public static final String REGISTRY_SEPARATOR = "|"; + public static final String REGISTRY_SEPARATOR = "|"; - public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern - .compile("\\s*[|;]+\\s*"); + public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern + .compile("\\s*[|;]+\\s*"); - public static final String SEMICOLON_SEPARATOR = ";"; + public static final String SEMICOLON_SEPARATOR = ";"; - public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern - .compile("\\s*[;]+\\s*"); + public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern + .compile("\\s*[;]+\\s*"); - public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; + public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; - public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; + public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; - public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; + public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; - public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; + public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; - public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; + public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; - public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; + public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; - public static final String COUNT_PROTOCOL = "count"; + public static final String COUNT_PROTOCOL = "count"; - public static final String TRACE_PROTOCOL = "trace"; + public static final String TRACE_PROTOCOL = "trace"; - public static final String EMPTY_PROTOCOL = "empty"; + public static final String EMPTY_PROTOCOL = "empty"; - public static final String ADMIN_PROTOCOL = "admin"; + public static final String ADMIN_PROTOCOL = "admin"; - public static final String PROVIDER_PROTOCOL = "provider"; + public static final String PROVIDER_PROTOCOL = "provider"; - public static final String CONSUMER_PROTOCOL = "consumer"; + public static final String CONSUMER_PROTOCOL = "consumer"; - public static final String ROUTE_PROTOCOL = "route"; + public static final String ROUTE_PROTOCOL = "route"; - public static final String SCRIPT_PROTOCOL = "script"; + public static final String SCRIPT_PROTOCOL = "script"; - public static final String CONDITION_PROTOCOL = "condition"; + public static final String CONDITION_PROTOCOL = "condition"; - public static final String MOCK_PROTOCOL = "mock"; + public static final String MOCK_PROTOCOL = "mock"; - public static final String RETURN_PREFIX = "return "; + public static final String RETURN_PREFIX = "return "; - public static final String THROW_PREFIX = "throw"; + public static final String THROW_PREFIX = "throw"; - public static final String FAIL_PREFIX = "fail:"; + public static final String FAIL_PREFIX = "fail:"; - public static final String FORCE_PREFIX = "force:"; + public static final String FORCE_PREFIX = "force:"; - public static final String FORCE_KEY = "force"; + public static final String FORCE_KEY = "force"; - public static final String MERGER_KEY = "merger"; + public static final String MERGER_KEY = "merger"; /** * 集群时是否排除非available的invoker */ - public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; + public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; /** */ - public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; + public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; /** * 集群时是否启用sticky策略 */ - public static final String CLUSTER_STICKY_KEY = "sticky"; + public static final String CLUSTER_STICKY_KEY = "sticky"; /** * sticky默认值. */ - public static final boolean DEFAULT_CLUSTER_STICKY = false; + public static final boolean DEFAULT_CLUSTER_STICKY = false; /** * 创建client时,是否先要建立连接。 */ - public static final String LAZY_CONNECT_KEY = "lazy"; + public static final String LAZY_CONNECT_KEY = "lazy"; /** * lazy连接的初始状态是连接状态还是非连接状态? */ - public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; + public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; /** * lazy连接的初始状态默认是连接状态. @@ -448,150 +448,155 @@ public class Constants { /** * 注册中心是否同步存储文件,默认异步 */ - public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; + public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; /** * 注册中心失败事件重试事件 */ - public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; + public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; /** * 重试周期 */ - public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; - + public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; + /** * 注册中心自动重连时间 */ - public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; + public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; + + public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; - public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; - - public static final String SESSION_TIMEOUT_KEY = "session"; + public static final String SESSION_TIMEOUT_KEY = "session"; - public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; + public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; /** * 注册中心导出URL参数的KEY */ - public static final String EXPORT_KEY = "export"; + public static final String EXPORT_KEY = "export"; /** * 注册中心引用URL参数的KEY */ - public static final String REFER_KEY = "refer"; + public static final String REFER_KEY = "refer"; /** * callback inst id */ - public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; + public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; /** * 每个客户端同一个接口 callback服务实例的限制 */ - public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; + public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; /** * 每个客户端同一个接口 callback服务实例的限制 */ - public static final int DEFAULT_CALLBACK_INSTANCES = 1; + public static final int DEFAULT_CALLBACK_INSTANCES = 1; - public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; + public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; - public static final String IS_CALLBACK_SERVICE = "is_callback_service"; + public static final String IS_CALLBACK_SERVICE = "is_callback_service"; /** * channel中callback的invokers */ - public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; + public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; @Deprecated - public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; - public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; + public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; - public static final String IS_SERVER_KEY = "isserver"; + public static final String IS_SERVER_KEY = "isserver"; /** * 默认值毫秒,避免重新计算. */ - public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; + public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; - public static final String ON_CONNECT_KEY = "onconnect"; + public static final String ON_CONNECT_KEY = "onconnect"; - public static final String ON_DISCONNECT_KEY = "ondisconnect"; + public static final String ON_DISCONNECT_KEY = "ondisconnect"; - public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; + public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; - public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; + public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; - public static final String ON_THROW_METHOD_KEY = "onthrow.method"; + public static final String ON_THROW_METHOD_KEY = "onthrow.method"; - public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; + public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; - public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; + public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; - public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; + public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; - public static final String OVERRIDE_PROTOCOL = "override"; + public static final String OVERRIDE_PROTOCOL = "override"; - public static final String PRIORITY_KEY = "priority"; - - public static final String RULE_KEY = "rule"; + public static final String PRIORITY_KEY = "priority"; - public static final String TYPE_KEY = "type"; + public static final String RULE_KEY = "rule"; - public static final String RUNTIME_KEY = "runtime"; + public static final String TYPE_KEY = "type"; + + public static final String RUNTIME_KEY = "runtime"; // when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers - public static final String ROUTER_TYPE_CLEAR = "clean"; + public static final String ROUTER_TYPE_CLEAR = "clean"; - public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; + public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; - public static final String STUB_EVENT_KEY = "dubbo.stub.event"; + public static final String STUB_EVENT_KEY = "dubbo.stub.event"; - public static final boolean DEFAULT_STUB_EVENT = false; + public static final boolean DEFAULT_STUB_EVENT = false; - public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; + public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; //invocation attachment属性中如果有此值,则选择mock invoker - public static final String INVOCATION_NEED_MOCK = "invocation.need.mock"; + public static final String INVOCATION_NEED_MOCK = "invocation.need.mock"; + + public static final String LOCAL_PROTOCOL = "injvm"; + + public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; + + public static final String SCOPE_KEY = "scope"; + + public static final String SCOPE_LOCAL = "local"; + + public static final String SCOPE_REMOTE = "remote"; + + public static final String SCOPE_NONE = "none"; + + public static final String RELIABLE_PROTOCOL = "napoli"; + + public static final String TPS_LIMIT_RATE_KEY = "tps"; + + public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + + public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + + public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; - public static final String LOCAL_PROTOCOL = "injvm"; + public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; - public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; - - public static final String SCOPE_KEY = "scope"; - - public static final String SCOPE_LOCAL = "local"; - - public static final String SCOPE_REMOTE = "remote"; - - public static final String SCOPE_NONE = "none"; - - public static final String RELIABLE_PROTOCOL = "napoli"; - - public static final String TPS_LIMIT_RATE_KEY = "tps"; + public static final String INPUT_KEY = "input"; - public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; + public static final String OUTPUT_KEY = "output"; - public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; + public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); - public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; + public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; - public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; - - public static final String INPUT_KEY = "input"; - - public static final String OUTPUT_KEY = "output"; + public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; - public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); + public static final String GENERIC_SERIALIZATION_BEAN = "bean"; - public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; + //--------------------------------trace-------------------------------------------------------// - public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; + public static final String ENABLE_TRACE_KEY = "enableTrace"; - public static final String GENERIC_SERIALIZATION_BEAN = "bean"; /* * private Constants(){ } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java index 8f54baacee8..9f4f6c75435 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java @@ -15,15 +15,14 @@ */ package com.alibaba.dubbo.config.spring; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ConcurrentHashSet; +import com.alibaba.dubbo.common.utils.ReflectUtils; +import com.alibaba.dubbo.config.*; +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.annotation.Service; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanInitializationException; @@ -35,27 +34,18 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.ConcurrentHashSet; -import com.alibaba.dubbo.common.utils.ReflectUtils; -import com.alibaba.dubbo.config.AbstractConfig; -import com.alibaba.dubbo.config.ApplicationConfig; -import com.alibaba.dubbo.config.ConsumerConfig; -import com.alibaba.dubbo.config.ModuleConfig; -import com.alibaba.dubbo.config.MonitorConfig; -import com.alibaba.dubbo.config.ProtocolConfig; -import com.alibaba.dubbo.config.ProviderConfig; -import com.alibaba.dubbo.config.ReferenceConfig; -import com.alibaba.dubbo.config.RegistryConfig; -import com.alibaba.dubbo.config.ServiceConfig; -import com.alibaba.dubbo.config.annotation.Reference; -import com.alibaba.dubbo.config.annotation.Service; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * AnnotationBean - * + * * @author william.liangf * @export */ @@ -98,7 +88,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) try { // init scanner Class scannerClass = ReflectUtils.forName("org.springframework.context.annotation.ClassPathBeanDefinitionScanner"); - Object scanner = scannerClass.getConstructor(new Class[] {BeanDefinitionRegistry.class, boolean.class}).newInstance(new Object[] {(BeanDefinitionRegistry) beanFactory, true}); + Object scanner = scannerClass.getConstructor(new Class[]{BeanDefinitionRegistry.class, boolean.class}).newInstance((BeanDefinitionRegistry) beanFactory, true); // add filter Class filterClass = ReflectUtils.forName("org.springframework.core.type.filter.AnnotationTypeFilter"); Object filter = filterClass.getConstructor(Class.class).newInstance(Service.class); @@ -106,8 +96,8 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) addIncludeFilter.invoke(scanner, filter); // scan packages String[] packages = Constants.COMMA_SPLIT_PATTERN.split(annotationPackage); - Method scan = scannerClass.getMethod("scan", new Class[]{String[].class}); - scan.invoke(scanner, new Object[] {packages}); + Method scan = scannerClass.getMethod("scan", String[].class); + scan.invoke(scanner, new Object[]{packages}); } catch (Throwable e) { // spring 2.0 } @@ -133,11 +123,11 @@ public void destroy() throws Exception { public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (! isMatchPackage(bean)) { + if (!isMatchPackage(bean)) { return bean; } Class clazz = bean.getClass(); - if(isProxyBean(bean)){ + if (isProxyBean(bean)) { clazz = AopUtils.getTargetClass(bean); } Service service = clazz.getAnnotation(Service.class); @@ -157,34 +147,32 @@ public Object postProcessAfterInitialization(Object bean, String beanName) List registryConfigs = new ArrayList(); for (String registryId : service.registry()) { if (registryId != null && registryId.length() > 0) { - registryConfigs.add((RegistryConfig)applicationContext.getBean(registryId, RegistryConfig.class)); + registryConfigs.add(applicationContext.getBean(registryId, RegistryConfig.class)); } } serviceConfig.setRegistries(registryConfigs); } if (service.provider() != null && service.provider().length() > 0) { - serviceConfig.setProvider((ProviderConfig)applicationContext.getBean(service.provider(),ProviderConfig.class)); + serviceConfig.setProvider(applicationContext.getBean(service.provider(), ProviderConfig.class)); } if (service.monitor() != null && service.monitor().length() > 0) { - serviceConfig.setMonitor((MonitorConfig)applicationContext.getBean(service.monitor(), MonitorConfig.class)); + serviceConfig.setMonitor(applicationContext.getBean(service.monitor(), MonitorConfig.class)); } if (service.application() != null && service.application().length() > 0) { - serviceConfig.setApplication((ApplicationConfig)applicationContext.getBean(service.application(), ApplicationConfig.class)); + serviceConfig.setApplication(applicationContext.getBean(service.application(), ApplicationConfig.class)); } if (service.module() != null && service.module().length() > 0) { - serviceConfig.setModule((ModuleConfig)applicationContext.getBean(service.module(), ModuleConfig.class)); + serviceConfig.setModule(applicationContext.getBean(service.module(), ModuleConfig.class)); } if (service.provider() != null && service.provider().length() > 0) { - serviceConfig.setProvider((ProviderConfig)applicationContext.getBean(service.provider(), ProviderConfig.class)); - } else { - + serviceConfig.setProvider((ProviderConfig) applicationContext.getBean(service.provider(), ProviderConfig.class)); } if (service.protocol() != null && service.protocol().length > 0) { List protocolConfigs = new ArrayList(); // modified by lishen; fix dubbo's bug for (String protocolId : service.protocol()) { if (protocolId != null && protocolId.length() > 0) { - protocolConfigs.add((ProtocolConfig)applicationContext.getBean(protocolId, ProtocolConfig.class)); + protocolConfigs.add(applicationContext.getBean(protocolId, ProtocolConfig.class)); } } serviceConfig.setProtocols(protocolConfigs); @@ -192,7 +180,7 @@ public Object postProcessAfterInitialization(Object bean, String beanName) try { serviceConfig.afterPropertiesSet(); } catch (RuntimeException e) { - throw (RuntimeException) e; + throw e; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } @@ -203,14 +191,14 @@ public Object postProcessAfterInitialization(Object bean, String beanName) } return bean; } - + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (! isMatchPackage(bean)) { + if (!isMatchPackage(bean)) { return bean; } Class clazz = bean.getClass(); - if(isProxyBean(bean)){ + if (isProxyBean(bean)) { clazz = AopUtils.getTargetClass(bean); } Method[] methods = clazz.getMethods(); @@ -219,15 +207,15 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) if (name.length() > 3 && name.startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers()) - && ! Modifier.isStatic(method.getModifiers())) { + && !Modifier.isStatic(method.getModifiers())) { try { - Reference reference = method.getAnnotation(Reference.class); - if (reference != null) { - Object value = refer(reference, method.getParameterTypes()[0]); - if (value != null) { - method.invoke(bean, new Object[] { value }); - } - } + Reference reference = method.getAnnotation(Reference.class); + if (reference != null) { + Object value = refer(reference, method.getParameterTypes()[0]); + if (value != null) { + method.invoke(bean, value); + } + } } catch (Exception e) { // modified by lishen throw new BeanInitializationException("Failed to init remote service reference at method " + name + " in class " + bean.getClass().getName(), e); @@ -238,16 +226,16 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { try { - if (! field.isAccessible()) { + if (!field.isAccessible()) { field.setAccessible(true); } Reference reference = field.getAnnotation(Reference.class); - if (reference != null) { - Object value = refer(reference, field.getType()); - if (value != null) { - field.set(bean, value); - } - } + if (reference != null) { + Object value = refer(reference, field.getType()); + if (value != null) { + field.set(bean, value); + } + } } catch (Exception e) { // modified by lishen throw new BeanInitializationException("Failed to init remote service reference at filed " + field.getName() + " in class " + bean.getClass().getName(), e); @@ -259,9 +247,9 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) private Object refer(Reference reference, Class referenceClass) { //method.getParameterTypes()[0] String interfaceName; - if (! "".equals(reference.interfaceName())) { + if (!"".equals(reference.interfaceName())) { interfaceName = reference.interfaceName(); - } else if (! void.class.equals(reference.interfaceClass())) { + } else if (!void.class.equals(reference.interfaceClass())) { interfaceName = reference.interfaceClass().getName(); } else if (referenceClass.isInterface()) { interfaceName = referenceClass.getName(); @@ -283,30 +271,30 @@ private Object refer(Reference reference, Class referenceClass) { //method.ge List registryConfigs = new ArrayList(); for (String registryId : reference.registry()) { if (registryId != null && registryId.length() > 0) { - registryConfigs.add((RegistryConfig)applicationContext.getBean(registryId, RegistryConfig.class)); + registryConfigs.add(applicationContext.getBean(registryId, RegistryConfig.class)); } } referenceConfig.setRegistries(registryConfigs); } if (reference.consumer() != null && reference.consumer().length() > 0) { - referenceConfig.setConsumer((ConsumerConfig)applicationContext.getBean(reference.consumer(), ConsumerConfig.class)); + referenceConfig.setConsumer(applicationContext.getBean(reference.consumer(), ConsumerConfig.class)); } if (reference.monitor() != null && reference.monitor().length() > 0) { - referenceConfig.setMonitor((MonitorConfig)applicationContext.getBean(reference.monitor(), MonitorConfig.class)); + referenceConfig.setMonitor(applicationContext.getBean(reference.monitor(), MonitorConfig.class)); } if (reference.application() != null && reference.application().length() > 0) { - referenceConfig.setApplication((ApplicationConfig)applicationContext.getBean(reference.application(), ApplicationConfig.class)); + referenceConfig.setApplication(applicationContext.getBean(reference.application(), ApplicationConfig.class)); } if (reference.module() != null && reference.module().length() > 0) { - referenceConfig.setModule((ModuleConfig)applicationContext.getBean(reference.module(), ModuleConfig.class)); + referenceConfig.setModule(applicationContext.getBean(reference.module(), ModuleConfig.class)); } if (reference.consumer() != null && reference.consumer().length() > 0) { - referenceConfig.setConsumer((ConsumerConfig)applicationContext.getBean(reference.consumer(), ConsumerConfig.class)); + referenceConfig.setConsumer(applicationContext.getBean(reference.consumer(), ConsumerConfig.class)); } try { referenceConfig.afterPropertiesSet(); } catch (RuntimeException e) { - throw (RuntimeException) e; + throw e; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } @@ -322,7 +310,7 @@ private boolean isMatchPackage(Object bean) { return true; } Class clazz = bean.getClass(); - if(isProxyBean(bean)){ + if (isProxyBean(bean)) { clazz = AopUtils.getTargetClass(bean); } String beanClassName = clazz.getName(); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java index d149448739d..7f58d92cdf9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java @@ -81,7 +81,7 @@ public void afterPropertiesSet() throws Exception { if (consumerConfigMap != null && consumerConfigMap.size() > 0) { ConsumerConfig consumerConfig = null; for (ConsumerConfig config : consumerConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (consumerConfig != null) { throw new IllegalStateException("Duplicate consumer configs: " + consumerConfig + " and " + config); } @@ -99,7 +99,7 @@ public void afterPropertiesSet() throws Exception { if (applicationConfigMap != null && applicationConfigMap.size() > 0) { ApplicationConfig applicationConfig = null; for (ApplicationConfig config : applicationConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (applicationConfig != null) { throw new IllegalStateException("Duplicate application configs: " + applicationConfig + " and " + config); } @@ -117,7 +117,7 @@ public void afterPropertiesSet() throws Exception { if (moduleConfigMap != null && moduleConfigMap.size() > 0) { ModuleConfig moduleConfig = null; for (ModuleConfig config : moduleConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (moduleConfig != null) { throw new IllegalStateException("Duplicate module configs: " + moduleConfig + " and " + config); } @@ -136,7 +136,7 @@ public void afterPropertiesSet() throws Exception { if (registryConfigMap != null && registryConfigMap.size() > 0) { List registryConfigs = new ArrayList(); for (RegistryConfig config : registryConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { registryConfigs.add(config); } } @@ -152,7 +152,7 @@ public void afterPropertiesSet() throws Exception { if (monitorConfigMap != null && monitorConfigMap.size() > 0) { MonitorConfig monitorConfig = null; for (MonitorConfig config : monitorConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (monitorConfig != null) { throw new IllegalStateException("Duplicate monitor configs: " + monitorConfig + " and " + config); } @@ -168,7 +168,7 @@ public void afterPropertiesSet() throws Exception { if (b == null && getConsumer() != null) { b = getConsumer().isInit(); } - if (b != null && b.booleanValue()) { + if (b != null && b) { getObject(); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index cc9c2a0776a..b1d6effde79 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -78,19 +78,19 @@ public void setApplicationContext(ApplicationContext applicationContext) { if (applicationContext != null) { SPRING_CONTEXT = applicationContext; try { - Method method = applicationContext.getClass().getMethod("addApplicationListener", new Class[]{ApplicationListener.class}); // 兼容Spring2.0.1 - method.invoke(applicationContext, new Object[] {this}); + Method method = applicationContext.getClass().getMethod("addApplicationListener", ApplicationListener.class); // 兼容Spring2.0.1 + method.invoke(applicationContext, this); supportedApplicationListener = true; } catch (Throwable t) { if (applicationContext instanceof AbstractApplicationContext) { try { - Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", new Class[]{ApplicationListener.class}); // 兼容Spring2.0.1 + Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", ApplicationListener.class); // 兼容Spring2.0.1 if (! method.isAccessible()) { method.setAccessible(true); } - method.invoke(applicationContext, new Object[] {this}); + method.invoke(applicationContext, this); supportedApplicationListener = true; - } catch (Throwable t2) { + } catch (Throwable ignored) { } } } @@ -118,7 +118,7 @@ private boolean isDelay() { if (delay == null && provider != null) { delay = provider.getDelay(); } - return supportedApplicationListener && (delay == null || delay.intValue() == -1); + return supportedApplicationListener && (delay == null || delay == -1); } @SuppressWarnings({ "unchecked", "deprecation" }) @@ -131,7 +131,7 @@ public void afterPropertiesSet() throws Exception { && providerConfigMap.size() > 1) { // 兼容旧版本 List providerConfigs = new ArrayList(); for (ProviderConfig config : providerConfigMap.values()) { - if (config.isDefault() != null && config.isDefault().booleanValue()) { + if (config.isDefault() != null && config.isDefault()) { providerConfigs.add(config); } } @@ -141,7 +141,7 @@ public void afterPropertiesSet() throws Exception { } else { ProviderConfig providerConfig = null; for (ProviderConfig config : providerConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (providerConfig != null) { throw new IllegalStateException("Duplicate provider configs: " + providerConfig + " and " + config); } @@ -160,7 +160,7 @@ public void afterPropertiesSet() throws Exception { if (applicationConfigMap != null && applicationConfigMap.size() > 0) { ApplicationConfig applicationConfig = null; for (ApplicationConfig config : applicationConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (applicationConfig != null) { throw new IllegalStateException("Duplicate application configs: " + applicationConfig + " and " + config); } @@ -178,7 +178,7 @@ public void afterPropertiesSet() throws Exception { if (moduleConfigMap != null && moduleConfigMap.size() > 0) { ModuleConfig moduleConfig = null; for (ModuleConfig config : moduleConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (moduleConfig != null) { throw new IllegalStateException("Duplicate module configs: " + moduleConfig + " and " + config); } @@ -197,7 +197,7 @@ public void afterPropertiesSet() throws Exception { if (registryConfigMap != null && registryConfigMap.size() > 0) { List registryConfigs = new ArrayList(); for (RegistryConfig config : registryConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { registryConfigs.add(config); } } @@ -213,7 +213,7 @@ public void afterPropertiesSet() throws Exception { if (monitorConfigMap != null && monitorConfigMap.size() > 0) { MonitorConfig monitorConfig = null; for (MonitorConfig config : monitorConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { if (monitorConfig != null) { throw new IllegalStateException("Duplicate monitor configs: " + monitorConfig + " and " + config); } @@ -231,7 +231,7 @@ public void afterPropertiesSet() throws Exception { if (protocolConfigMap != null && protocolConfigMap.size() > 0) { List protocolConfigs = new ArrayList(); for (ProtocolConfig config : protocolConfigMap.values()) { - if (config.isDefault() == null || config.isDefault().booleanValue()) { + if (config.isDefault() == null || config.isDefault()) { protocolConfigs.add(config); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java index 33c0072f287..7b7a005f689 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java @@ -15,41 +15,41 @@ */ package com.alibaba.dubbo.remoting.exchange; -import java.util.concurrent.atomic.AtomicLong; - import com.alibaba.dubbo.common.utils.StringUtils; +import java.util.concurrent.atomic.AtomicLong; + /** * Request. - * + * * @author qian.lei * @author william.liangf */ public class Request { - + public static final String HEARTBEAT_EVENT = null; - + public static final String READONLY_EVENT = "R"; - + private static final AtomicLong INVOKE_ID = new AtomicLong(0); - private final long mId; + private final long mId; + + private String mVersion; - private String mVersion; + private boolean mTwoWay = true; - private boolean mTwoWay = true; - private boolean mEvent = false; - private boolean mBroken = false; + private boolean mBroken = false; - private Object mData; + private Object mData; public Request() { mId = newId(); } - public Request(long id){ + public Request(long id) { mId = id; } @@ -116,7 +116,7 @@ private static long newId() { @Override public String toString() { return "Request [id=" + mId + ", version=" + mVersion + ", twoway=" + mTwoWay + ", event=" + mEvent - + ", broken=" + mBroken + ", data=" + (mData == this ? "this" : safeToString(mData)) + "]"; + + ", broken=" + mBroken + ", data=" + (mData == this ? "this" : safeToString(mData)) + "]"; } private static String safeToString(Object data) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index e2db42b06f5..e95ecb84fde 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.remoting.exchange.codec; -import java.io.IOException; -import java.io.InputStream; - import com.alibaba.dubbo.common.io.Bytes; import com.alibaba.dubbo.common.io.StreamUtils; import com.alibaba.dubbo.common.logger.Logger; @@ -38,34 +35,37 @@ import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; import com.alibaba.dubbo.remoting.transport.CodecSupport; +import java.io.IOException; +import java.io.InputStream; + /** * ExchangeCodec. - * + * * @author qianlei * @author william.liangf */ public class ExchangeCodec extends TelnetCodec { - private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class); + private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class); // header length. - protected static final int HEADER_LENGTH = 16; + protected static final int HEADER_LENGTH = 16; // magic header. - protected static final short MAGIC = (short) 0xdabb; - - protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; - - protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; + protected static final short MAGIC = (short) 0xdabb; + + protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; + + protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; // message flag. - protected static final byte FLAG_REQUEST = (byte) 0x80; + protected static final byte FLAG_REQUEST = (byte) 0x80; - protected static final byte FLAG_TWOWAY = (byte) 0x40; + protected static final byte FLAG_TWOWAY = (byte) 0x40; - protected static final byte FLAG_EVENT = (byte) 0x20; + protected static final byte FLAG_EVENT = (byte) 0x20; - protected static final int SERIALIZATION_MASK = 0x1f; + protected static final int SERIALIZATION_MASK = 0x1f; public Short getMagicCode() { return MAGIC; @@ -79,9 +79,6 @@ public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOE } else { super.encode(channel, buffer, msg); } - - // TODO modified by lishen -// System.out.println(">>>>>>>>>>>>>>>>>>>>>> the resulting byte size of encoding is " + buffer.readableBytes()); if (logger.isTraceEnabled()) { logger.trace("the resulting byte size of encoding is " + buffer.readableBytes()); } @@ -94,17 +91,17 @@ public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { buffer.readBytes(header); return decode(channel, buffer, readable, header); } - + protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. - if (readable > 0 && header[0] != MAGIC_HIGH + if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); buffer.readBytes(header, length, readable - length); } - for (int i = 1; i < header.length - 1; i ++) { + for (int i = 1; i < header.length - 1; i++) { if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { buffer.readerIndex(buffer.readerIndex() - header.length + i); header = Bytes.copyOf(header, i); @@ -123,7 +120,7 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt checkPayload(channel, len); int tt = len + HEADER_LENGTH; - if( readable < tt ) { + if (readable < tt) { return DecodeResult.NEED_MORE_INPUT; } @@ -292,8 +289,7 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re } else { encodeResponseData(channel, out, res.getResult()); } - } - else out.writeUTF(res.getErrorMessage()); + } else out.writeUTF(res.getErrorMessage()); out.flushBuffer(); } finally { // modified by lishen @@ -314,22 +310,22 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } catch (Throwable t) { // 发送失败信息给Consumer,否则Consumer只能等超时了 - if (! res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { + if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { try { // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理? logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); - + Response r = new Response(res.getId(), res.getVersion()); r.setStatus(Response.BAD_RESPONSE); r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); channel.send(r); - + return; } catch (RemotingException e) { logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); } } - + // 重新抛出收到的异常 if (t instanceof IOException) { throw (IOException) t; @@ -337,12 +333,12 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; - } else { + } else { throw new RuntimeException(t.getMessage(), t); } } } - + @Override protected Object decodeData(ObjectInput in) throws IOException { return decodeRequestData(in); @@ -372,16 +368,16 @@ protected Object decodeResponseData(ObjectInput in) throws IOException { throw new IOException(StringUtils.toString("Read object failed.", e)); } } - + @Override protected void encodeData(ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } - + private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } - + @Deprecated protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); @@ -394,12 +390,12 @@ protected void encodeRequestData(ObjectOutput out, Object data) throws IOExcepti protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } - + @Override protected Object decodeData(Channel channel, ObjectInput in) throws IOException { - return decodeRequestData(channel ,in); + return decodeRequestData(channel, in); } - + protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException { try { return in.readObject(); @@ -428,7 +424,7 @@ protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOEx protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { return decodeResponseData(channel, in); } - + @Override protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data); @@ -437,6 +433,7 @@ protected void encodeData(Channel channel, ObjectOutput out, Object data) throws private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeEventData(out, data); } + @Deprecated protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeHeartbeatData(out, data); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 08a32fd6ec7..5cd03fd126d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -15,15 +15,6 @@ */ package com.alibaba.dubbo.remoting.exchange.support.header; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -39,28 +30,37 @@ import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + /** * ExchangeServerImpl - * + * * @author william.liangf */ public class HeaderExchangeServer implements ExchangeServer { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1, - new NamedThreadFactory( - "dubbo-remoting-server-heartbeat", - true)); + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1, + new NamedThreadFactory( + "dubbo-remoting-server-heartbeat", + true)); // 心跳定时器 - private ScheduledFuture heatbeatTimer; + private ScheduledFuture heartbeatTimer; // 心跳超时,毫秒。缺省0,不会执行心跳。 - private int heartbeat; + private int heartbeat; + + private int heartbeatTimeout; - private int heartbeatTimeout; - private final Server server; private volatile boolean closed = false; @@ -77,7 +77,7 @@ public HeaderExchangeServer(Server server) { } startHeatbeatTimer(); } - + public Server getServer() { return server; } @@ -105,10 +105,10 @@ public void close(final int timeout) { if (timeout > 0) { final long max = (long) timeout; final long start = System.currentTimeMillis(); - if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, false)){ + if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, false)) { sendChannelReadOnlyEvent(); } - while (HeaderExchangeServer.this.isRunning() + while (HeaderExchangeServer.this.isRunning() && System.currentTimeMillis() - start < max) { try { Thread.sleep(10); @@ -120,23 +120,24 @@ public void close(final int timeout) { doClose(); server.close(timeout); } - - private void sendChannelReadOnlyEvent(){ + + private void sendChannelReadOnlyEvent() { Request request = new Request(); request.setEvent(Request.READONLY_EVENT); request.setTwoWay(false); request.setVersion(Version.getVersion()); - + Collection channels = getChannels(); for (Channel channel : channels) { try { - if (channel.isConnected())channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); + if (channel.isConnected()) + channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } catch (RemotingException e) { logger.warn("send connot write messge error.", e); } } } - + private void doClose() { if (closed) { return; @@ -151,7 +152,7 @@ private void doClose() { } public Collection getExchangeChannels() { - Collection exchangeChannels = new ArrayList(); + Collection exchangeChannels = new ArrayList(); Collection channels = server.getChannels(); if (channels != null && channels.size() > 0) { for (Channel channel : channels) { @@ -166,9 +167,9 @@ public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { return HeaderExchangeChannel.getOrAddChannel(channel); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public Collection getChannels() { - return (Collection)getExchangeChannels(); + return (Collection) getExchangeChannels(); } public Channel getChannel(InetSocketAddress remoteAddress) { @@ -211,9 +212,9 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } } - + @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters){ + public void reset(com.alibaba.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @@ -234,27 +235,27 @@ public void send(Object message, boolean sent) throws RemotingException { private void startHeatbeatTimer() { stopHeartbeatTimer(); if (heartbeat > 0) { - heatbeatTimer = scheduled.scheduleWithFixedDelay( - new HeartBeatTask( new HeartBeatTask.ChannelProvider() { + heartbeatTimer = scheduled.scheduleWithFixedDelay( + new HeartBeatTask(new HeartBeatTask.ChannelProvider() { public Collection getChannels() { return Collections.unmodifiableCollection( - HeaderExchangeServer.this.getChannels() ); + HeaderExchangeServer.this.getChannels()); } }, heartbeat, heartbeatTimeout), - heartbeat, heartbeat,TimeUnit.MILLISECONDS); + heartbeat, heartbeat, TimeUnit.MILLISECONDS); } } private void stopHeartbeatTimer() { try { - ScheduledFuture timer = heatbeatTimer; - if (timer != null && ! timer.isCancelled()) { + ScheduledFuture timer = heartbeatTimer; + if (timer != null && !timer.isCancelled()) { timer.cancel(true); } } catch (Throwable t) { logger.warn(t.getMessage(), t); } finally { - heatbeatTimer =null; + heartbeatTimer = null; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java index 3d1445e8c35..909d59fd5e5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java @@ -16,28 +16,28 @@ package com.alibaba.dubbo.remoting.exchange.support.header; -import java.util.Collection; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Client; import com.alibaba.dubbo.remoting.exchange.Request; +import java.util.Collection; + /** * @author kimi */ final class HeartBeatTask implements Runnable { - private static final Logger logger = LoggerFactory.getLogger( HeartBeatTask.class ); + private static final Logger logger = LoggerFactory.getLogger(HeartBeatTask.class); private ChannelProvider channelProvider; - private int heartbeat; + private int heartbeat; - private int heartbeatTimeout; + private int heartbeatTimeout; - HeartBeatTask( ChannelProvider provider, int heartbeat, int heartbeatTimeout ) { + HeartBeatTask(ChannelProvider provider, int heartbeat, int heartbeatTimeout) { this.channelProvider = provider; this.heartbeat = heartbeat; this.heartbeatTimeout = heartbeatTimeout; @@ -46,46 +46,46 @@ final class HeartBeatTask implements Runnable { public void run() { try { long now = System.currentTimeMillis(); - for ( Channel channel : channelProvider.getChannels() ) { + for (Channel channel : channelProvider.getChannels()) { if (channel.isClosed()) { continue; } try { - Long lastRead = ( Long ) channel.getAttribute( - HeaderExchangeHandler.KEY_READ_TIMESTAMP ); - Long lastWrite = ( Long ) channel.getAttribute( - HeaderExchangeHandler.KEY_WRITE_TIMESTAMP ); - if ( ( lastRead != null && now - lastRead > heartbeat ) - || ( lastWrite != null && now - lastWrite > heartbeat ) ) { + Long lastRead = (Long) channel.getAttribute( + HeaderExchangeHandler.KEY_READ_TIMESTAMP); + Long lastWrite = (Long) channel.getAttribute( + HeaderExchangeHandler.KEY_WRITE_TIMESTAMP); + if ((lastRead != null && now - lastRead > heartbeat) + || (lastWrite != null && now - lastWrite > heartbeat)) { Request req = new Request(); - req.setVersion( "2.0.0" ); - req.setTwoWay( true ); - req.setEvent( Request.HEARTBEAT_EVENT ); - channel.send( req ); - if ( logger.isDebugEnabled() ) { - logger.debug( "Send heartbeat to remote channel " + channel.getRemoteAddress() - + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms" ); + req.setVersion("2.0.0"); + req.setTwoWay(true); + req.setEvent(Request.HEARTBEAT_EVENT); + channel.send(req); + if (logger.isDebugEnabled()) { + logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() + + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms"); } } - if ( lastRead != null && now - lastRead > heartbeatTimeout ) { - logger.warn( "Close channel " + channel - + ", because heartbeat read idle time out: " + heartbeatTimeout + "ms" ); + if (lastRead != null && now - lastRead > heartbeatTimeout) { + logger.warn("Close channel " + channel + + ", because heartbeat read idle time out: " + heartbeatTimeout + "ms"); if (channel instanceof Client) { - try { - ((Client)channel).reconnect(); - }catch (Exception e) { - //do nothing - } + try { + ((Client) channel).reconnect(); + } catch (Exception e) { + //do nothing + } } else { - channel.close(); + channel.close(); } } - } catch ( Throwable t ) { - logger.warn( "Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t ); + } catch (Throwable t) { + logger.warn("Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); } } - } catch ( Throwable t ) { - logger.warn( "Unhandled exception when heartbeat, cause: " + t.getMessage(), t ); + } catch (Throwable t) { + logger.warn("Unhandled exception when heartbeat, cause: " + t.getMessage(), t); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java index f4d9ddb0c76..7b1d0ee9606 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java @@ -15,17 +15,6 @@ */ package com.alibaba.dubbo.remoting.transport; -import java.net.InetSocketAddress; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -42,61 +31,69 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; +import java.net.InetSocketAddress; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + /** * AbstractClient - * + * * @author qian.lei * @author chao.liuc */ public abstract class AbstractClient extends AbstractEndpoint implements Client { - + private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class); - - protected static final String CLIENT_THREAD_POOL_NAME ="DubboClientHandler"; - + + protected static final String CLIENT_THREAD_POOL_NAME = "DubboClientHandler"; + private static final AtomicInteger CLIENT_THREAD_POOL_ID = new AtomicInteger(); - private final Lock connectLock = new ReentrantLock(); - - private static final ScheduledThreadPoolExecutor reconnectExecutorService = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("DubboClientReconnectTimer", true)); - - private volatile ScheduledFuture reconnectExecutorFuture = null; - + private final Lock connectLock = new ReentrantLock(); + + private static final ScheduledThreadPoolExecutor reconnectExecutorService = new ScheduledThreadPoolExecutor(2, + new NamedThreadFactory("DubboClientReconnectTimer", true)); + + private volatile ScheduledFuture reconnectExecutorFuture = null; + protected volatile ExecutorService executor; - - private final boolean send_reconnect ; - + + private final boolean send_reconnect; + private final AtomicInteger reconnect_count = new AtomicInteger(0); - + //重连的error日志是否已经被调用过. - private final AtomicBoolean reconnect_error_log_flag = new AtomicBoolean(false) ; - + private final AtomicBoolean reconnect_error_log_flag = new AtomicBoolean(false); + //重连warning的间隔.(waring多少次之后,warning一次) //for test - private final int reconnect_warning_period ; - + private final int reconnect_warning_period; + //the last successed connected time private long lastConnectedTime = System.currentTimeMillis(); - - private final long shutdown_timeout ; - - + + private final long shutdown_timeout; + + public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); - + send_reconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false); - + shutdown_timeout = url.getParameter(Constants.SHUTDOWN_TIMEOUT_KEY, Constants.DEFAULT_SHUTDOWN_TIMEOUT); - + //默认重连间隔2s,1800表示1小时warning一次. reconnect_warning_period = url.getParameter("reconnect.waring.period", 1800); - + try { doOpen(); } catch (Throwable t) { close(); - throw new RemotingException(url.toInetSocketAddress(), null, - "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); + throw new RemotingException(url.toInetSocketAddress(), null, + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); } try { // connect. @@ -110,53 +107,53 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException throw t; } else { logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); + + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); } - } catch (Throwable t){ + } catch (Throwable t) { close(); - throw new RemotingException(url.toInetSocketAddress(), null, - "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); + throw new RemotingException(url.toInetSocketAddress(), null, + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); } - + executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class) - .getDefaultExtension().get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); + .getDefaultExtension().get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); ExtensionLoader.getExtensionLoader(DataStore.class) - .getDefaultExtension().remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); + .getDefaultExtension().remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort())); } - - protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler 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); } - + /** * init reconnect thread */ - private synchronized void initConnectStatusCheckCommand(){ + private synchronized void initConnectStatusCheckCommand() { //reconnect=false to close reconnect int reconnect = getReconnectParam(getUrl()); - if(reconnect > 0 && (reconnectExecutorFuture == null || reconnectExecutorFuture.isCancelled())){ - Runnable connectStatusCheckCommand = new Runnable() { + if (reconnect > 0 && (reconnectExecutorFuture == null || reconnectExecutorFuture.isCancelled())) { + Runnable connectStatusCheckCommand = new Runnable() { public void run() { try { - if (! isConnected()) { + if (!isConnected()) { connect(); } else { lastConnectedTime = System.currentTimeMillis(); } - } catch (Throwable t) { - String errorMsg = "client reconnect to "+getUrl().getAddress()+" find error . url: "+ getUrl(); + } catch (Throwable t) { + String errorMsg = "client reconnect to " + getUrl().getAddress() + " find error . url: " + getUrl(); // wait registry sync provider list - if (System.currentTimeMillis() - lastConnectedTime > shutdown_timeout){ - if (!reconnect_error_log_flag.get()){ + if (System.currentTimeMillis() - lastConnectedTime > shutdown_timeout) { + if (!reconnect_error_log_flag.get()) { reconnect_error_log_flag.set(true); logger.error(errorMsg, t); - return ; + return; } } - if ( reconnect_count.getAndIncrement() % reconnect_warning_period == 0){ + if (reconnect_count.getAndIncrement() % reconnect_warning_period == 0) { logger.warn(errorMsg, t); } } @@ -165,34 +162,34 @@ public void run() { reconnectExecutorFuture = reconnectExecutorService.scheduleWithFixedDelay(connectStatusCheckCommand, reconnect, reconnect, TimeUnit.MILLISECONDS); } } - + /** * @param url * @return 0-false */ - private static int getReconnectParam(URL url){ - int reconnect ; + private static int getReconnectParam(URL url) { + int reconnect; String param = url.getParameter(Constants.RECONNECT_KEY); - if (param == null || param.length()==0 || "true".equalsIgnoreCase(param)){ + if (param == null || param.length() == 0 || "true".equalsIgnoreCase(param)) { reconnect = Constants.DEFAULT_RECONNECT_PERIOD; - }else if ("false".equalsIgnoreCase(param)){ + } else if ("false".equalsIgnoreCase(param)) { reconnect = 0; } else { - try{ + try { reconnect = Integer.parseInt(param); - }catch (Exception e) { - throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:"+param); + } catch (Exception e) { + throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param); } - if(reconnect < 0){ - throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:"+param); + if (reconnect < 0) { + throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param); } } return reconnect; } - - private synchronized void destroyConnectStatusCheckCommand(){ + + private synchronized void destroyConnectStatusCheckCommand() { try { - if (reconnectExecutorFuture != null && ! reconnectExecutorFuture.isDone()){ + if (reconnectExecutorFuture != null && !reconnectExecutorFuture.isDone()) { reconnectExecutorFuture.cancel(true); reconnectExecutorService.purge(); } @@ -200,11 +197,11 @@ private synchronized void destroyConnectStatusCheckCommand(){ logger.warn(e.getMessage(), e); } } - + protected ExecutorService createExecutor() { return Executors.newCachedThreadPool(new NamedThreadFactory(CLIENT_THREAD_POOL_NAME + CLIENT_THREAD_POOL_ID.incrementAndGet() + "-" + getUrl().getAddress(), true)); } - + public InetSocketAddress getConnectAddress() { return new InetSocketAddress(NetUtils.filterLocalHost(getUrl().getHost()), getUrl().getPort()); } @@ -257,19 +254,19 @@ public boolean hasAttribute(String key) { return false; return channel.hasAttribute(key); } - + public void send(Object message, boolean sent) throws RemotingException { - if (send_reconnect && !isConnected()){ + if (send_reconnect && !isConnected()) { connect(); } Channel channel = getChannel(); //TODO getChannel返回的状态是否包含null需要改进 - if (channel == null || ! channel.isConnected()) { - throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl()); + if (channel == null || !channel.isConnected()) { + throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl()); } channel.send(message, sent); } - + protected void connect() throws RemotingException { connectLock.lock(); try { @@ -278,16 +275,16 @@ protected void connect() throws RemotingException { } initConnectStatusCheckCommand(); doConnect(); - if (! isConnected()) { + if (!isConnected()) { throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", cause: Connect wait timeout: " + getTimeout() + "ms."); + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", cause: Connect wait timeout: " + getTimeout() + "ms."); } else { - if (logger.isInfoEnabled()){ - logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", channel is " + this.getChannel()); - } + if (logger.isInfoEnabled()) { + logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", channel is " + this.getChannel()); + } } reconnect_count.set(0); reconnect_error_log_flag.set(false); @@ -295,8 +292,8 @@ protected void connect() throws RemotingException { throw e; } catch (Throwable e) { throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", cause: " + e.getMessage(), e); + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", cause: " + e.getMessage(), e); } finally { connectLock.unlock(); } @@ -323,18 +320,18 @@ public void disconnect() { connectLock.unlock(); } } - + public void reconnect() throws RemotingException { disconnect(); connect(); } public void close() { - try { - if (executor != null) { - ExecutorUtil.shutdownNow(executor, 100); - } - } catch (Throwable e) { + try { + if (executor != null) { + ExecutorUtil.shutdownNow(executor, 100); + } + } catch (Throwable e) { logger.warn(e.getMessage(), e); } try { @@ -343,7 +340,7 @@ public void close() { logger.warn(e.getMessage(), e); } try { - disconnect(); + disconnect(); } catch (Throwable e) { logger.warn(e.getMessage(), e); } @@ -355,10 +352,10 @@ public void close() { } public void close(int timeout) { - ExecutorUtil.gracefulShutdown(executor ,timeout); + ExecutorUtil.gracefulShutdown(executor, timeout); close(); } - + @Override public String toString() { return getClass().getName() + " [" + getLocalAddress() + " -> " + getRemoteAddress() + "]"; @@ -366,35 +363,35 @@ public String toString() { /** * Open client. - * + * * @throws Throwable */ protected abstract void doOpen() throws Throwable; /** * Close client. - * + * * @throws Throwable */ protected abstract void doClose() throws Throwable; /** * Connect to server. - * + * * @throws Throwable */ protected abstract void doConnect() throws Throwable; - + /** * disConnect to server. - * + * * @throws Throwable */ protected abstract void doDisConnect() throws Throwable; /** * Get the connected channel. - * + * * @return channel */ protected abstract Channel getChannel(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java index 9fc02918eac..3aacabe0588 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java @@ -21,26 +21,26 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.transport.codec.CodecAdapter; /** * AbstractEndpoint - * + * * @author william.liangf */ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable { - + private static final Logger logger = LoggerFactory.getLogger(AbstractEndpoint.class); - private Codec2 codec; + private Codec2 codec; - private int timeout; + private int timeout; + + private int connectTimeout; - private int connectTimeout; - public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); this.codec = getChannelCodec(url); @@ -51,7 +51,7 @@ public AbstractEndpoint(URL url, ChannelHandler handler) { public void reset(URL url) { if (isClosed()) { throw new IllegalStateException("Failed to reset parameters " - + url + ", cause: Channel closed. channel: " + getLocalAddress()); + + url + ", cause: Channel closed. channel: " + getLocalAddress()); } try { if (url.hasParameter(Constants.HEARTBEAT_KEY)) { @@ -81,9 +81,9 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } } - + @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters){ + public void reset(com.alibaba.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @@ -105,7 +105,7 @@ protected static Codec2 getChannelCodec(URL url) { return ExtensionLoader.getExtensionLoader(Codec2.class).getExtension(codecName); } else { return new CodecAdapter(ExtensionLoader.getExtensionLoader(Codec.class) - .getExtension(codecName)); + .getExtension(codecName)); } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/DispatcherServlet.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/DispatcherServlet.java index ae3c7210bfe..5b82e20ca20 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/DispatcherServlet.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/DispatcherServlet.java @@ -13,56 +13,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.http.servlet; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +package com.alibaba.dubbo.remoting.http.servlet; + +import com.alibaba.dubbo.remoting.http.HttpHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -import com.alibaba.dubbo.remoting.http.HttpHandler; - -/** - * Service dispatcher Servlet. - * - * @author qian.lei - */ -public class DispatcherServlet extends HttpServlet { - - private static final long serialVersionUID = 5766349180380479888L; - - private static DispatcherServlet INSTANCE; - - private static final Map handlers = new ConcurrentHashMap(); - - public static void addHttpHandler(int port, HttpHandler processor) { - handlers.put(port, processor); - } - - public static void removeHttpHandler(int port) { - handlers.remove(port); +/** + * Service dispatcher Servlet. + * + * @author qian.lei + */ +public class DispatcherServlet extends HttpServlet { + + private static final long serialVersionUID = 5766349180380479888L; + + private static DispatcherServlet INSTANCE; + + private static final Map handlers = new ConcurrentHashMap(); + + public static void addHttpHandler(int port, HttpHandler processor) { + handlers.put(port, processor); + } + + public static void removeHttpHandler(int port) { + handlers.remove(port); } - + public static DispatcherServlet getInstance() { - return INSTANCE; + return INSTANCE; } - + public DispatcherServlet() { - DispatcherServlet.INSTANCE = this; - } - - protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - HttpHandler handler = handlers.get(request.getLocalPort()); - if( handler == null ) {// service not found. - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); - } else { - handler.handle(request, response); - } - } - + DispatcherServlet.INSTANCE = this; + } + + protected void service(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpHandler handler = handlers.get(request.getLocalPort()); + if (handler == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); + } else { + handler.handle(request, response); + } + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java index 686d562ae68..ac56f74d6b3 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -53,8 +53,6 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { tomcat.setPort(url.getPort()); tomcat.getConnector().setProperty( "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); -// tomcat.getConnector().setProperty( -// "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); tomcat.getConnector().setProperty( "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1))); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java index 8f7a92d1deb..bb67ca1c606 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java @@ -15,20 +15,6 @@ */ package com.alibaba.dubbo.remoting.transport.netty; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -42,24 +28,37 @@ import com.alibaba.dubbo.remoting.Server; import com.alibaba.dubbo.remoting.transport.AbstractServer; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; + +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * NettyServer - * + * * @author qian.lei * @author chao.liuc */ public class NettyServer extends AbstractServer implements Server { - + private static final Logger logger = LoggerFactory.getLogger(NettyServer.class); - private Map channels; // + private Map channels; // - private ServerBootstrap bootstrap; + private ServerBootstrap bootstrap; private org.jboss.netty.channel.Channel channel; - public NettyServer(URL url, ChannelHandler handler) throws RemotingException{ + public NettyServer(URL url, ChannelHandler handler) throws RemotingException { super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } @@ -70,7 +69,7 @@ protected void doOpen() throws Throwable { ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true)); ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); - + final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); channels = nettyHandler.getChannels(); // https://issues.jboss.org/browse/NETTY-365 @@ -78,7 +77,7 @@ protected void doOpen() throws Throwable { // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { - NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this); + NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); ChannelPipeline pipeline = Channels.pipeline(); /*int idleTimeout = getIdleTimeout(); if (idleTimeout > 10000) { @@ -119,7 +118,7 @@ protected void doClose() throws Throwable { logger.warn(e.getMessage(), e); } try { - if (bootstrap != null) { + if (bootstrap != null) { // release external resource. bootstrap.releaseExternalResources(); } @@ -134,7 +133,7 @@ protected void doClose() throws Throwable { logger.warn(e.getMessage(), e); } } - + public Collection getChannels() { Collection chs = new HashSet(); for (Channel channel : this.channels.values()) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java index 92c5ce4de7d..d1d83dfbc66 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java @@ -15,32 +15,32 @@ */ package com.alibaba.dubbo.rpc; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; + import java.io.Serializable; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; - /** * RPC Invocation. - * - * @serial Don't change the class name and properties. + * * @author qian.lei + * @serial Don't change the class name and properties. */ public class RpcInvocation implements Invocation, Serializable { private static final long serialVersionUID = -4355285085441097045L; - private String methodName; + private String methodName; - private Class[] parameterTypes; + private Class[] parameterTypes; - private Object[] arguments; + private Object[] arguments; - private Map attachments; + private Map attachments; private transient Invoker invoker; @@ -48,7 +48,7 @@ public RpcInvocation() { } public RpcInvocation(Invocation invocation, Invoker invoker) { - this(invocation.getMethodName(), invocation.getParameterTypes(), + this(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments(), new HashMap(invocation.getAttachments()), invocation.getInvoker()); if (invoker != null) { @@ -76,7 +76,7 @@ public RpcInvocation(Invocation invocation, Invoker invoker) { } public RpcInvocation(Invocation invocation) { - this(invocation.getMethodName(), invocation.getParameterTypes(), + this(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments(), invocation.getAttachments(), invocation.getInvoker()); } @@ -103,7 +103,7 @@ public RpcInvocation(String methodName, Class[] parameterTypes, Object[] argu this.attachments = attachments == null ? new HashMap() : attachments; this.invoker = invoker; } - + public Invoker getInvoker() { return invoker; } @@ -143,7 +143,7 @@ public void setArguments(Object[] arguments) { public void setAttachments(Map attachments) { this.attachments = attachments == null ? new HashMap() : attachments; } - + public void setAttachment(String key, String value) { if (attachments == null) { attachments = new HashMap(); @@ -155,28 +155,28 @@ public void setAttachmentIfAbsent(String key, String value) { if (attachments == null) { attachments = new HashMap(); } - if (! attachments.containsKey(key)) { - attachments.put(key, value); + if (!attachments.containsKey(key)) { + attachments.put(key, value); } } public void addAttachments(Map attachments) { - if (attachments == null) { - return; - } - if (this.attachments == null) { - this.attachments = new HashMap(); + if (attachments == null) { + return; + } + if (this.attachments == null) { + this.attachments = new HashMap(); } - this.attachments.putAll(attachments); + this.attachments.putAll(attachments); } public void addAttachmentsIfAbsent(Map attachments) { - if (attachments == null) { - return; - } - for (Map.Entry entry : attachments.entrySet()) { - setAttachmentIfAbsent(entry.getKey(), entry.getValue()); - } + if (attachments == null) { + return; + } + for (Map.Entry entry : attachments.entrySet()) { + setAttachmentIfAbsent(entry.getKey(), entry.getValue()); + } } public String getAttachment(String key) { @@ -185,7 +185,7 @@ public String getAttachment(String key) { } return attachments.get(key); } - + public String getAttachment(String key, String defaultValue) { if (attachments == null) { return defaultValue; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java index 64f36a5c299..706fcd1efd2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java @@ -21,28 +21,28 @@ /** * RPC Result. - * - * @serial Don't change the class name and properties. + * * @author qianlei + * @serial Don't change the class name and properties. */ public class RpcResult implements Result, Serializable { - private static final long serialVersionUID = -6925924956850004727L; + private static final long serialVersionUID = -6925924956850004727L; - private Object result; + private Object result; - private Throwable exception; + private Throwable exception; - private Map attachments = new HashMap(); + private Map attachments = new HashMap(); - public RpcResult(){ + public RpcResult() { } - public RpcResult(Object result){ + public RpcResult(Object result) { this.result = result; } - public RpcResult(Throwable exception){ + public RpcResult(Throwable exception) { this.exception = exception; } @@ -54,8 +54,8 @@ public Object recreate() throws Throwable { } /** - * @deprecated Replace to getValue() * @see com.alibaba.dubbo.rpc.RpcResult#getValue() + * @deprecated Replace to getValue() */ @Deprecated public Object getResult() { @@ -63,8 +63,8 @@ public Object getResult() { } /** - * @deprecated Replace to setValue() * @see com.alibaba.dubbo.rpc.RpcResult#setValue() + * @deprecated Replace to setValue() */ @Deprecated public void setResult(Object result) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java index 767c7338a9c..679cfbd5a6d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java @@ -15,20 +15,16 @@ */ package com.alibaba.dubbo.rpc.listener; -import java.util.List; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.InvokerListener; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.*; + +import java.util.List; /** * ListenerInvoker - * + * * @author william.liangf */ public class ListenerInvokerWrapper implements Invoker { @@ -36,10 +32,10 @@ public class ListenerInvokerWrapper implements Invoker { private static final Logger logger = LoggerFactory.getLogger(ListenerInvokerWrapper.class); private final Invoker invoker; - + private final List listeners; - public ListenerInvokerWrapper(Invoker invoker, List listeners){ + public ListenerInvokerWrapper(Invoker invoker, List listeners) { if (invoker == null) { throw new IllegalArgumentException("invoker == null"); } @@ -73,10 +69,10 @@ public boolean isAvailable() { public Result invoke(Invocation invocation) throws RpcException { return invoker.invoke(invocation); } - + @Override public String toString() { - return getInterface() + " -> " + getUrl()==null?" ":getUrl().toString(); + return getInterface() + " -> " + getUrl() == null ? " " : getUrl().toString(); } public void destroy() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java index b5f2b6ff1ad..1b75315f878 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java @@ -1,64 +1,58 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol; -import java.lang.reflect.InvocationTargetException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.support.RpcUtils; +import com.alibaba.dubbo.rpc.*; +import com.alibaba.dubbo.rpc.support.RpcUtils; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; /** * AbstractInvoker. - * + * * @author qian.lei * @author william.liangf */ public abstract class AbstractInvoker implements Invoker { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); - private final Class type; + private final Class type; - private final URL url; + private final URL url; private final Map attachment; private volatile boolean available = true; private volatile boolean destroyed = false; - - public AbstractInvoker(Class type, URL url){ + + public AbstractInvoker(Class type, URL url) { this(type, url, (Map) null); } - + public AbstractInvoker(Class type, URL url, String[] keys) { this(type, url, convertAttachment(url, keys)); } @@ -72,7 +66,7 @@ public AbstractInvoker(Class type, URL url, Map attachment) { this.url = url; this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment); } - + private static Map convertAttachment(URL url, String[] keys) { if (keys == null || keys.length == 0) { return null; @@ -98,48 +92,48 @@ public URL getUrl() { public boolean isAvailable() { return available; } - + protected void setAvailable(boolean available) { this.available = available; } public void destroy() { - if (isDestroyed()) { - return; + if (isDestroyed()) { + return; } destroyed = true; setAvailable(false); - } - - public boolean isDestroyed() { - return destroyed; - } - + } + + public boolean isDestroyed() { + return destroyed; + } + public String toString() { return getInterface() + " -> " + (getUrl() == null ? "" : getUrl().toString()); } public Result invoke(Invocation inv) throws RpcException { - if(destroyed) { - throw new RpcException("Rpc invoker for service " + this + " on consumer " + NetUtils.getLocalHost() - + " use dubbo version " + Version.getVersion() - + " is DESTROYED, can not be invoked any more!"); + if (destroyed) { + throw new RpcException("Rpc invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + + " use dubbo version " + Version.getVersion() + + " is DESTROYED, can not be invoked any more!"); } - RpcInvocation invocation = (RpcInvocation) inv; + RpcInvocation invocation = (RpcInvocation) inv; invocation.setInvoker(this); if (attachment != null && attachment.size() > 0) { - invocation.addAttachmentsIfAbsent(attachment); + invocation.addAttachmentsIfAbsent(attachment); } Map context = RpcContext.getContext().getAttachments(); if (context != null) { - invocation.addAttachmentsIfAbsent(context); - } - if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)){ - invocation.setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); - } - RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); - - + invocation.addAttachmentsIfAbsent(context); + } + if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { + invocation.setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); + } + RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); + + try { return doInvoke(invocation); } catch (InvocationTargetException e) { // biz exception diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 8c1e46759c4..21c7316775c 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -16,19 +16,11 @@ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.serialize.Cleanable; import com.alibaba.dubbo.common.serialize.ObjectInput; -import com.alibaba.dubbo.common.serialize.OptimizedSerialization; -import com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization; import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; @@ -39,6 +31,12 @@ import com.alibaba.dubbo.remoting.transport.CodecSupport; import com.alibaba.dubbo.rpc.RpcInvocation; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; + import static com.alibaba.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.decodeInvocationArgument; /** @@ -48,13 +46,13 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec private static final Logger log = LoggerFactory.getLogger(DecodeableRpcInvocation.class); - private Channel channel; + private Channel channel; - private byte serializationType; + private byte serializationType; private InputStream inputStream; - private Request request; + private Request request; private volatile boolean hasDecoded; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 79c2d451e38..229de6d75e8 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -15,16 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.locks.ReentrantLock; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -37,21 +27,17 @@ import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.Transporter; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.Exchangers; +import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractProtocol; +import java.net.InetSocketAddress; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.ReentrantLock; + /** * dubbo protocol support. * @@ -64,15 +50,15 @@ public class DubboProtocol extends AbstractProtocol { public static final String NAME = "dubbo"; public static final String COMPATIBLE_CODEC_NAME = "dubbo1compatible"; - + public static final int DEFAULT_PORT = 20880; - + public final ReentrantLock lock = new ReentrantLock(); - + private final Map serverMap = new ConcurrentHashMap(); // - + private final Map referenceClientMap = new ConcurrentHashMap(); // - + private final ConcurrentMap ghostClientMap = new ConcurrentHashMap(); private final Set optimizers = new ConcurrentHashSet(); @@ -80,32 +66,32 @@ public class DubboProtocol extends AbstractProtocol { //consumer side export a stub service for dispatching event //servicekey-stubmethods private final ConcurrentMap stubServiceMethodsMap = new ConcurrentHashMap(); - + private static final String IS_CALLBACK_SERVICE_INVOKE = "_isCallBackServiceInvoke"; 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))){ + 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.contains(",")){ + if (methodsStr == null || !methodsStr.contains(",")) { hasMethod = inv.getMethodName().equals(methodsStr); } else { String[] methods = methodsStr.split(","); - for (String method : methods){ - if (inv.getMethodName().equals(method)){ + 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 ); + 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; } } @@ -131,12 +117,12 @@ public void connected(Channel channel) throws RemotingException { @Override public void disconnected(Channel channel) throws RemotingException { - if(logger.isInfoEnabled()){ - logger.info("disconected from "+ channel.getRemoteAddress() + ",url:" + channel.getUrl()); + if (logger.isInfoEnabled()) { + logger.info("disconected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); } invoke(channel, Constants.ON_DISCONNECT_KEY); } - + private void invoke(Channel channel, String methodKey) { Invocation invocation = createInvocation(channel, channel.getUrl(), methodKey); if (invocation != null) { @@ -147,7 +133,7 @@ private void invoke(Channel channel, String methodKey) { } } } - + private Invocation createInvocation(Channel channel, URL url, String methodKey) { String method = url.getParameter(methodKey); if (method == null || method.length() == 0) { @@ -158,19 +144,19 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) invocation.setAttachment(Constants.GROUP_KEY, url.getParameter(Constants.GROUP_KEY)); invocation.setAttachment(Constants.INTERFACE_KEY, url.getParameter(Constants.INTERFACE_KEY)); invocation.setAttachment(Constants.VERSION_KEY, url.getParameter(Constants.VERSION_KEY)); - if (url.getParameter(Constants.STUB_EVENT_KEY, false)){ + if (url.getParameter(Constants.STUB_EVENT_KEY, false)) { invocation.setAttachment(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()); } return invocation; } }; - + private static DubboProtocol INSTANCE; public DubboProtocol() { INSTANCE = this; } - + public static DubboProtocol getDubboProtocol() { if (INSTANCE == null) { ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME); // load @@ -185,45 +171,45 @@ public Collection getServers() { public Collection> getExporters() { return Collections.unmodifiableCollection(exporterMap.values()); } - - Map> getExporterMap(){ + + Map> getExporterMap() { return exporterMap; } - + private boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(channel.getUrl().getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + return url.getPort() == address.getPort() && + NetUtils.filterLocalHost(channel.getUrl().getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } - - Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException{ + + Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException { boolean isCallBackServiceInvoke = false; boolean isStubServiceInvoke = false; int port = channel.getLocalAddress().getPort(); String path = inv.getAttachments().get(Constants.PATH_KEY); //如果是客户端的回调服务. isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getAttachments().get(Constants.STUB_EVENT_KEY)); - if (isStubServiceInvoke){ + if (isStubServiceInvoke) { port = channel.getRemoteAddress().getPort(); } //callback isCallBackServiceInvoke = isClientSide(channel) && !isStubServiceInvoke; - if(isCallBackServiceInvoke){ - path = inv.getAttachments().get(Constants.PATH_KEY)+"."+inv.getAttachments().get(Constants.CALLBACK_SERVICE_KEY); + if (isCallBackServiceInvoke) { + path = inv.getAttachments().get(Constants.PATH_KEY) + "." + inv.getAttachments().get(Constants.CALLBACK_SERVICE_KEY); inv.getAttachments().put(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } String serviceKey = serviceKey(port, path, inv.getAttachments().get(Constants.VERSION_KEY), inv.getAttachments().get(Constants.GROUP_KEY)); DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); - + if (exporter == null) throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv); return exporter.getInvoker(); } - + public Collection> getInvokers() { return Collections.unmodifiableCollection(invokers); } @@ -234,20 +220,20 @@ public int getDefaultPort() { public Exporter export(Invoker invoker) throws RpcException { URL url = invoker.getUrl(); - + // export service. String key = serviceKey(url); DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); exporterMap.put(key, exporter); - + //export an stub service for dispaching event - Boolean isStubSupportEvent = url.getParameter(Constants.STUB_EVENT_KEY,Constants.DEFAULT_STUB_EVENT); - Boolean isCallbackservice = url.getParameter(Constants.IS_CALLBACK_SERVICE, false); - if (isStubSupportEvent && !isCallbackservice){ + Boolean isStubSupportEvent = url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT); + Boolean isCallbackService = url.getParameter(Constants.IS_CALLBACK_SERVICE, false); + if (isStubSupportEvent && !isCallbackService) { String stubServiceMethods = url.getParameter(Constants.STUB_EVENT_METHODS_KEY); - if (stubServiceMethods == null || stubServiceMethods.length() == 0 ){ - if (logger.isWarnEnabled()){ - logger.warn(new IllegalStateException("consumer [" +url.getParameter(Constants.INTERFACE_KEY) + + if (stubServiceMethods == null || stubServiceMethods.length() == 0) { + if (logger.isWarnEnabled()) { + logger.warn(new IllegalStateException("consumer [" + url.getParameter(Constants.INTERFACE_KEY) + "], has set stubproxy support event ,but no stub methods founded.")); } } else { @@ -296,23 +282,23 @@ private void optimizeSerialization(URL url) throws RpcException { throw new RpcException("Cannot instantiate the serialization optimizer class: " + className, e); } } - + private void openServer(URL url) { // find server. String key = url.getAddress(); //client 也可以暴露一个只有server可以调用的服务。 - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY,true); + boolean isServer = url.getParameter(Constants.IS_SERVER_KEY, true); if (isServer) { - ExchangeServer server = serverMap.get(key); - if (server == null) { - serverMap.put(key, createServer(url)); - } else { - //server支持reset,配合override功能使用 - server.reset(url); - } + ExchangeServer server = serverMap.get(key); + if (server == null) { + serverMap.put(key, createServer(url)); + } else { + //server支持reset,配合override功能使用 + server.reset(url); + } } } - + private ExchangeServer createServer(URL url) { //默认开启server关闭时发送readonly事件 url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); @@ -320,7 +306,7 @@ private ExchangeServer createServer(URL url) { url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); - if (str != null && str.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) + if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) throw new RpcException("Unsupported server type: " + str + ", url: " + url); url = url.addParameter(Constants.CODEC_KEY, Version.isCompatibleVersion() ? COMPATIBLE_CODEC_NAME : DubboCodec.NAME); @@ -350,20 +336,20 @@ public Invoker refer(Class serviceType, URL url) throws RpcException { invokers.add(invoker); return invoker; } - - private ExchangeClient[] getClients(URL url){ + + private ExchangeClient[] getClients(URL url) { //是否共享连接 boolean service_share_connect = false; int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0); //如果connections不配置,则共享连接,否则每服务每连接 - if (connections == 0){ + 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){ + if (service_share_connect) { clients[i] = getSharedClient(url); } else { clients[i] = initClient(url); @@ -371,35 +357,34 @@ private ExchangeClient[] getClients(URL url){ } return clients; } - + /** - *获取共享连接 + * 获取共享连接 */ - private ExchangeClient getSharedClient(URL url){ + private ExchangeClient getSharedClient(URL url) { String key = url.getAddress(); ReferenceCountExchangeClient client = referenceClientMap.get(key); - if ( client != null ){ - if ( !client.isClosed()){ + if (client != null) { + if (!client.isClosed()) { client.incrementAndGetCount(); return client; } else { -// logger.warn(new IllegalStateException("client is closed,but stay in clientmap .client :"+ client)); referenceClientMap.remove(key); } } ExchangeClient exchagneclient = initClient(url); - + client = new ReferenceCountExchangeClient(exchagneclient, ghostClientMap); referenceClientMap.put(key, client); ghostClientMap.remove(key); - return client; + return client; } /** * 创建新连接. */ private ExchangeClient initClient(URL url) { - + // client type setting. String str = url.getParameter(Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_CLIENT)); @@ -408,20 +393,20 @@ private ExchangeClient initClient(URL url) { url = url.addParameter(Constants.CODEC_KEY, Version.isCompatibleVersion() && compatible ? COMPATIBLE_CODEC_NAME : 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)) { + 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 ; + + ExchangeClient client; try { //设置连接应该是lazy的 - if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)){ - client = new LazyConnectExchangeClient(url ,requestHandler); + if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)) { + client = new LazyConnectExchangeClient(url, requestHandler); } else { - client = Exchangers.connect(url ,requestHandler); + client = Exchangers.connect(url, requestHandler); } } catch (RemotingException e) { throw new RpcException("Fail to create remoting client for service(" + url @@ -444,7 +429,7 @@ public void destroy() { } } } - + for (String key : new ArrayList(referenceClientMap.keySet())) { ExchangeClient client = referenceClientMap.remove(key); if (client != null) { @@ -458,7 +443,7 @@ public void destroy() { } } } - + for (String key : new ArrayList(ghostClientMap.keySet())) { ExchangeClient client = ghostClientMap.remove(key); if (client != null) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index dd27a534736..6b70d1d95ac 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -1,73 +1,73 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.net.InetSocketAddress; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.Parameters; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.Parameters; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.Exchangers; +import com.alibaba.dubbo.remoting.exchange.ResponseFuture; + +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * dubbo protocol support class. - * + * * @author chao.liuc */ -@SuppressWarnings("deprecation") -final class LazyConnectExchangeClient implements ExchangeClient{ +@SuppressWarnings("deprecation") +final class LazyConnectExchangeClient implements ExchangeClient { - private final static Logger logger = LoggerFactory.getLogger(LazyConnectExchangeClient.class); + private final static Logger logger = LoggerFactory.getLogger(LazyConnectExchangeClient.class); - private final URL url; - private final ExchangeHandler requestHandler; - private volatile ExchangeClient client; - private final Lock connectLock = new ReentrantLock(); + private final URL url; + private final ExchangeHandler requestHandler; + private volatile ExchangeClient client; + private final Lock connectLock = new ReentrantLock(); //lazy connect 如果没有初始化时的连接状态 - private final boolean initialState ; - - protected final boolean requestWithWarning; - - //当调用时warning,出现这个warning,表示程序可能存在bug. - static final String REQUEST_WITH_WARNING_KEY = "lazyclient_request_with_warning"; - - private AtomicLong warningcount = new AtomicLong(0); - + private final boolean initialState; + + protected final boolean requestWithWarning; + + //当调用时warning,出现这个warning,表示程序可能存在bug. + static final String REQUEST_WITH_WARNING_KEY = "lazyclient_request_with_warning"; + + private AtomicLong warningcount = new AtomicLong(0); + public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { //lazy connect ,need set send.reconnect = true, to avoid channel bad status. this.url = url.addParameter(Constants.SEND_RECONNECT_KEY, Boolean.TRUE.toString()); this.requestHandler = requestHandler; - this.initialState = url.getParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY,Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE); + this.initialState = url.getParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Constants.DEFAULT_LAZY_CONNECT_INITIAL_STATE); this.requestWithWarning = url.getParameter(REQUEST_WITH_WARNING_KEY, false); - } - + } + private void initClient() throws RemotingException { - if (client != null ) + if (client != null) return; if (logger.isInfoEnabled()) { logger.info("Lazy connect to " + url); @@ -82,7 +82,7 @@ private void initClient() throws RemotingException { } } - public ResponseFuture request(Object request) throws RemotingException { + public ResponseFuture request(Object request) throws RemotingException { warning(request); initClient(); return client.request(request); @@ -93,34 +93,36 @@ public URL getUrl() { } public InetSocketAddress getRemoteAddress() { - if (client == null){ - return InetSocketAddress.createUnresolved(url.getHost(), url.getPort()); - } else { - return client.getRemoteAddress(); + if (client == null) { + return InetSocketAddress.createUnresolved(url.getHost(), url.getPort()); + } else { + return client.getRemoteAddress(); } } - public ResponseFuture request(Object request, int timeout) throws RemotingException { + + public ResponseFuture request(Object request, int timeout) throws RemotingException { warning(request); - initClient(); + initClient(); return client.request(request, timeout); - } - - /** - * 如果配置了调用warning,则每调用5000次warning一次. - * @param request - */ - private void warning(Object request){ - if (requestWithWarning ){ - if (warningcount.get() % 5000 == 0){ - logger.warn(new IllegalStateException("safe guard client , should not be called ,must have a bug.")); - } - warningcount.incrementAndGet() ; - } - } - + } + + /** + * 如果配置了调用warning,则每调用5000次warning一次. + * + * @param request + */ + private void warning(Object request) { + if (requestWithWarning) { + if (warningcount.get() % 5000 == 0) { + logger.warn(new IllegalStateException("safe guard client , should not be called ,must have a bug.")); + } + warningcount.incrementAndGet(); + } + } + public ChannelHandler getChannelHandler() { checkClient(); - return client.getChannelHandler(); + return client.getChannelHandler(); } public boolean isConnected() { @@ -132,10 +134,10 @@ public boolean isConnected() { } public InetSocketAddress getLocalAddress() { - if (client == null){ - return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); - } else { - return client.getLocalAddress(); + if (client == null) { + return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); + } else { + return client.getLocalAddress(); } } @@ -173,11 +175,11 @@ public void close(int timeout) { public void reset(URL url) { checkClient(); client.reset(url); - } - - @Deprecated - public void reset(Parameters parameters){ - reset(getUrl().addParameters(parameters.getParameters())); + } + + @Deprecated + public void reset(Parameters parameters) { + reset(getUrl().addParameters(parameters.getParameters())); } public void reconnect() throws RemotingException { @@ -186,10 +188,10 @@ public void reconnect() throws RemotingException { } public Object getAttribute(String key) { - if (client == null){ - return null; - } else { - return client.getAttribute(key); + if (client == null) { + return null; + } else { + return client.getAttribute(key); } } @@ -204,10 +206,10 @@ public void removeAttribute(String key) { } public boolean hasAttribute(String key) { - if (client == null){ - return false; + if (client == null) { + return false; } else { - return client.hasAttribute(key); + return client.hasAttribute(key); } } @@ -216,5 +218,5 @@ private void checkClient() { throw new IllegalStateException( "LazyConnectExchangeClient state error. the client has not be init .url:" + url); } - } + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index bf5e50cb4c6..dc0227f995e 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -49,5 +49,9 @@ provided true + + com.squareup.okhttp3 + okhttp + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/AbstractHessianConnection.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/AbstractHessianConnection.java new file mode 100644 index 00000000000..e2c2515b295 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/AbstractHessianConnection.java @@ -0,0 +1,33 @@ +package com.alibaba.dubbo.rpc.protocol.hessian; + +import com.caucho.hessian.client.HessianConnection; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author Xs + */ +public abstract class AbstractHessianConnection implements HessianConnection { + + protected final ByteArrayOutputStream output; + + AbstractHessianConnection() { + this.output = new ByteArrayOutputStream(); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return output; + } + + + @Override + public void destroy() throws IOException { + } + + @Override + public void close() throws IOException { + } +} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java index 6a9f7c75c3f..ab0a0ba74db 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -13,17 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.rpc.protocol.hessian; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +package com.alibaba.dubbo.rpc.protocol.hessian; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; @@ -38,39 +28,48 @@ import com.caucho.hessian.client.HessianProxyFactory; import com.caucho.hessian.io.HessianMethodSerializationException; import com.caucho.hessian.server.HessianSkeleton; - -/** - * http rpc support. - * - * @author qianlei - */ -public class HessianProtocol extends AbstractProxyProtocol { - - private final Map serverMap = new ConcurrentHashMap(); + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * http rpc support. + * + * @author qianlei + */ +public class HessianProtocol extends AbstractProxyProtocol { + + private final Map serverMap = new ConcurrentHashMap(); private final Map skeletonMap = new ConcurrentHashMap(); - + private HttpBinder httpBinder; - + public HessianProtocol() { super(HessianException.class); - } + } public void setHttpBinder(HttpBinder httpBinder) { this.httpBinder = httpBinder; } - - public int getDefaultPort() { - return 80; + + public int getDefaultPort() { + return 80; } private class HessianHandler implements HttpHandler { - + public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); HessianSkeleton skeleton = skeletonMap.get(uri); - if (! request.getMethod().equalsIgnoreCase("POST")) { + if (!request.getMethod().equalsIgnoreCase("POST")) { response.setStatus(500); } else { RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); @@ -81,40 +80,42 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } } } - - } - - protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - String addr = url.getIp() + ":" + url.getPort(); - HttpServer server = serverMap.get(addr); - if (server == null) { - server = httpBinder.bind(url, new HessianHandler()); - serverMap.put(addr, server); + + } + + protected Runnable doExport(T impl, Class type, URL url) throws RpcException { + String addr = url.getIp() + ":" + url.getPort(); + HttpServer server = serverMap.get(addr); + if (server == null) { + server = httpBinder.bind(url, new HessianHandler()); + serverMap.put(addr, server); } final String path = url.getAbsolutePath(); HessianSkeleton skeleton = new HessianSkeleton(impl, type); - skeletonMap.put(path, skeleton); - return new Runnable() { + skeletonMap.put(path, skeleton); + return new Runnable() { public void run() { - skeletonMap.remove(path); - } - }; - } + skeletonMap.remove(path); + } + }; + } @SuppressWarnings("unchecked") protected T doRefer(Class serviceType, URL url) throws RpcException { HessianProxyFactory hessianProxyFactory = new HessianProxyFactory(); String client = url.getParameter(Constants.CLIENT_KEY, Constants.DEFAULT_HTTP_CLIENT); - if ("httpclient".equals(client)) { + if ("httpclient".equalsIgnoreCase(client)) { hessianProxyFactory.setConnectionFactory(new HttpClientConnectionFactory()); - } else if (client != null && client.length() > 0 && ! Constants.DEFAULT_HTTP_CLIENT.equals(client)) { + } else if ("okHttpClient".equalsIgnoreCase(client)) { + hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory(url)); + } else if (client != null && client.length() > 0 && !Constants.DEFAULT_HTTP_CLIENT.equals(client)) { throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); } int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); hessianProxyFactory.setConnectTimeout(timeout); - hessianProxyFactory.setReadTimeout(timeout); - return (T) hessianProxyFactory.create(serviceType, url.setProtocol("http").toJavaURL(), Thread.currentThread().getContextClassLoader()); - } + hessianProxyFactory.setReadTimeout(timeout); + return (T) hessianProxyFactory.create(serviceType, url.setProtocol("http").toJavaURL(), Thread.currentThread().getContextClassLoader()); + } protected int getErrorCode(Throwable e) { if (e instanceof HessianConnectionException) { @@ -130,22 +131,22 @@ protected int getErrorCode(Throwable e) { } return super.getErrorCode(e); } - - public void destroy() { - super.destroy(); - for (String key : new ArrayList(serverMap.keySet())) { - HttpServer server = serverMap.remove(key); - if (server != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close hessian server " + server.getUrl()); - } - server.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - } - + + public void destroy() { + super.destroy(); + for (String key : new ArrayList(serverMap.keySet())) { + HttpServer server = serverMap.remove(key); + if (server != null) { + try { + if (logger.isInfoEnabled()) { + logger.info("Close hessian server " + server.getUrl()); + } + server.close(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } + } + } + } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java index e8cf9f19ad0..6b2c612a008 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java @@ -15,38 +15,33 @@ */ package com.alibaba.dubbo.rpc.protocol.hessian; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; - import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.message.BasicHeader; -import com.caucho.hessian.client.HessianConnection; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; /** * HttpClientConnection - * + * * @author william.liangf */ -public class HttpClientConnection implements HessianConnection { - +public class HttpClientConnection extends AbstractHessianConnection { + private final HttpClient httpClient; - private final ByteArrayOutputStream output; - + private final HttpPost request; - + private volatile HttpResponse response; public HttpClientConnection(HttpClient httpClient, URL url) { this.httpClient = httpClient; - this.output = new ByteArrayOutputStream(); this.request = new HttpPost(url.toString()); } @@ -68,7 +63,7 @@ public int getStatusCode() { } public String getStatusMessage() { - return response == null || response.getStatusLine() == null ? null : response.getStatusLine().getReasonPhrase(); + return response == null || response.getStatusLine() == null ? null : response.getStatusLine().getReasonPhrase(); } public InputStream getInputStream() throws IOException { @@ -77,12 +72,6 @@ public InputStream getInputStream() throws IOException { public void close() throws IOException { HttpPost request = this.request; - if (request != null) { - request.abort(); - } + request.abort(); } - - public void destroy() throws IOException { - } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnection.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnection.java new file mode 100644 index 00000000000..0247a848291 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnection.java @@ -0,0 +1,53 @@ +package com.alibaba.dubbo.rpc.protocol.hessian; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +/** + * @author Xs + */ +public class OkHttpConnection extends AbstractHessianConnection { + + private final OkHttpClient okHttpClient; + + private final Request.Builder builder; + + private volatile Response response; + + public OkHttpConnection(OkHttpClient client, URL url) { + this.okHttpClient = client; + this.builder = new Request.Builder().url(url); + } + + @Override + public void addHeader(String key, String value) { + builder.addHeader(key, value); + } + + @Override + public void sendRequest() throws IOException { + Request request = builder.post(RequestBody.create(null, output.toByteArray())).build(); + this.response = okHttpClient.newCall(request).execute(); + } + + @Override + public int getStatusCode() { + return response == null ? 0 : response.code(); + } + + @Override + public String getStatusMessage() { + return response == null ? null : response.message(); + } + + @Override + public InputStream getInputStream() throws IOException { + return response == null || response.body() == null ? null : response.body().byteStream(); + } +} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java new file mode 100644 index 00000000000..7b85811cbd4 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -0,0 +1,43 @@ +package com.alibaba.dubbo.rpc.protocol.hessian; + +import com.alibaba.dubbo.common.Constants; +import com.caucho.hessian.client.HessianConnection; +import com.caucho.hessian.client.HessianConnectionFactory; +import com.caucho.hessian.client.HessianProxyFactory; +import okhttp3.OkHttpClient; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +/** + * @author Xs + */ +public class OkHttpConnectionFactory implements HessianConnectionFactory { + + private final OkHttpClient client; + + + public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + + Boolean enableTrace = url.getParameter(Constants.ENABLE_TRACE_KEY, true); + if (enableTrace) { + + } + int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + builder.readTimeout(timeout, TimeUnit.MILLISECONDS); + builder.writeTimeout(timeout, TimeUnit.MILLISECONDS); + client = builder.build(); + } + + @Override + public void setHessianProxyFactory(HessianProxyFactory hessianProxyFactory) { + // NOP + } + + @Override + public HessianConnection open(URL url) throws IOException { + return new OkHttpConnection(client, url); + } +} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocolTest.java b/dubbo-rpc/dubbo-rpc-hessian/src/test/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocolTest.java index 5939f036474..9ef84c0efe9 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/test/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocolTest.java @@ -69,7 +69,24 @@ public void testHttpClient() { invoker.destroy(); exporter.unexport(); } - + + @Test + public void testOkHttpClient() { + HessianServiceImpl server = new HessianServiceImpl(); + Assert.assertFalse(server.isCalled()); + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + URL url = URL.valueOf("hessian://127.0.0.1:5342/" + HessianService.class.getName() + "?version=1.0.0&client=okHttpClient"); + Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); + Invoker invoker = protocol.refer(HessianService.class, url); + HessianService client = proxyFactory.getProxy(invoker); + String result = client.sayHello("haha"); + Assert.assertTrue(server.isCalled()); + Assert.assertEquals("Hello, haha", result); + invoker.destroy(); + exporter.unexport(); + } + @Test public void testTimeOut() { HessianServiceImpl server = new HessianServiceImpl(); diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java index 84bc398a3fb..f7f968cf54f 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java @@ -15,22 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.http; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.remoting.RemoteAccessException; -import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; -import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; -import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; -import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.http.HttpBinder; @@ -39,22 +23,36 @@ import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import org.springframework.remoting.RemoteAccessException; +import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; +import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; +import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; +import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * HttpProtocol - * + * * @author william.liangf */ public class HttpProtocol extends AbstractProxyProtocol { - public static final int DEFAULT_PORT = 80; + public static final int DEFAULT_PORT = 80; private final Map serverMap = new ConcurrentHashMap(); private final Map skeletonMap = new ConcurrentHashMap(); private HttpBinder httpBinder; - + public HttpProtocol() { super(RemoteAccessException.class); } @@ -68,12 +66,12 @@ public int getDefaultPort() { } private class InternalHandler implements HttpHandler { - + public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); HttpInvokerServiceExporter skeleton = skeletonMap.get(uri); - if (! request.getMethod().equalsIgnoreCase("POST")) { + if (!request.getMethod().equalsIgnoreCase("POST")) { response.setStatus(500); } else { RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); @@ -84,7 +82,7 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } } } - + } protected Runnable doExport(final T impl, Class type, URL url) throws RpcException { @@ -118,21 +116,21 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc httpProxyFactoryBean.setServiceInterface(serviceType); String client = url.getParameter(Constants.CLIENT_KEY); if (client == null || client.length() == 0 || "simple".equals(client)) { - SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { - protected void prepareConnection(HttpURLConnection con, - int contentLength) throws IOException { - super.prepareConnection(con, contentLength); - con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); - } - }; - httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); + SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { + protected void prepareConnection(HttpURLConnection con, + int contentLength) throws IOException { + super.prepareConnection(con, contentLength); + con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + } + }; + httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if ("commons".equals(client)) { - CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); - httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); - httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); - } else if (client != null && client.length() > 0) { - throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); + CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); + httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); + } else if (client.length() > 0) { + throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); } httpProxyFactoryBean.afterPropertiesSet(); return (T) httpProxyFactoryBean.getObject(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java index 92d259907db..26826922bfd 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,7 +43,6 @@ public class DubboHttpServer extends BaseRestServer { private final ResteasyDeployment deployment = new ResteasyDeployment(); private HttpBinder httpBinder; private HttpServer httpServer; -// private boolean isExternalServer; public DubboHttpServer(HttpBinder httpBinder) { this.httpBinder = httpBinder; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java index 0b7c9b38732..03f8634c62f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,8 +35,6 @@ public RestServer createServer(String name) { // TODO move names to Constants if ("servlet".equalsIgnoreCase(name) || "jetty".equalsIgnoreCase(name) || "tomcat".equalsIgnoreCase(name)) { return new DubboHttpServer(httpBinder); -// } else if ("tjws".equalsIgnoreCase(name)) { -// return new TjwsServer(); } else if ("netty".equalsIgnoreCase(name)) { return new NettyServer(); } else if ("sunhttp".equalsIgnoreCase(name)) { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java index 92b1b440531..800c67c9c0b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +20,6 @@ import org.apache.commons.io.IOUtils; import javax.annotation.Priority; -import javax.ws.rs.Priorities; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java index 6c4dee9837f..12509b2798b 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -1,10 +1,10 @@ /** * File Created at 2011-12-05 * $Id$ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -14,28 +14,6 @@ package com.alibaba.dubbo.rpc.protocol.thrift; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.lang.StringUtils; -import org.apache.thrift.TApplicationException; -import org.apache.thrift.TBase; -import org.apache.thrift.TException; -import org.apache.thrift.TFieldIdEnum; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.ClassHelper; @@ -49,6 +27,27 @@ import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; +import org.apache.commons.lang.StringUtils; +import org.apache.thrift.TApplicationException; +import org.apache.thrift.TBase; +import org.apache.thrift.TException; +import org.apache.thrift.TFieldIdEnum; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TIOStreamTransport; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; /** * Thrift framed protocol codec. @@ -73,7 +72,7 @@ */ public class ThriftCodec implements Codec2 { - private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger( 0 ); + private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger(0); private static final ConcurrentMap> cachedClass = new ConcurrentHashMap>(); @@ -91,75 +90,76 @@ public class ThriftCodec implements Codec2 { public static final String PARAMETER_CLASS_NAME_GENERATOR = "class.name.generator"; - public static final byte VERSION = (byte)1; + public static final byte VERSION = (byte) 1; public static final short MAGIC = (short) 0xdabc; - public void encode( Channel channel, ChannelBuffer buffer, Object message ) + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { - if ( message instanceof Request ) { - encodeRequest( channel, buffer, ( Request ) message ); - } - else if ( message instanceof Response ) { - encodeResponse( channel, buffer, ( Response ) message ); + if (message instanceof Request) { + encodeRequest(channel, buffer, (Request) message); + } else if (message instanceof Response) { + encodeResponse(channel, buffer, (Response) message); } else { throw new UnsupportedOperationException( - new StringBuilder( 32 ) - .append( "Thrift codec only support encode " ) - .append( Request.class.getName() ) - .append( " and " ) - .append( Response.class.getName() ) - .toString() ); + new StringBuilder(32) + .append("Thrift codec only support encode ") + .append(Request.class.getName()) + .append(" and ") + .append(Response.class.getName()) + .toString()); } } - public Object decode( Channel channel, ChannelBuffer buffer ) throws IOException { + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int available = buffer.readableBytes(); - if ( available < MESSAGE_SHORTEST_LENGTH ) { + if (available < MESSAGE_SHORTEST_LENGTH) { return DecodeResult.NEED_MORE_INPUT; } else { - TIOStreamTransport transport = new TIOStreamTransport( new ChannelBufferInputStream(buffer)); + TIOStreamTransport transport = new TIOStreamTransport(new ChannelBufferInputStream(buffer)); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); short magic; int messageLength; - try{ + try { // protocol.readI32(); // skip the first message length byte[] bytes = new byte[4]; - transport.read( bytes, 0, 4 ); + transport.read(bytes, 0, 4); magic = protocol.readI16(); messageLength = protocol.readI32(); - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); + } catch (TException e) { + throw new IOException(e.getMessage(), e); } - if ( MAGIC != magic ) { + if (MAGIC != magic) { throw new IOException( - new StringBuilder( 32 ) - .append( "Unknown magic code " ) - .append( magic ) - .toString() ); + new StringBuilder(32) + .append("Unknown magic code ") + .append(magic) + .toString()); } - if ( available < messageLength ) { return DecodeResult.NEED_MORE_INPUT; } + if (available < messageLength) { + return DecodeResult.NEED_MORE_INPUT; + } - return decode( protocol ); + return decode(protocol); } } - private Object decode( TProtocol protocol ) + private Object decode(TProtocol protocol) throws IOException { // version @@ -174,267 +174,273 @@ private Object decode( TProtocol protocol ) serviceName = protocol.readString(); id = protocol.readI64(); message = protocol.readMessageBegin(); - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); + } catch (TException e) { + throw new IOException(e.getMessage(), e); } - if ( message.type == TMessageType.CALL ) { + if (message.type == TMessageType.CALL) { RpcInvocation result = new RpcInvocation(); - result.setAttachment(Constants.INTERFACE_KEY, serviceName ); - result.setMethodName( message.name ); + result.setAttachment(Constants.INTERFACE_KEY, serviceName); + result.setMethodName(message.name); String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName( serviceName, message.name ); + .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name); - if ( StringUtils.isEmpty( argsClassName ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - "The specified interface name incorrect." ); + if (StringUtils.isEmpty(argsClassName)) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, + "The specified interface name incorrect."); } - Class clazz = cachedClass.get( argsClassName ); + Class clazz = cachedClass.get(argsClassName); - if ( clazz == null ) { + if (clazz == null) { try { - clazz = ClassHelper.forNameWithThreadContextClassLoader( argsClassName ); + clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName); - cachedClass.putIfAbsent( argsClassName, clazz ); + cachedClass.putIfAbsent(argsClassName, clazz); - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (ClassNotFoundException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase args; try { - args = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + args = (TBase) clazz.newInstance(); + } catch (InstantiationException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - try{ - args.read( protocol ); + try { + args.read(protocol); protocol.readMessageEnd(); - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (TException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } List parameters = new ArrayList(); - List> parameterTypes =new ArrayList>(); + List> parameterTypes = new ArrayList>(); int index = 1; - while ( true ) { + while (true) { - TFieldIdEnum fieldIdEnum = args.fieldForId( index++ ); + TFieldIdEnum fieldIdEnum = args.fieldForId(index++); - if ( fieldIdEnum == null ) { break; } + if (fieldIdEnum == null) { + break; + } String fieldName = fieldIdEnum.getFieldName(); - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); + String getMethodName = ThriftUtils.generateGetMethodName(fieldName); Method getMethod; try { - getMethod = clazz.getMethod( getMethodName ); - } catch ( NoSuchMethodException e ) { + getMethod = clazz.getMethod(getMethodName); + } catch (NoSuchMethodException e) { throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - parameterTypes.add( getMethod.getReturnType() ); + parameterTypes.add(getMethod.getReturnType()); try { - parameters.add( getMethod.invoke( args ) ); - } catch ( IllegalAccessException e ) { + parameters.add(getMethod.invoke(args)); + } catch (IllegalAccessException e) { throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { + RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (InvocationTargetException e) { throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } - result.setArguments( parameters.toArray() ); + result.setArguments(parameters.toArray()); result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); - Request request = new Request( id ); - request.setData( result ); + Request request = new Request(id); + request.setData(result); - cachedRequest.putIfAbsent( id, - RequestData.create( message.seqid, serviceName, message.name ) ); + cachedRequest.putIfAbsent(id, + RequestData.create(message.seqid, serviceName, message.name)); return request; - } else if ( message.type == TMessageType.EXCEPTION ) { + } else if (message.type == TMessageType.EXCEPTION) { TApplicationException exception; try { - exception = TApplicationException.read( protocol ); + exception = TApplicationException.read(protocol); protocol.readMessageEnd(); - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); + } catch (TException e) { + throw new IOException(e.getMessage(), e); } RpcResult result = new RpcResult(); - result.setException( new RpcException( exception.getMessage() ) ); + result.setException(new RpcException(exception.getMessage())); Response response = new Response(); - response.setResult( result ); + response.setResult(result); - response.setId( id ); + response.setId(id); return response; - } else if ( message.type == TMessageType.REPLY ) { + } else if (message.type == TMessageType.REPLY) { - String resultClassName = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName( serviceName, message.name ); + String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) + .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name); - if ( StringUtils.isEmpty( resultClassName ) ) { + if (StringUtils.isEmpty(resultClassName)) { throw new IllegalArgumentException( - new StringBuilder( 32 ) - .append( "Could not infer service result class name from service name " ) - .append( serviceName ) - .append( ", the service name you specified may not generated by thrift idl compiler" ) - .toString() ); + new StringBuilder(32) + .append("Could not infer service result class name from service name ") + .append(serviceName) + .append(", the service name you specified may not generated by thrift idl compiler") + .toString()); } - Class clazz = cachedClass.get( resultClassName ); + Class clazz = cachedClass.get(resultClassName); - if ( clazz == null ) { + if (clazz == null) { try { - clazz = ClassHelper.forNameWithThreadContextClassLoader( resultClassName ); + clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent( resultClassName, clazz ); + cachedClass.putIfAbsent(resultClassName, clazz); - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (ClassNotFoundException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } - TBase result; + TBase result; try { - result = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + result = (TBase) clazz.newInstance(); + } catch (InstantiationException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { - result.read( protocol ); + result.read(protocol); protocol.readMessageEnd(); - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (TException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } Object realResult = null; int index = 0; - while ( true ) { + while (true) { - TFieldIdEnum fieldIdEnum = result.fieldForId( index++ ); + TFieldIdEnum fieldIdEnum = result.fieldForId(index++); - if ( fieldIdEnum == null ) { break ; } + if (fieldIdEnum == null) { + break; + } Field field; try { - field = clazz.getDeclaredField( fieldIdEnum.getFieldName() ); - field.setAccessible( true ); - } catch ( NoSuchFieldException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + field = clazz.getDeclaredField(fieldIdEnum.getFieldName()); + field.setAccessible(true); + } catch (NoSuchFieldException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { - realResult = field.get( result ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + realResult = field.get(result); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - if ( realResult != null ) { break ; } + if (realResult != null) { + break; + } } Response response = new Response(); - response.setId( id ); + response.setId(id); RpcResult rpcResult = new RpcResult(); - if ( realResult instanceof Throwable ) { - rpcResult.setException( ( Throwable ) realResult ); + if (realResult instanceof Throwable) { + rpcResult.setException((Throwable) realResult); } else { rpcResult.setValue(realResult); } - response.setResult( rpcResult ); + response.setResult(rpcResult); return response; } else { // Impossible - throw new IOException( ); + throw new IOException(); } } - private void encodeRequest( Channel channel, ChannelBuffer buffer, Request request ) + private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { - RpcInvocation inv = ( RpcInvocation ) request.getData(); + RpcInvocation inv = (RpcInvocation) request.getData(); int seqId = nextSeqId(); String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); - if ( StringUtils.isEmpty( serviceName ) ) { + if (StringUtils.isEmpty(serviceName)) { throw new IllegalArgumentException( - new StringBuilder( 32 ) - .append( "Could not find service name in attachment with key " ) + new StringBuilder(32) + .append("Could not find service name in attachment with key ") .append(Constants.INTERFACE_KEY) - .toString() ); + .toString()); } TMessage message = new TMessage( inv.getMethodName(), TMessageType.CALL, - seqId ); + seqId); - String methodArgs = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateArgsClassName(serviceName, inv.getMethodName()); + String methodArgs = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) + .getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) + .generateArgsClassName(serviceName, inv.getMethodName()); - if ( StringUtils.isEmpty( methodArgs ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder(32).append( - "Could not encode request, the specified interface may be incorrect." ).toString() ); + if (StringUtils.isEmpty(methodArgs)) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, + new StringBuilder(32).append( + "Could not encode request, the specified interface may be incorrect.").toString()); } - Class clazz = cachedClass.get( methodArgs ); + Class clazz = cachedClass.get(methodArgs); - if ( clazz == null ) { + if (clazz == null) { try { - clazz = ClassHelper.forNameWithThreadContextClassLoader( methodArgs ); + clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs); - cachedClass.putIfAbsent( methodArgs, clazz ); + cachedClass.putIfAbsent(methodArgs, clazz); - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (ClassNotFoundException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } @@ -443,86 +449,88 @@ private void encodeRequest( Channel channel, ChannelBuffer buffer, Request reque try { args = (TBase) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (InstantiationException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - for( int i = 0; i < inv.getArguments().length; i++ ) { + for (int i = 0; i < inv.getArguments().length; i++) { Object obj = inv.getArguments()[i]; - if ( obj == null ) { continue; } + if (obj == null) { + continue; + } - TFieldIdEnum field = args.fieldForId( i + 1 ); + TFieldIdEnum field = args.fieldForId(i + 1); - String setMethodName = ThriftUtils.generateSetMethodName( field.getFieldName() ); + String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName()); Method method; try { - method = clazz.getMethod( setMethodName, inv.getParameterTypes()[i] ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]); + } catch (NoSuchMethodException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { - method.invoke( args, obj ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + method.invoke(args, obj); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (InvocationTargetException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); + RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - TIOStreamTransport transport = new TIOStreamTransport( bos ); + TIOStreamTransport transport = new TIOStreamTransport(bos); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); int headerLength, messageLength; byte[] bytes = new byte[4]; try { // magic - protocol.writeI16( MAGIC ); + protocol.writeI16(MAGIC); // message length placeholder - protocol.writeI32( Integer.MAX_VALUE ); + protocol.writeI32(Integer.MAX_VALUE); // message header length placeholder - protocol.writeI16( Short.MAX_VALUE ); + protocol.writeI16(Short.MAX_VALUE); // version - protocol.writeByte( VERSION ); + protocol.writeByte(VERSION); // service name - protocol.writeString( serviceName ); + protocol.writeString(serviceName); // dubbo request id - protocol.writeI64( request.getId() ); + protocol.writeI64(request.getId()); protocol.getTransport().flush(); // header size headerLength = bos.size(); // message body - protocol.writeMessageBegin( message ); - args.write( protocol ); + protocol.writeMessageBegin(message); + args.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); // fill in message length and header length try { - TFramedTransport.encodeFrameSize( messageLength, bytes ); - bos.setWriteIndex( MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short )( 0xffff & headerLength ) ); + TFramedTransport.encodeFrameSize(messageLength, bytes); + bos.setWriteIndex(MESSAGE_LENGTH_INDEX); + protocol.writeI32(messageLength); + bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX); + protocol.writeI16((short) (0xffff & headerLength)); } finally { - bos.setWriteIndex( oldIndex ); + bos.setWriteIndex(oldIndex); } - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (TException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } buffer.writeBytes(bytes); @@ -530,32 +538,32 @@ private void encodeRequest( Channel channel, ChannelBuffer buffer, Request reque } - private void encodeResponse( Channel channel, ChannelBuffer buffer, Response response ) + private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException { - RpcResult result = ( RpcResult ) response.getResult(); + RpcResult result = (RpcResult) response.getResult(); - RequestData rd = cachedRequest.get( response.getId() ); + RequestData rd = cachedRequest.get(response.getId()); - String resultClassName = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ).getExtension( - channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateResultClassName(rd.serviceName, rd.methodName); + String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension( + channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) + .generateResultClassName(rd.serviceName, rd.methodName); - if ( StringUtils.isEmpty( resultClassName ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder( 32 ).append( - "Could not encode response, the specified interface may be incorrect." ).toString() ); + if (StringUtils.isEmpty(resultClassName)) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, + new StringBuilder(32).append( + "Could not encode response, the specified interface may be incorrect.").toString()); } - Class clazz = cachedClass.get( resultClassName ); + Class clazz = cachedClass.get(resultClassName); - if ( clazz == null ) { + if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent( resultClassName, clazz ); - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + cachedClass.putIfAbsent(resultClassName, clazz); + } catch (ClassNotFoundException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } @@ -563,81 +571,83 @@ private void encodeResponse( Channel channel, ChannelBuffer buffer, Response res TBase resultObj; try { - resultObj = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + resultObj = (TBase) clazz.newInstance(); + } catch (InstantiationException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } TApplicationException applicationException = null; TMessage message; - if ( result.hasException() ) { + if (result.hasException()) { Throwable throwable = result.getException(); int index = 1; boolean found = false; - while ( true ) { - TFieldIdEnum fieldIdEnum = resultObj.fieldForId( index++ ); - if ( fieldIdEnum == null ) { break; } + while (true) { + TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++); + if (fieldIdEnum == null) { + break; + } String fieldName = fieldIdEnum.getFieldName(); - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); - String setMethodName = ThriftUtils.generateSetMethodName( fieldName ); + String getMethodName = ThriftUtils.generateGetMethodName(fieldName); + String setMethodName = ThriftUtils.generateSetMethodName(fieldName); Method getMethod; Method setMethod; try { - getMethod = clazz.getMethod( getMethodName ); - if ( getMethod.getReturnType().equals( throwable.getClass() ) ) { + getMethod = clazz.getMethod(getMethodName); + if (getMethod.getReturnType().equals(throwable.getClass())) { found = true; - setMethod = clazz.getMethod( setMethodName, throwable.getClass() ); - setMethod.invoke( resultObj, throwable ); + setMethod = clazz.getMethod(setMethodName, throwable.getClass()); + setMethod.invoke(resultObj, throwable); } - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (NoSuchMethodException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (InvocationTargetException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } - if ( !found ) { - applicationException = new TApplicationException( throwable.getMessage() ); + if (!found) { + applicationException = new TApplicationException(throwable.getMessage()); } } else { Object realResult = result.getResult(); // result field id is 0 - String fieldName = resultObj.fieldForId( 0 ).getFieldName(); - String setMethodName = ThriftUtils.generateSetMethodName( fieldName ); - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); + String fieldName = resultObj.fieldForId(0).getFieldName(); + String setMethodName = ThriftUtils.generateSetMethodName(fieldName); + String getMethodName = ThriftUtils.generateGetMethodName(fieldName); Method getMethod; Method setMethod; try { - getMethod = clazz.getMethod( getMethodName ); - setMethod = clazz.getMethod( setMethodName, getMethod.getReturnType() ); - setMethod.invoke( resultObj, realResult ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + getMethod = clazz.getMethod(getMethodName); + setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType()); + setMethod.invoke(resultObj, realResult); + } catch (NoSuchMethodException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (InvocationTargetException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } - if ( applicationException != null ) { - message = new TMessage( rd.methodName, TMessageType.EXCEPTION, rd.id ); + if (applicationException != null) { + message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id); } else { - message = new TMessage( rd.methodName, TMessageType.REPLY, rd.id ); + message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id); } - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); + RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - TIOStreamTransport transport = new TIOStreamTransport( bos ); + TIOStreamTransport transport = new TIOStreamTransport(bos); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); int messageLength; int headerLength; @@ -645,46 +655,46 @@ private void encodeResponse( Channel channel, ChannelBuffer buffer, Response res byte[] bytes = new byte[4]; try { // magic - protocol.writeI16( MAGIC ); + protocol.writeI16(MAGIC); // message length - protocol.writeI32( Integer.MAX_VALUE ); + protocol.writeI32(Integer.MAX_VALUE); // message header length - protocol.writeI16( Short.MAX_VALUE ); + protocol.writeI16(Short.MAX_VALUE); // version - protocol.writeByte( VERSION ); + protocol.writeByte(VERSION); // service name - protocol.writeString( rd.serviceName ); + protocol.writeString(rd.serviceName); // id - protocol.writeI64( response.getId() ); + protocol.writeI64(response.getId()); protocol.getTransport().flush(); headerLength = bos.size(); // message - protocol.writeMessageBegin( message ); - switch ( message.type ) { + protocol.writeMessageBegin(message); + switch (message.type) { case TMessageType.EXCEPTION: - applicationException.write( protocol ); + applicationException.write(protocol); break; case TMessageType.REPLY: - resultObj.write( protocol ); + resultObj.write(protocol); break; } protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); - try{ - TFramedTransport.encodeFrameSize( messageLength, bytes ); - bos.setWriteIndex( MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); + try { + TFramedTransport.encodeFrameSize(messageLength, bytes); + bos.setWriteIndex(MESSAGE_LENGTH_INDEX); + protocol.writeI32(messageLength); + bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX); + protocol.writeI16((short) (0xffff & headerLength)); } finally { - bos.setWriteIndex( oldIndex ); + bos.setWriteIndex(oldIndex); } - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); + } catch (TException e) { + throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } buffer.writeBytes(bytes); @@ -706,7 +716,7 @@ static class RequestData { String serviceName; String methodName; - static RequestData create( int id, String sn, String mn ) { + static RequestData create(int id, String sn, String mn) { RequestData result = new RequestData(); result.id = id; result.serviceName = sn; diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml new file mode 100644 index 00000000000..8bf675546c1 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -0,0 +1,23 @@ + + + + dubbo-tracker + com.alibaba + 2.8.4 + + 4.0.0 + + dubbo-tracker-api + jar + + + + com.alibaba + dubbo-common + ${project.parent.version} + + + + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java new file mode 100644 index 00000000000..e9be2ba6736 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.common.extension.SPI; + +/** + * @author Xs + */ +@SPI("zipkin") +public interface RpcTracker { +} diff --git a/dubbo-tracker/pom.xml b/dubbo-tracker/pom.xml new file mode 100644 index 00000000000..019ee0552a2 --- /dev/null +++ b/dubbo-tracker/pom.xml @@ -0,0 +1,18 @@ + + + + dubbo-parent + com.alibaba + 2.8.4 + + 4.0.0 + + dubbo-tracker + pom + + dubbo-tracker-api + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2f1517bd3c9..c9f1cb48084 100644 --- a/pom.xml +++ b/pom.xml @@ -14,371 +14,395 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - pom - ${project.artifactId} - The parent project of dubbo - http://code.alibabatech.com/wiki/display/dubbo - 2011 - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - - - Alibaba - http://www.alibaba.com - - - dubbo-common - dubbo-container - dubbo-remoting - dubbo-rpc - dubbo-filter - dubbo-cluster - dubbo-registry - dubbo-monitor - dubbo-config - dubbo - dubbo-simple - dubbo-admin - dubbo-demo - hessian-lite + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.alibaba + dubbo-parent + 2.8.4 + pom + ${project.artifactId} + The parent project of dubbo + http://code.alibabatech.com/wiki/display/dubbo + 2011 + + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + Alibaba + http://www.alibaba.com + + + + + alimaven + aliyun maven + http://maven.aliyun.com/nexus/content/groups/public/ + + + maven.net.cn + one of the central mirrors in china + http://maven.net.cn/content/groups/public/ + + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public + + + + + dubbo-common + dubbo-container + dubbo-remoting + dubbo-rpc + dubbo-filter + dubbo-cluster + dubbo-registry + dubbo-monitor + dubbo-config + dubbo + dubbo-simple + dubbo-admin + dubbo-demo + hessian-lite + dubbo-tracker - - - - test - - - .project - - - - dubbo-test - - - - hudson - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - - - - - - 3.2.9.RELEASE - 3.20.0-GA - 3.7.0.Final - 1.1.7 - 2.1.4 - 4.2.1 - 3.2.1-fixed-2 - 1.4.1 - 1.1.39 - 3.1 - 0.8 - 3.4.6 - 0.1 - 2.5.0 - 2.1.0 - 1.3.6 - 2.6.1 - 0.8.0 - 1.0.13 - 4.0.7 - 3.1.0 - 6.1.26 - 1.0.0.GA - 4.2.0.Final - 0.4 - 2.0-M5.1 - 3.0 - 2.2 - 3.0.8 + + + + test + + + .project + + + + dubbo-test + + + + hudson + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + + 3.2.9.RELEASE + 3.20.0-GA + 3.7.0.Final + 1.1.7 + 2.1.4 + 4.2.1 + 3.2.1-fixed-2 + 1.4.1 + 1.1.39 + 3.1 + 0.8 + 3.4.6 + 0.1 + 2.5.0 + 2.1.0 + 1.3.6 + 2.6.1 + 0.8.0 + 1.0.13 + 4.0.7 + 3.1.0 + 6.1.26 + 1.0.0.GA + 4.2.0.Final + 0.4 + 2.0-M5.1 + 3.0 + 2.2 + 3.0.8 2.3.3 1.6 8.0.11 - - 1.6.2 - 1.1 - 1.2.16 - 1.0.6 - - 4.10 - 3.0 - 0.999.8 - - - false - true - ${file_encoding} + + 1.6.2 + 1.1 + 1.2.16 + 1.0.6 + + 4.10 + 3.0 + 0.999.8 + + + false + true + ${file_encoding} - - Copyright 1999-2012 Alibaba Group. Licensed under - the Apache License, Version 2.0 (the "License"); you - may not use this file except in compliance with the License. You - may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 Unless required - by applicable law or agreed to in writing, software distributed - under the License is distributed on an "AS IS" - BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - express or implied. See the License for the specific language - governing permissions and limitations under the License. - oss + + Copyright 1999-2012 Alibaba Group. Licensed under + the Apache License, Version 2.0 (the "License"); you + may not use this file except in compliance with the License. You + may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 Unless required + by applicable law or agreed to in writing, software distributed + under the License is distributed on an "AS IS" + BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + express or implied. See the License for the specific language + governing permissions and limitations under the License. + + oss - - 2.3.2 - 1.6 - 1.6 - UTF-8 + + 2.3.2 + 1.6 + 1.6 + UTF-8 - 2.1.1 - 2.3.2 - 2.1.1 - 2.3.1 - 2.7 + 2.1.1 + 2.3.2 + 2.1.1 + 2.3.1 + 2.7 2.17 - - - - - - org.springframework - spring-framework-bom - ${spring.bom.version} - pom - import - - - org.javassist - javassist - ${javassist_version} - - - io.netty - netty - ${netty_version} - - - org.apache.mina - mina-core - ${mina_version} - - - org.glassfish.grizzly - grizzly-core - ${grizzly_version} - - - org.apache.httpcomponents - httpclient - ${httpclient_version} - - - com.alibaba - hessian-lite - ${hessian_lite_version} - - - com.alibaba - fastjson - ${fastjson_version} - - - com.thoughtworks.xstream - xstream - ${xstream_version} - - - org.apache.bsf - bsf-api - ${bsf_version} - - - org.jvnet.sorcerer - sorcerer-javac - ${sorcerer_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - com.github.sgroschupf - zkclient - ${zkclient_version} - - - org.apache.curator - curator-framework - ${curator_version} - - - redis.clients - jedis - ${jedis_version} - - - com.googlecode.xmemcached - xmemcached - ${xmemcached_version} - - - org.apache.cxf - cxf-rt-frontend-simple - ${cxf_version} - - - org.apache.cxf - cxf-rt-transports-http - ${cxf_version} - - - org.apache.thrift - libthrift - ${thrift_version} - - - jfree - jfreechart - ${jfreechart_version} - - - com.caucho - hessian - ${hessian_version} - - - javax.servlet - javax.servlet-api - ${servlet_version} - - - org.mortbay.jetty - jetty - ${jetty_version} - - - javax.validation - validation-api - ${validation_version} - - - org.hibernate - hibernate-validator - ${hibernate_validator_version} - - - javax.cache - cache-api - ${jcache_version} - - - org.apache.tuscany.sca - tuscany-sca-api - ${sca_version} - - - com.google.inject - guice - ${guice_version} - - - com.alibaba.citrus - citrus-webx-all - ${webx_version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson_version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson_version} - - - - org.slf4j - slf4j-api - ${slf4j_version} - - - org.slf4j - slf4j-log4j12 - ${slf4j_version} - - - commons-logging - commons-logging-api - ${jcl_version} - - - log4j - log4j - ${log4j_version} - - - ch.qos.logback - logback-classic - ${logback_version} - - - - junit - junit - ${junit_version} - test - - - org.easymock - easymock - ${easymock_version} - test - - - com.googlecode.jmockit - jmockit - ${jmockit_version} - test - - - org.easymock - easymockclassextension - ${easymock_version} - test - - - cglib - cglib-nodep - ${cglib_version} - - - commons-pool - commons-pool - ${commons_pool_version} - + + + + + + org.springframework + spring-framework-bom + ${spring.bom.version} + pom + import + + + org.javassist + javassist + ${javassist_version} + + + io.netty + netty + ${netty_version} + + + org.apache.mina + mina-core + ${mina_version} + + + org.glassfish.grizzly + grizzly-core + ${grizzly_version} + + + org.apache.httpcomponents + httpclient + ${httpclient_version} + + + com.alibaba + hessian-lite + ${hessian_lite_version} + + + com.alibaba + fastjson + ${fastjson_version} + + + com.thoughtworks.xstream + xstream + ${xstream_version} + + + org.apache.bsf + bsf-api + ${bsf_version} + + + org.jvnet.sorcerer + sorcerer-javac + ${sorcerer_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + com.github.sgroschupf + zkclient + ${zkclient_version} + + + org.apache.curator + curator-framework + ${curator_version} + + + redis.clients + jedis + ${jedis_version} + + + com.googlecode.xmemcached + xmemcached + ${xmemcached_version} + + + org.apache.cxf + cxf-rt-frontend-simple + ${cxf_version} + + + org.apache.cxf + cxf-rt-transports-http + ${cxf_version} + + + org.apache.thrift + libthrift + ${thrift_version} + + + jfree + jfreechart + ${jfreechart_version} + + + com.caucho + hessian + ${hessian_version} + + + javax.servlet + javax.servlet-api + ${servlet_version} + + + org.mortbay.jetty + jetty + ${jetty_version} + + + javax.validation + validation-api + ${validation_version} + + + org.hibernate + hibernate-validator + ${hibernate_validator_version} + + + javax.cache + cache-api + ${jcache_version} + + + org.apache.tuscany.sca + tuscany-sca-api + ${sca_version} + + + com.google.inject + guice + ${guice_version} + + + com.alibaba.citrus + citrus-webx-all + ${webx_version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson_version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson_version} + + + + org.slf4j + slf4j-api + ${slf4j_version} + + + org.slf4j + slf4j-log4j12 + ${slf4j_version} + + + commons-logging + commons-logging-api + ${jcl_version} + + + log4j + log4j + ${log4j_version} + + + ch.qos.logback + logback-classic + ${logback_version} + + + + junit + junit + ${junit_version} + test + + + org.easymock + easymock + ${easymock_version} + test + + + com.googlecode.jmockit + jmockit + ${jmockit_version} + test + + + org.easymock + easymockclassextension + ${easymock_version} + test + + + cglib + cglib-nodep + ${cglib_version} + + + commons-pool + commons-pool + ${commons_pool_version} + org.apache.tomcat.embed tomcat-embed-core @@ -441,287 +465,327 @@ fst 1.55 - - - - - junit - junit - - - org.easymock - easymock - - - org.easymock - easymockclassextension - - - com.googlecode.jmockit - jmockit - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - true - true - - true - true - - - - - - maven-source-plugin - - - attach-sources - package - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-surefire-plugin + + + com.squareup.okhttp3 + okhttp + 3.2.0 + + + + io.zipkin.brave + brave-core + 3.9.0 + + + + io.zipkin.brave + brave-http + 3.9.0 + + + + io.zipkin.brave + brave-web-servlet-filter + 3.9.0 + + + + io.zipkin.brave + brave-okhttp + 3.9.0 + + + + io.zipkin.brave + brave-spancollector-http + 3.9.0 + + + + com.google.auto.value + auto-value + 1.3 + + + + + + + junit + junit + + + org.easymock + easymock + + + org.easymock + easymockclassextension + + + com.googlecode.jmockit + jmockit + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + true + true + + true + true + + + + + + maven-source-plugin + + + attach-sources + package + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-surefire-plugin ${maven-surefire-plugin_version} - - true - once - ${argline} - - - - transporter - ${transporter} - - - serialization - ${serialization} - - - - port - ${port} - - - threadpool - ${threadpool} - - - threads - ${threads} - - - iothreads - ${iothreads} - - - - server - ${server} - - - timeout - ${timeout} - - - length - ${length} - - - connections - ${connections} - - - base - ${base} - - - concurrent - ${concurrent} - - - runs - ${runs} - - - onerror - ${onerror} - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - ${skip_maven_deploy} - - - + + true + once + ${argline} + + + + transporter + ${transporter} + + + serialization + ${serialization} + + + + port + ${port} + + + threadpool + ${threadpool} + + + threads + ${threads} + + + iothreads + ${iothreads} + + + + server + ${server} + + + timeout + ${timeout} + + + length + ${length} + + + connections + ${connections} + + + base + ${base} + + + concurrent + ${concurrent} + + + runs + ${runs} + + + onerror + ${onerror} + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + ${skip_maven_deploy} + + + - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven_jar_plugin_version} - - - org.apache.maven.plugins - maven-war-plugin - ${maven_war_plugin_version} - - - org.apache.maven.plugins - maven-install-plugin - ${maven_install_plugin_version} - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven_deploy_plugin_version} - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven_compiler_plugin_version} - + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven_jar_plugin_version} + + + org.apache.maven.plugins + maven-war-plugin + ${maven_war_plugin_version} + + + org.apache.maven.plugins + maven-install-plugin + ${maven_install_plugin_version} + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven_deploy_plugin_version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven_compiler_plugin_version} + true - ${java_source_version} - ${java_target_version} - ${file_encoding} - - -XX:MaxPermSize=512M - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-dependency-plugin - - - [2.1,) - - - unpack - - - - - - - - - - - - + ${java_source_version} + ${java_target_version} + ${file_encoding} + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-dependency-plugin + + + [2.1,) + + + unpack + + + + + + + + + + + + - + - - jira - http://code.alibabatech.com/jira/browse/DUBBO - - - http://code.alibabatech.com/svn/dubbo/trunk - scm:svn:http://code.alibabatech.com/svn/dubbo/trunk - - - - Dubbo User Mailling List - dubbo-subscribe AT googlegroups DOT com - dubbo-unsubscribe AT googlegroups DOT com - dubbo AT googlegroups DOT com - http://groups.google.com/group/dubbo - - - - - QianXiao(Shawn) - shawn.qianx - shawn.qianx (AT) alibaba-inc.com - - Developer - - +8 - - - LiangFei(William) - william.liangf - william.liangf (AT) alibaba-inc.com - - Developer - - +8 - - - LiDing(Jerry) - ding.lid - ding.lid (AT) alibaba-inc.com - - Developer - - +8 - - - LiuChao(Charles) - chao.liuc - chao.liuc (AT) alibaba-inc.com - - Developer - - +8 - - - LiuHaoMin(Ludvik) - haoming.liuhm - haoming.liuhm (AT) alibaba-inc.com - - Developer - - +8 - - - ChenLei(Tony) - tony.chenl - tony.chenl (AT) alibaba-inc.com - - Developer - - +8 - - - LvGang(Kimi) - gang.lvg - gang.lvg (AT) alibaba-inc.com - - Developer - - +8 - - + + jira + http://code.alibabatech.com/jira/browse/DUBBO + + + http://code.alibabatech.com/svn/dubbo/trunk + scm:svn:http://code.alibabatech.com/svn/dubbo/trunk + + + + Dubbo User Mailling List + dubbo-subscribe AT googlegroups DOT com + dubbo-unsubscribe AT googlegroups DOT com + dubbo AT googlegroups DOT com + http://groups.google.com/group/dubbo + + + + + QianXiao(Shawn) + shawn.qianx + shawn.qianx (AT) alibaba-inc.com + + Developer + + +8 + + + LiangFei(William) + william.liangf + william.liangf (AT) alibaba-inc.com + + Developer + + +8 + + + LiDing(Jerry) + ding.lid + ding.lid (AT) alibaba-inc.com + + Developer + + +8 + + + LiuChao(Charles) + chao.liuc + chao.liuc (AT) alibaba-inc.com + + Developer + + +8 + + + LiuHaoMin(Ludvik) + haoming.liuhm + haoming.liuhm (AT) alibaba-inc.com + + Developer + + +8 + + + ChenLei(Tony) + tony.chenl + tony.chenl (AT) alibaba-inc.com + + Developer + + +8 + + + LvGang(Kimi) + gang.lvg + gang.lvg (AT) alibaba-inc.com + + Developer + + +8 + + From 4b3b12be958c409c19192f0dfc46c64796636e67 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 9 Jan 2017 22:28:58 +0800 Subject: [PATCH 04/69] add rpcTracker and zipkin componets --- .../common/extension/ExtensionLoader.java | 38 +-- .../extension/support/ActivateComparator.java | 2 +- .../alibaba/dubbo/common/utils/NetUtils.java | 213 +++++++------ .../alibaba/dubbo/config/ProtocolConfig.java | 139 +++++---- .../alibaba/dubbo/config/ServiceConfig.java | 186 ++++++----- .../dubbo/config/spring/ServiceBean.java | 95 +++--- .../support/AbstractMonitorFactory.java | 20 +- .../dubbo/monitor/support/MonitorFilter.java | 54 ++-- ...rFactroy.java => DubboMonitorFactory.java} | 128 ++++---- .../com.alibaba.dubbo.monitor.MonitorFactory | 2 +- .../dubbo/registry/dubbo/MockedClient.java | 69 +++-- .../remoting/exchange/ExchangeClient.java | 4 +- .../dubbo/remoting/exchange/Interceptor.java | 19 ++ .../dubbo/remoting/exchange/Response.java | 126 ++++---- .../exchange/support/DefaultFuture.java | 293 +++++++++--------- .../support/header/HeaderExchangeChannel.java | 49 ++- .../support/header/HeaderExchangeClient.java | 136 +++++--- .../support/header/HeaderExchangeServer.java | 6 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 3 +- .../dubbo/rpc/protocol/AbstractExporter.java | 6 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 4 +- .../rpc/protocol/AbstractProxyProtocol.java | 4 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 58 ++-- .../protocol/dubbo/DecodeableRpcResult.java | 26 +- .../rpc/protocol/dubbo/DubboExporter.java | 10 +- .../rpc/protocol/dubbo/DubboInvoker.java | 72 ++--- .../dubbo/LazyConnectExchangeClient.java | 10 +- .../dubbo/ReferenceCountExchangeClient.java | 30 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 5 + .../hessian/OkHttpConnectionFactory.java | 8 +- dubbo-tracker/dubbo-tracker-api/pom.xml | 10 + .../tracker/ClientRequestInterceptor.java | 9 + .../tracker/ClientResponseInterceptor.java | 10 + .../dubbo/tracker/DecodeableRequest.java | 28 ++ .../dubbo/tracker/DecodeableResponse.java | 7 + .../dubbo/tracker/DubboSpanNameProvider.java | 13 + .../alibaba/dubbo/tracker/RpcAttachment.java | 26 ++ .../com/alibaba/dubbo/tracker/RpcTracker.java | 7 +- .../dubbo/tracker/RpcTrackerFactory.java | 16 + .../alibaba/dubbo/tracker/TrackerKeys.java | 10 + .../filter/ClientRpcTrackerFilter.java | 9 + .../filter/ServerRpcTrackerFilter.java | 9 + dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 75 +++++ .../zipkin/BraveClientRequestAdapter.java | 59 ++++ .../zipkin/BraveClientRequestInterceptor.java | 38 +++ .../zipkin/BraveClientResponseAdapter.java | 25 ++ .../BraveClientResponseInterceptor.java | 25 ++ .../dubbo/tracker/zipkin/BraveRpcTracker.java | 37 +++ .../zipkin/BraveRpcTrackerFactory.java | 22 ++ .../LoggingSpanCollectorMetricsHandler.java | 23 ++ .../MappedServerClientAndLocalSpanState.java | 62 ++++ .../tracker/zipkin/SpanCollectorFactory.java | 15 + .../filter/BraveClientRpcTrackerFilter.java | 32 ++ .../filter/BraveServerRpcTrackerFilter.java | 28 ++ .../internal/com.alibaba.dubbo.rpc.Filter | 2 + ...om.alibaba.dubbo.tracker.RpcTrackerFactory | 1 + dubbo-tracker/pom.xml | 1 + dubbo/pom.xml | 74 +++-- 58 files changed, 1585 insertions(+), 903 deletions(-) rename dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/{DubboMonitorFactroy.java => DubboMonitorFactory.java} (94%) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/pom.xml create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java index 89080bf64fc..b3eaf68f2e1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java @@ -740,7 +740,7 @@ private Class createAdaptiveExtensionClass() { } private String createAdaptiveExtensionClassCode() { - StringBuilder codeBuidler = new StringBuilder(); + StringBuilder codeBuilder = new StringBuilder(); Method[] methods = type.getMethods(); boolean hasAdaptiveAnnotation = false; for(Method m : methods) { @@ -753,9 +753,9 @@ private String createAdaptiveExtensionClassCode() { if(! hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); - codeBuidler.append("package " + type.getPackage().getName() + ";"); - codeBuidler.append("\nimport " + ExtensionLoader.class.getName() + ";"); - codeBuidler.append("\npublic class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {"); + codeBuilder.append("package " + type.getPackage().getName() + ";"); + codeBuilder.append("\nimport " + ExtensionLoader.class.getName() + ";"); + codeBuilder.append("\npublic class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {"); for (Method method : methods) { Class rt = method.getReturnType(); @@ -915,34 +915,34 @@ private String createAdaptiveExtensionClassCode() { code.append(");"); } - codeBuidler.append("\npublic " + rt.getCanonicalName() + " " + method.getName() + "("); + codeBuilder.append("\npublic " + rt.getCanonicalName() + " " + method.getName() + "("); for (int i = 0; i < pts.length; i ++) { if (i > 0) { - codeBuidler.append(", "); + codeBuilder.append(", "); } - codeBuidler.append(pts[i].getCanonicalName()); - codeBuidler.append(" "); - codeBuidler.append("arg" + i); + codeBuilder.append(pts[i].getCanonicalName()); + codeBuilder.append(" "); + codeBuilder.append("arg" + i); } - codeBuidler.append(")"); + codeBuilder.append(")"); if (ets.length > 0) { - codeBuidler.append(" throws "); + codeBuilder.append(" throws "); for (int i = 0; i < ets.length; i ++) { if (i > 0) { - codeBuidler.append(", "); + codeBuilder.append(", "); } - codeBuidler.append(pts[i].getCanonicalName()); + codeBuilder.append(pts[i].getCanonicalName()); } } - codeBuidler.append(" {"); - codeBuidler.append(code.toString()); - codeBuidler.append("\n}"); + codeBuilder.append(" {"); + codeBuilder.append(code.toString()); + codeBuilder.append("\n}"); } - codeBuidler.append("\n}"); + codeBuilder.append("\n}"); if (logger.isDebugEnabled()) { - logger.debug(codeBuidler.toString()); + logger.debug(codeBuilder.toString()); } - return codeBuidler.toString(); + return codeBuilder.toString(); } private static ClassLoader findClassLoader() { diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/support/ActivateComparator.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/support/ActivateComparator.java index 16351fbbbec..edb5de16dc1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/support/ActivateComparator.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/support/ActivateComparator.java @@ -22,7 +22,7 @@ import com.alibaba.dubbo.common.extension.SPI; /** - * OrderComparetor + * OrderComparator * * @author william.liangf */ diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java index a037544e5ab..4cadb5648a4 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java @@ -15,29 +15,25 @@ */ package com.alibaba.dubbo.common.utils; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; + import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.NetworkInterface; -import java.net.ServerSocket; -import java.net.UnknownHostException; +import java.net.*; import java.util.Enumeration; import java.util.Map; import java.util.Random; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; - /** - * IP and Port Helper for RPC, - * + * IP and Port Helper for RPC, + * * @author shawn.qianx */ public class NetUtils { - + private static final Logger logger = LoggerFactory.getLogger(NetUtils.class); public static final String LOCALHOST = "127.0.0.1"; @@ -45,11 +41,11 @@ public class NetUtils { public static final String ANYHOST = "0.0.0.0"; private static final int RND_PORT_START = 30000; - + private static final int RND_PORT_RANGE = 10000; - + private static final Random RANDOM = new Random(System.currentTimeMillis()); - + public static int getRandomPort() { return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE); } @@ -66,76 +62,76 @@ public static int getAvailablePort() { if (ss != null) { try { ss.close(); - } catch (IOException e) { + } catch (IOException ignored) { } } } } - + public static int getAvailablePort(int port) { - if (port <= 0) { - return getAvailablePort(); - } - for(int i = port; i < MAX_PORT; i ++) { - ServerSocket ss = null; + if (port <= 0) { + return getAvailablePort(); + } + for (int i = port; i < MAX_PORT; i++) { + ServerSocket ss = null; try { ss = new ServerSocket(i); return i; } catch (IOException e) { - // continue + // continue } finally { if (ss != null) { try { ss.close(); - } catch (IOException e) { + } catch (IOException ignored) { } } } - } - return port; + } + return port; } private static final int MIN_PORT = 0; - + private static final int MAX_PORT = 65535; - - public static boolean isInvalidPort(int port){ + + public static boolean isInvalidPort(int port) { return port > MIN_PORT || port <= MAX_PORT; } private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$"); - public static boolean isValidAddress(String address){ - return ADDRESS_PATTERN.matcher(address).matches(); + public static boolean isValidAddress(String address) { + return ADDRESS_PATTERN.matcher(address).matches(); } private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); - + public static boolean isLocalHost(String host) { - return host != null - && (LOCAL_IP_PATTERN.matcher(host).matches() - || host.equalsIgnoreCase("localhost")); + return host != null + && (LOCAL_IP_PATTERN.matcher(host).matches() + || host.equalsIgnoreCase("localhost")); } public static boolean isAnyHost(String host) { return "0.0.0.0".equals(host); } - + public static boolean isInvalidLocalHost(String host) { - return host == null - || host.length() == 0 - || host.equalsIgnoreCase("localhost") - || host.equals("0.0.0.0") - || (LOCAL_IP_PATTERN.matcher(host).matches()); + return host == null + || host.length() == 0 + || host.equalsIgnoreCase("localhost") + || host.equals("0.0.0.0") + || (LOCAL_IP_PATTERN.matcher(host).matches()); } - + public static boolean isValidLocalHost(String host) { - return ! isInvalidLocalHost(host); + return !isInvalidLocalHost(host); } public static InetSocketAddress getLocalSocketAddress(String host, int port) { - return isInvalidLocalHost(host) ? - new InetSocketAddress(port) : new InetSocketAddress(host, port); + return isInvalidLocalHost(host) ? + new InetSocketAddress(port) : new InetSocketAddress(host, port); } private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); @@ -144,17 +140,17 @@ private static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) return false; String name = address.getHostAddress(); - return (name != null - && ! ANYHOST.equals(name) - && ! LOCALHOST.equals(name) + return (name != null + && !ANYHOST.equals(name) + && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches()); } - - public static String getLocalHost(){ + + public static String getLocalHost() { InetAddress address = getLocalAddress(); return address == null ? LOCALHOST : address.getHostAddress(); } - + public static String filterLocalHost(String host) { if (host == null || host.length() == 0) { return host; @@ -171,17 +167,17 @@ public static String filterLocalHost(String host) { } } else { if (NetUtils.isInvalidLocalHost(host)) { - return NetUtils.getLocalHost(); - } + return NetUtils.getLocalHost(); + } } - return host; + return host; } - + private static volatile InetAddress LOCAL_ADDRESS = null; /** * 遍历本地网卡,返回第一个合理的IP。 - * + * * @return 本地网卡IP */ public static InetAddress getLocalAddress() { @@ -191,12 +187,12 @@ public static InetAddress getLocalAddress() { LOCAL_ADDRESS = localAddress; return localAddress; } - + public static String getLogHost() { InetAddress address = LOCAL_ADDRESS; return address == null ? LOCALHOST : address.getHostAddress(); } - + private static InetAddress getLocalAddress0() { InetAddress localAddress = null; try { @@ -214,16 +210,14 @@ private static InetAddress getLocalAddress0() { try { NetworkInterface network = interfaces.nextElement(); Enumeration addresses = network.getInetAddresses(); - if (addresses != null) { - while (addresses.hasMoreElements()) { - try { - InetAddress address = addresses.nextElement(); - if (isValidAddress(address)) { - return address; - } - } catch (Throwable e) { - logger.warn("Failed to retriving ip address, " + e.getMessage(), e); + while (addresses.hasMoreElements()) { + try { + InetAddress address = addresses.nextElement(); + if (isValidAddress(address)) { + return address; } + } catch (Throwable e) { + logger.warn("Failed to retriving ip address, " + e.getMessage(), e); } } } catch (Throwable e) { @@ -237,39 +231,39 @@ private static InetAddress getLocalAddress0() { logger.error("Could not get local host ip address, will use 127.0.0.1 instead."); return localAddress; } - + private static final Map hostNameCache = new LRUCache(1000); public static String getHostName(String address) { - try { - int i = address.indexOf(':'); - if (i > -1) { - address = address.substring(0, i); - } - String hostname = hostNameCache.get(address); - if (hostname != null && hostname.length() > 0) { - return hostname; - } - InetAddress inetAddress = InetAddress.getByName(address); - if (inetAddress != null) { - hostname = inetAddress.getHostName(); - hostNameCache.put(address, hostname); - return hostname; - } - } catch (Throwable e) { - // ignore - } - return address; + try { + int i = address.indexOf(':'); + if (i > -1) { + address = address.substring(0, i); + } + String hostname = hostNameCache.get(address); + if (hostname != null && hostname.length() > 0) { + return hostname; + } + InetAddress inetAddress = InetAddress.getByName(address); + if (inetAddress != null) { + hostname = inetAddress.getHostName(); + hostNameCache.put(address, hostname); + return hostname; + } + } catch (Throwable e) { + // ignore + } + return address; } - + /** * @param hostName - * @return ip address or hostName if UnknownHostException + * @return ip address or hostName if UnknownHostException */ public static String getIpByHost(String hostName) { - try{ + try { return InetAddress.getByName(hostName).getHostAddress(); - }catch (UnknownHostException e) { + } catch (UnknownHostException e) { return hostName; } } @@ -277,7 +271,7 @@ public static String getIpByHost(String hostName) { public static String toAddressString(InetSocketAddress address) { return address.getAddress().getHostAddress() + ":" + address.getPort(); } - + public static InetSocketAddress toAddress(String address) { int i = address.indexOf(':'); String host; @@ -291,15 +285,30 @@ public static InetSocketAddress toAddress(String address) { } return new InetSocketAddress(host, port); } - + + public static int toAddressInt(String address) { + if (StringUtils.isEmpty(address)) { + throw new IllegalArgumentException("address must not be null!"); + } + int reVal = 0; + String[] strs = address.split("\\."); + if (strs.length != 4) { + throw new IllegalArgumentException("address is illegal: " + address); + } + for (int i = 0; i < strs.length; i++) { + reVal |= Integer.valueOf(strs[i]) << ((3 - i) * 8); + } + return reVal; + } + public static String toURL(String protocol, String host, int port, String path) { - StringBuilder sb = new StringBuilder(); - sb.append(protocol).append("://"); - sb.append(host).append(':').append(port); - if( path.charAt(0) != '/' ) - sb.append('/'); - sb.append(path); - return sb.toString(); - } - + StringBuilder sb = new StringBuilder(); + sb.append(protocol).append("://"); + sb.append(host).append(':').append(port); + if (path.charAt(0) != '/') + sb.append('/'); + sb.append(path); + return sb.toString(); + } + } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index 8e592bd9739..f1bd9473246 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -15,108 +15,108 @@ */ package com.alibaba.dubbo.config; -import java.util.Map; - import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.registry.support.AbstractRegistryFactory; -import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.rpc.Protocol; +import java.util.Map; + /** * ProtocolConfig - * + * * @author william.liangf * @export */ public class ProtocolConfig extends AbstractConfig { - private static final long serialVersionUID = 6913423882496634749L; + private static final long serialVersionUID = 6913423882496634749L; // 服务协议 - private String name; + private String name; // 服务IP地址(多网卡时使用) - private String host; + private String host; // 服务端口 - private Integer port; + private Integer port; // 上下文路径 - private String contextpath; - + private String contextpath; + // 线程池类型 - private String threadpool; - + private String threadpool; + // 线程池大小(固定大小) - private Integer threads; - + private Integer threads; + // IO线程池大小(固定大小) - private Integer iothreads; - + private Integer iothreads; + // 线程池队列大小 - private Integer queues; - + private Integer queues; + // 最大接收连接数 - private Integer accepts; - + private Integer accepts; + // 协议编码 - private String codec; - + private String codec; + // 序列化方式 - private String serialization; - + private String serialization; + // 字符集 - private String charset; - + private String charset; + // 最大请求数据长度 - private Integer payload; - + private Integer payload; + // 缓存区大小 - private Integer buffer; - + private Integer buffer; + // 心跳间隔 - private Integer heartbeat; + private Integer heartbeat; // 访问日志 - private String accesslog; - + private String accesslog; + // 网络传输方式 - private String transporter; - + private String transporter; + // 信息交换方式 - private String exchanger; - + private String exchanger; + // 信息线程模型派发方式 - private String dispatcher; + private String dispatcher; // 对称网络组网方式 - private String networker; - + private String networker; + // 服务器端实现 - private String server; - + private String server; + // 客户端实现 - private String client; - + private String client; + // 支持的telnet命令,多个命令用逗号分隔 - private String telnet; - + private String telnet; + // 命令行提示符 - private String prompt; + private String prompt; // status检查 - private String status; - + private String status; + // 是否注册 - private Boolean register; + private Boolean register; // 是否长连接 // TODO add this to provider config @@ -127,16 +127,16 @@ public class ProtocolConfig extends AbstractConfig { private String optimizer; private String extension; - + // 参数 private Map parameters; // 是否为缺省 private Boolean isDefault; - + public ProtocolConfig() { } - + public ProtocolConfig(String name) { setName(name); } @@ -145,7 +145,7 @@ public ProtocolConfig(String name, int port) { setName(name); setPort(port); } - + @Parameter(excluded = true) public String getName() { return name; @@ -227,15 +227,15 @@ public void setIothreads(Integer iothreads) { public Integer getQueues() { return queues; } - + public void setQueues(Integer queues) { this.queues = queues; } - + public Integer getAccepts() { return accepts; } - + public void setAccepts(Integer accepts) { this.accepts = accepts; } @@ -254,7 +254,7 @@ public void setCodec(String codec) { public String getSerialization() { return serialization; } - + public void setSerialization(String serialization) { if ("dubbo".equals(name)) { checkMultiExtension(Serialization.class, "serialization", serialization); @@ -315,11 +315,11 @@ public void setClient(String client) { } this.client = client; } - + public String getAccesslog() { return accesslog; } - + public void setAccesslog(String accesslog) { this.accesslog = accesslog; } @@ -327,7 +327,7 @@ public void setAccesslog(String accesslog) { public String getTelnet() { return telnet; } - + public void setTelnet(String telnet) { checkMultiExtension(TelnetHandler.class, "telnet", telnet); this.telnet = telnet; @@ -345,7 +345,7 @@ public void setPrompt(String prompt) { public String getStatus() { return status; } - + public void setStatus(String status) { checkMultiExtension(StatusChecker.class, "status", status); this.status = status; @@ -354,24 +354,24 @@ public void setStatus(String status) { public Boolean isRegister() { return register; } - + public void setRegister(Boolean register) { this.register = register; } - + public String getTransporter() { return transporter; } - + public void setTransporter(String transporter) { checkExtension(Transporter.class, "transporter", transporter); this.transporter = transporter; } - + public String getExchanger() { return exchanger; } - + public void setExchanger(String exchanger) { checkExtension(Exchanger.class, "exchanger", exchanger); this.exchanger = exchanger; @@ -379,6 +379,7 @@ public void setExchanger(String exchanger) { /** * 单词拼写错误,请使用{@link #getDispatcher()} + * * @deprecated {@link #getDispatcher()} */ @Deprecated @@ -389,6 +390,7 @@ public String getDispather() { /** * 单词拼写错误,请使用{@link #setDispatcher(String) + * * @deprecated {@link #setDispatcher(String)} */ @Deprecated @@ -455,7 +457,8 @@ public void setExtension(String extension) { public void destory() { if (name != null) { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).destroy();; + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).destroy(); + ; } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index 76a393a5ac4..bc143fdeff2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -15,20 +15,6 @@ */ package com.alibaba.dubbo.config; -import java.lang.reflect.Method; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.UUID; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -40,55 +26,55 @@ import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.dubbo.config.support.Parameter; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.ProxyFactory; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory; -import com.alibaba.dubbo.rpc.ServiceClassHolder; import com.alibaba.dubbo.rpc.service.GenericService; import com.alibaba.dubbo.rpc.support.ProtocolUtils; +import java.lang.reflect.Method; +import java.net.*; +import java.util.*; + /** * ServiceConfig - * + * * @author william.liangf * @export */ public class ServiceConfig extends AbstractServiceConfig { - private static final long serialVersionUID = 3033787999037024738L; + private static final long serialVersionUID = 3033787999037024738L; private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - + private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private static final Map RANDOM_PORT_MAP = new HashMap(); // 接口类型 - private String interfaceName; + private String interfaceName; - private Class interfaceClass; + private Class interfaceClass; // 接口实现类引用 - private T ref; + private T ref; // 服务名称 - private String path; + private String path; // 方法配置 - private List methods; + private List methods; private ProviderConfig provider; private final List urls = new ArrayList(); - + private final List> exporters = new ArrayList>(); private transient volatile boolean exported; - private transient volatile boolean unexported; - + private transient volatile boolean unexported; + private volatile String generic; public ServiceConfig() { @@ -105,16 +91,16 @@ public URL toUrl() { public List toUrls() { return urls; } - + @Parameter(excluded = true) public boolean isExported() { - return exported; - } + return exported; + } @Parameter(excluded = true) - public boolean isUnexported() { - return unexported; - } + public boolean isUnexported() { + return unexported; + } public synchronized void export() { if (provider != null) { @@ -125,7 +111,7 @@ public synchronized void export() { delay = provider.getDelay(); } } - if (export != null && ! export.booleanValue()) { + if (export != null && !export) { return; } if (delay != null && delay > 0) { @@ -133,7 +119,7 @@ public synchronized void export() { public void run() { try { Thread.sleep(delay); - } catch (Throwable e) { + } catch (Throwable ignored) { } doExport(); } @@ -145,7 +131,7 @@ public void run() { doExport(); } } - + protected synchronized void doExport() { if (unexported) { throw new IllegalStateException("Already unexported!"); @@ -207,9 +193,9 @@ protected synchronized void doExport() { checkRef(); generic = Boolean.FALSE.toString(); } - if(local !=null){ - if(local=="true"){ - local=interfaceName+"Local"; + if (local != null) { + if (local.equals("true")) { + local = interfaceName + "Local"; } Class localClass; try { @@ -217,13 +203,13 @@ protected synchronized void doExport() { } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } - if(!interfaceClass.isAssignableFrom(localClass)){ + if (!interfaceClass.isAssignableFrom(localClass)) { throw new IllegalStateException("The local implemention class " + localClass.getName() + " not implement interface " + interfaceName); } } - if(stub !=null){ - if(stub=="true"){ - stub=interfaceName+"Stub"; + if (stub != null) { + if (stub.equals("true")) { + stub = interfaceName + "Stub"; } Class stubClass; try { @@ -231,7 +217,7 @@ protected synchronized void doExport() { } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } - if(!interfaceClass.isAssignableFrom(stubClass)){ + if (!interfaceClass.isAssignableFrom(stubClass)) { throw new IllegalStateException("The stub implemention class " + stubClass.getName() + " not implement interface " + interfaceName); } } @@ -251,7 +237,7 @@ private void checkRef() { if (ref == null) { throw new IllegalStateException("ref not allow null!"); } - if (! interfaceClass.isInstance(ref)) { + if (!interfaceClass.isInstance(ref)) { throw new IllegalStateException("The class " + ref.getClass().getName() + " unimplemented interface " + interfaceClass + "!"); @@ -259,26 +245,26 @@ private void checkRef() { } public synchronized void unexport() { - if (! exported) { + if (!exported) { return; } if (unexported) { return; } - if (exporters != null && exporters.size() > 0) { - for (Exporter exporter : exporters) { - try { + if (exporters != null && exporters.size() > 0) { + for (Exporter exporter : exporters) { + try { exporter.unexport(); } catch (Throwable t) { logger.warn("unexpected err when unexport" + exporter, t); } - } - exporters.clear(); - } + } + exporters.clear(); + } unexported = true; } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + + @SuppressWarnings({"unchecked", "rawtypes"}) private void doExportUrls() { List registryURLs = loadRegistries(true); for (ProtocolConfig protocolConfig : protocols) { @@ -317,7 +303,8 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } finally { try { socket.close(); - } catch (Throwable e) {} + } catch (Throwable ignored) { + } } } catch (Exception e) { logger.warn(e.getMessage(), e); @@ -376,30 +363,30 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (arguments != null && arguments.size() > 0) { for (ArgumentConfig argument : arguments) { //类型自动转换. - if(argument.getType() != null && argument.getType().length() >0){ + if (argument.getType() != null && argument.getType().length() > 0) { Method[] methods = interfaceClass.getMethods(); //遍历所有方法 - if(methods != null && methods.length > 0){ + if (methods != null && methods.length > 0) { for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); //匹配方法名称,获取方法签名. - if(methodName.equals(method.getName())){ + if (methodName.equals(method.getName())) { Class[] argtypes = methods[i].getParameterTypes(); //一个方法中单个callback - if (argument.getIndex() != -1 ){ - if (argtypes[argument.getIndex()].getName().equals(argument.getType())){ + if (argument.getIndex() != -1) { + if (argtypes[argument.getIndex()].getName().equals(argument.getType())) { appendParameters(map, argument, method.getName() + "." + argument.getIndex()); - }else { - throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); + } else { + throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :" + argument.getIndex() + ", type:" + argument.getType()); } } else { //一个方法中多个callback - for (int j = 0 ;j argclazz = argtypes[j]; - if (argclazz.getName().equals(argument.getType())){ + if (argclazz.getName().equals(argument.getType())) { appendParameters(map, argument, method.getName() + "." + j); - if (argument.getIndex() != -1 && argument.getIndex() != j){ - throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); + if (argument.getIndex() != -1 && argument.getIndex() != j) { + throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :" + argument.getIndex() + ", type:" + argument.getType()); } } } @@ -407,9 +394,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } } } - }else if(argument.getIndex() != -1){ + } else if (argument.getIndex() != -1) { appendParameters(map, argument, method.getName() + "." + argument.getIndex()); - }else { + } else { throw new IllegalArgumentException("argument config must set index or type attribute.eg: or "); } @@ -428,15 +415,14 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); - if(methods.length == 0) { + if (methods.length == 0) { logger.warn("NO method found in service interface " + interfaceClass.getName()); map.put("methods", Constants.ANY_VALUE); - } - else { + } else { map.put("methods", StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); } } - if (! ConfigUtils.isEmpty(token)) { + if (!ConfigUtils.isEmpty(token)) { if (ConfigUtils.isDefault(token)) { map.put("token", UUID.randomUUID().toString()); } else { @@ -462,14 +448,14 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r String scope = url.getParameter(Constants.SCOPE_KEY); //配置为none不暴露 - if (! Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) { + if (!Constants.SCOPE_NONE.equalsIgnoreCase(scope)) { //配置不是remote的情况下做本地暴露 (配置为remote,则表示只暴露远程服务) - if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) { + if (!Constants.SCOPE_REMOTE.equalsIgnoreCase(scope)) { exportLocal(url); } //如果配置不是local则暴露为远程服务.(配置为local,则表示只暴露远程服务) - if (! Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope) ){ + if (!Constants.SCOPE_LOCAL.equalsIgnoreCase(scope)) { if (logger.isInfoEnabled()) { logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); } @@ -501,7 +487,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) private void exportLocal(URL url) { if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { URL local = URL.valueOf(url.toFullString()) @@ -515,7 +501,7 @@ private void exportLocal(URL url) { Exporter exporter = protocol.export( proxyFactory.getInvoker(ref, (Class) interfaceClass, local)); exporters.add(exporter); - logger.info("Export dubbo service " + interfaceClass.getName() +" to local registry"); + logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry"); } } @@ -535,7 +521,7 @@ private void checkProtocol() { && provider != null) { setProtocols(provider.getProtocols()); } - // 兼容旧版本 + // 兼容旧版本 if (protocols == null || protocols.size() == 0) { setProtocol(new ProtocolConfig()); } @@ -557,7 +543,7 @@ public Class getInterfaceClass() { try { if (interfaceName != null && interfaceName.length() > 0) { this.interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() - .getContextClassLoader()); + .getContextClassLoader()); } } catch (ClassNotFoundException t) { throw new IllegalStateException(t.getMessage(), t); @@ -566,9 +552,9 @@ public Class getInterfaceClass() { } /** - * @deprecated - * @see #setInterface(Class) * @param interfaceClass + * @see #setInterface(Class) + * @deprecated */ public void setInterfaceClass(Class interfaceClass) { setInterface(interfaceClass); @@ -584,9 +570,9 @@ public void setInterface(String interfaceName) { id = interfaceName; } } - + public void setInterface(Class interfaceClass) { - if (interfaceClass != null && ! interfaceClass.isInterface()) { + if (interfaceClass != null && !interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } this.interfaceClass = interfaceClass; @@ -611,21 +597,23 @@ public void setPath(String path) { this.path = path; } - public List getMethods() { - return methods; - } + public List getMethods() { + return methods; + } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void setMethods(List methods) { - this.methods = (List) methods; - } + this.methods = (List) methods; + } public ProviderConfig getProvider() { return provider; } public void setGeneric(String generic) { - if (StringUtils.isEmpty(generic)) { return; } + if (StringUtils.isEmpty(generic)) { + return; + } if (ProtocolUtils.isGeneric(generic)) { this.generic = generic; } else { @@ -640,11 +628,11 @@ public String getGeneric() { public void setProvider(ProviderConfig provider) { this.provider = provider; } - - public List getExportedUrls(){ + + public List getExportedUrls() { return urls; } - + // ======== Deprecated ======== /** @@ -674,7 +662,7 @@ private static final List convertProviderToProtocol(List convertProtocolToProvider(List protocols) { if (protocols == null || protocols.size() == 0) { @@ -686,7 +674,7 @@ private static final List convertProtocolToProvider(List extends ServiceConfig implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware { - private static final long serialVersionUID = 213195494150089726L; + private static final long serialVersionUID = 213195494150089726L; private static transient ApplicationContext SPRING_CONTEXT; - - private transient ApplicationContext applicationContext; + + private transient ApplicationContext applicationContext; private transient String beanName; private transient boolean supportedApplicationListener; - - public ServiceBean() { + + public ServiceBean() { super(); } @@ -69,33 +62,33 @@ public ServiceBean(Service service) { } public static ApplicationContext getSpringContext() { - return SPRING_CONTEXT; - } + return SPRING_CONTEXT; + } - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - SpringExtensionFactory.addApplicationContext(applicationContext); - if (applicationContext != null) { - SPRING_CONTEXT = applicationContext; - try { - Method method = applicationContext.getClass().getMethod("addApplicationListener", ApplicationListener.class); // 兼容Spring2.0.1 - method.invoke(applicationContext, this); - supportedApplicationListener = true; - } catch (Throwable t) { + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + SpringExtensionFactory.addApplicationContext(applicationContext); + if (applicationContext != null) { + SPRING_CONTEXT = applicationContext; + try { + Method method = applicationContext.getClass().getMethod("addApplicationListener", ApplicationListener.class); // 兼容Spring2.0.1 + method.invoke(applicationContext, this); + supportedApplicationListener = true; + } catch (Throwable t) { if (applicationContext instanceof AbstractApplicationContext) { - try { - Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", ApplicationListener.class); // 兼容Spring2.0.1 - if (! method.isAccessible()) { + try { + Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", ApplicationListener.class); // 兼容Spring2.0.1 + if (!method.isAccessible()) { method.setAccessible(true); } - method.invoke(applicationContext, this); + method.invoke(applicationContext, this); supportedApplicationListener = true; - } catch (Throwable ignored) { - } - } - } - } - } + } catch (Throwable ignored) { + } + } + } + } + } public void setBeanName(String name) { this.beanName = name; @@ -103,7 +96,7 @@ public void setBeanName(String name) { public void onApplicationEvent(ApplicationEvent event) { if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) { - if (isDelay() && ! isExported() && ! isUnexported()) { + if (isDelay() && !isExported() && !isUnexported()) { if (logger.isInfoEnabled()) { logger.info("The service ready on spring started. service: " + getInterface()); } @@ -111,7 +104,7 @@ public void onApplicationEvent(ApplicationEvent event) { } } } - + private boolean isDelay() { Integer delay = getDelay(); ProviderConfig provider = getProvider(); @@ -121,12 +114,12 @@ private boolean isDelay() { return supportedApplicationListener && (delay == null || delay == -1); } - @SuppressWarnings({ "unchecked", "deprecation" }) - public void afterPropertiesSet() throws Exception { + @SuppressWarnings({"unchecked", "deprecation"}) + public void afterPropertiesSet() throws Exception { if (getProvider() == null) { - Map providerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false); + Map providerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false); if (providerConfigMap != null && providerConfigMap.size() > 0) { - Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); + Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); if ((protocolConfigMap == null || protocolConfigMap.size() == 0) && providerConfigMap.size() > 1) { // 兼容旧版本 List providerConfigs = new ArrayList(); @@ -227,7 +220,7 @@ public void afterPropertiesSet() throws Exception { } if ((getProtocols() == null || getProtocols().size() == 0) && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().size() == 0)) { - Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); + Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); if (protocolConfigMap != null && protocolConfigMap.size() > 0) { List protocolConfigs = new ArrayList(); for (ProtocolConfig config : protocolConfigMap.values()) { @@ -241,13 +234,13 @@ public void afterPropertiesSet() throws Exception { } } if (getPath() == null || getPath().length() == 0) { - if (beanName != null && beanName.length() > 0 + if (beanName != null && beanName.length() > 0 && getInterface() != null && getInterface().length() > 0 && beanName.startsWith(getInterface())) { setPath(beanName); } } - if (! isDelay()) { + if (!isDelay()) { export(); } } diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/AbstractMonitorFactory.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/AbstractMonitorFactory.java index 3aa81d27b2e..8ded0696f54 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/AbstractMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/AbstractMonitorFactory.java @@ -15,28 +15,28 @@ */ package com.alibaba.dubbo.monitor.support; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.ReentrantLock; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.monitor.Monitor; import com.alibaba.dubbo.monitor.MonitorFactory; import com.alibaba.dubbo.monitor.MonitorService; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; + /** * AbstractMonitorFactroy. (SPI, Singleton, ThreadSafe) - * + * * @author william.liangf */ public abstract class AbstractMonitorFactory implements MonitorFactory { // 注册中心获取过程锁 private static final ReentrantLock LOCK = new ReentrantLock(); - + // 注册中心集合 Map private static final Map MONITORS = new ConcurrentHashMap(); @@ -45,8 +45,8 @@ public static Collection getMonitors() { } public Monitor getMonitor(URL url) { - url = url.setPath(MonitorService.class.getName()).addParameter(Constants.INTERFACE_KEY, MonitorService.class.getName()); - String key = url.toServiceString(); + url = url.setPath(MonitorService.class.getName()).addParameter(Constants.INTERFACE_KEY, MonitorService.class.getName()); + String key = url.toServiceString(); LOCK.lock(); try { Monitor monitor = MONITORS.get(key); diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/MonitorFilter.java index 14f2d943196..9cd2110fba9 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/com/alibaba/dubbo/monitor/support/MonitorFilter.java @@ -15,10 +15,6 @@ */ package com.alibaba.dubbo.monitor.support; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Activate; @@ -28,33 +24,31 @@ import com.alibaba.dubbo.monitor.Monitor; import com.alibaba.dubbo.monitor.MonitorFactory; import com.alibaba.dubbo.monitor.MonitorService; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.support.RpcUtils; - + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + /** * MonitorFilter. (SPI, Singleton, ThreadSafe) - * + * * @author william.liangf */ @Activate(group = {Constants.PROVIDER, Constants.CONSUMER}) public class MonitorFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(MonitorFilter.class); - + private final ConcurrentMap concurrents = new ConcurrentHashMap(); - + private MonitorFactory monitorFactory; - + public void setMonitorFactory(MonitorFactory monitorFactory) { this.monitorFactory = monitorFactory; } - + // 调用过程拦截 public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) { @@ -75,7 +69,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept return invoker.invoke(invocation); } } - + // 信息采集 private void collect(Invoker invoker, Invocation invocation, Result result, RpcContext context, long start, boolean error) { try { @@ -110,22 +104,22 @@ private void collect(Invoker invoker, Invocation invocation, Result result, R output = result.getAttachment(Constants.OUTPUT_KEY); } monitor.collect(new URL(Constants.COUNT_PROTOCOL, - NetUtils.getLocalHost(), localPort, - service + "/" + method, - MonitorService.APPLICATION, application, - MonitorService.INTERFACE, service, - MonitorService.METHOD, method, - remoteKey, remoteValue, - error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1", - MonitorService.ELAPSED, String.valueOf(elapsed), - MonitorService.CONCURRENT, String.valueOf(concurrent), - Constants.INPUT_KEY, input, - Constants.OUTPUT_KEY, output)); + NetUtils.getLocalHost(), localPort, + service + "/" + method, + MonitorService.APPLICATION, application, + MonitorService.INTERFACE, service, + MonitorService.METHOD, method, + remoteKey, remoteValue, + error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1", + MonitorService.ELAPSED, String.valueOf(elapsed), + MonitorService.CONCURRENT, String.valueOf(concurrent), + Constants.INPUT_KEY, input, + Constants.OUTPUT_KEY, output)); } catch (Throwable t) { logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t); } } - + // 获取并发计数器 private AtomicInteger getConcurrent(Invoker invoker, Invocation invocation) { String key = invoker.getInterface().getName() + "." + invocation.getMethodName(); diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactroy.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactory.java similarity index 94% rename from dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactroy.java rename to dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactory.java index 97558c27122..13dd7bc152b 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactroy.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/com/alibaba/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -1,65 +1,65 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.monitor.dubbo; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.monitor.Monitor; -import com.alibaba.dubbo.monitor.MonitorService; -import com.alibaba.dubbo.monitor.support.AbstractMonitorFactory; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.ProxyFactory; - -/** - * DefaultMonitorFactroy - * - * @author william.liangf - */ -public class DubboMonitorFactroy extends AbstractMonitorFactory { - - private Protocol protocol; - - private ProxyFactory proxyFactory; - - public void setProtocol(Protocol protocol) { - this.protocol = protocol; - } - - public void setProxyFactory(ProxyFactory proxyFactory) { - this.proxyFactory = proxyFactory; - } - - @Override - protected Monitor createMonitor(URL url) { - url = url.setProtocol(url.getParameter(Constants.PROTOCOL_KEY, "dubbo")); - if (url.getPath() == null || url.getPath().length() == 0) { - url = url.setPath(MonitorService.class.getName()); - } - String filter = url.getParameter(Constants.REFERENCE_FILTER_KEY); - if (filter == null || filter.length() == 0) { - filter = ""; - } else { - filter = filter + ","; - } - url = url.addParameters(Constants.CLUSTER_KEY, "failsafe", Constants.CHECK_KEY, String.valueOf(false), - Constants.REFERENCE_FILTER_KEY, filter + "-monitor"); - Invoker monitorInvoker = protocol.refer(MonitorService.class, url); - MonitorService monitorService = proxyFactory.getProxy(monitorInvoker); - return new DubboMonitor(monitorInvoker, monitorService); - } - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.monitor.dubbo; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.monitor.Monitor; +import com.alibaba.dubbo.monitor.MonitorService; +import com.alibaba.dubbo.monitor.support.AbstractMonitorFactory; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Protocol; +import com.alibaba.dubbo.rpc.ProxyFactory; + +/** + * DefaultMonitorFactroy + * + * @author william.liangf + */ +public class DubboMonitorFactory extends AbstractMonitorFactory { + + private Protocol protocol; + + private ProxyFactory proxyFactory; + + public void setProtocol(Protocol protocol) { + this.protocol = protocol; + } + + public void setProxyFactory(ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + } + + @Override + protected Monitor createMonitor(URL url) { + url = url.setProtocol(url.getParameter(Constants.PROTOCOL_KEY, "dubbo")); + if (url.getPath() == null || url.getPath().length() == 0) { + url = url.setPath(MonitorService.class.getName()); + } + String filter = url.getParameter(Constants.REFERENCE_FILTER_KEY); + if (filter == null || filter.length() == 0) { + filter = ""; + } else { + filter = filter + ","; + } + url = url.addParameters(Constants.CLUSTER_KEY, "failsafe", Constants.CHECK_KEY, String.valueOf(false), + Constants.REFERENCE_FILTER_KEY, filter + "-monitor"); + Invoker monitorInvoker = protocol.refer(MonitorService.class, url); + MonitorService monitorService = proxyFactory.getProxy(monitorInvoker); + return new DubboMonitor(monitorInvoker, monitorService); + } + } \ No newline at end of file diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory b/dubbo-monitor/dubbo-monitor-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory index 25ae258923a..3f759a1f5b2 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory +++ b/dubbo-monitor/dubbo-monitor-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory @@ -1 +1 @@ -dubbo=com.alibaba.dubbo.monitor.dubbo.DubboMonitorFactroy \ No newline at end of file +dubbo=com.alibaba.dubbo.monitor.dubbo.DubboMonitorFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java index 0d677d8cc72..562348179f0 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java @@ -1,33 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.registry.dubbo; -import java.net.InetSocketAddress; -import java.util.Map; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.remoting.exchange.support.Replier; +import java.net.InetSocketAddress; +import java.util.Map; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.exchange.support.Replier; /** * MockedClient @@ -149,7 +146,7 @@ public int getTimeout() { return 0; } - public void close(int timeout) { + public void close(int timeout) { close(); } @@ -255,10 +252,14 @@ public void send(Object message, boolean sent) throws RemotingException { } public void reset(URL url) { - } - - @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters) { } - + + @Deprecated + public void reset(com.alibaba.dubbo.common.Parameters parameters) { + } + + @Override + public void addInterceptor(Interceptor interceptor) { + + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java index 6e0d61c7d46..ffb0decc242 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java @@ -19,9 +19,11 @@ /** * ExchangeClient. (API/SPI, Prototype, ThreadSafe) - * + * * @author william.liangf */ public interface ExchangeClient extends Client, ExchangeChannel { + void addInterceptor(Interceptor interceptor); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java new file mode 100644 index 00000000000..6704c5c44ca --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.remoting.exchange; + +import com.alibaba.dubbo.remoting.RemotingException; + +/** + * @author Xs + */ +public interface Interceptor { + + ResponseFuture intercept(Chain chain); + + interface Chain { + + Object request(); + + ResponseFuture proceed(Object request, int timeout) throws RemotingException; + + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java index 0ac70708bac..4d09c46ea56 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java @@ -1,56 +1,56 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.exchange; /** * Response - * + * * @author qian.lei * @author william.liangf */ -public class Response { - - public static final String HEARTBEAT_EVENT = null; - +public class Response { + + public static final String HEARTBEAT_EVENT = null; + public static final String READONLY_EVENT = "R"; /** * ok. */ - public static final byte OK = 20; + public static final byte OK = 20; /** - * clien side timeout. + * client side timeout. */ - public static final byte CLIENT_TIMEOUT = 30; + public static final byte CLIENT_TIMEOUT = 30; /** * server side timeout. */ - public static final byte SERVER_TIMEOUT = 31; + public static final byte SERVER_TIMEOUT = 31; /** * request format error. */ - public static final byte BAD_REQUEST = 40; - - /** - * response format error. - */ - public static final byte BAD_RESPONSE = 50; + public static final byte BAD_REQUEST = 40; + + /** + * response format error. + */ + public static final byte BAD_RESPONSE = 50; /** * service not found. @@ -60,38 +60,38 @@ public class Response { /** * service error. */ - public static final byte SERVICE_ERROR = 70; + public static final byte SERVICE_ERROR = 70; /** * internal server error. */ - public static final byte SERVER_ERROR = 80; + public static final byte SERVER_ERROR = 80; /** * internal server error. */ - public static final byte CLIENT_ERROR = 90; + public static final byte CLIENT_ERROR = 90; - private long mId = 0; + private long mId = 0; - private String mVersion; + private String mVersion; - private byte mStatus = OK; + private byte mStatus = OK; - private boolean mEvent = false; + private boolean mEvent = false; - private String mErrorMsg; + private String mErrorMsg; - private Object mResult; + private Object mResult; - public Response(){ + public Response() { } - public Response(long id){ + public Response(long id) { mId = id; } - public Response(long id, String version){ + public Response(long id, String version) { mId = id; mVersion = version; } @@ -118,26 +118,26 @@ public byte getStatus() { public void setStatus(byte status) { mStatus = status; - } - - public boolean isEvent() { - return mEvent; - } - - public void setEvent(String event) { - mEvent = true; - mResult = event; - } - - public boolean isHeartbeat() { - return mEvent && HEARTBEAT_EVENT == mResult; - } - - @Deprecated - public void setHeartbeat(boolean isHeartbeat) { - if (isHeartbeat) { - setEvent(HEARTBEAT_EVENT); - } + } + + public boolean isEvent() { + return mEvent; + } + + public void setEvent(String event) { + mEvent = true; + mResult = event; + } + + public boolean isHeartbeat() { + return mEvent && HEARTBEAT_EVENT == mResult; + } + + @Deprecated + public void setHeartbeat(boolean isHeartbeat) { + if (isHeartbeat) { + setEvent(HEARTBEAT_EVENT); + } } public Object getResult() { @@ -159,6 +159,6 @@ public void setErrorMessage(String msg) { @Override public String toString() { return "Response [id=" + mId + ", version=" + mVersion + ", status=" + mStatus + ", event=" + mEvent - + ", error=" + mErrorMsg + ", result=" + (mResult == this ? "this" : mResult) + "]"; + + ", error=" + mErrorMsg + ", result=" + (mResult == this ? "this" : mResult) + "]"; } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java index d1bc6e4f724..17f1987d4db 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java @@ -1,85 +1,85 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.exchange.support; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.TimeoutException; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.ResponseCallback; +import com.alibaba.dubbo.remoting.exchange.ResponseFuture; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * DefaultFuture. - * - * @author qian.lei + * + * @author qian.lei * @author chao.liuc */ public class DefaultFuture implements ResponseFuture { - private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class); - - private static final Map CHANNELS = new ConcurrentHashMap(); + private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class); - private static final Map FUTURES = new ConcurrentHashMap(); + private static final Map CHANNELS = new ConcurrentHashMap(); + private static final Map FUTURES = new ConcurrentHashMap(); // invoke id. - private final long id; + private final long id; + + private final Channel channel; + + private final Request request; - private final Channel channel; - - private final Request request; + private final int timeout; - private final int timeout; + private final Lock lock = new ReentrantLock(); - private final Lock lock = new ReentrantLock(); + private final Condition done = lock.newCondition(); - private final Condition done = lock.newCondition(); + private final long start = System.currentTimeMillis(); - private final long start = System.currentTimeMillis(); + private volatile long sent; - private volatile long sent; - - private volatile Response response; + private volatile Response response; - private volatile ResponseCallback callback; + private volatile ResponseCallback callback; - public DefaultFuture(Channel channel, Request request, int timeout){ + public DefaultFuture(Channel channel, Request request, int timeout) { this.channel = channel; this.request = request; this.id = request.getId(); - this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + this.timeout = timeout > 0 ? timeout : channel.getUrl(). + getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); // put into waiting map. FUTURES.put(id, this); CHANNELS.put(id, channel); } - + public Object get() throws RemotingException { return get(timeout); } @@ -88,11 +88,11 @@ public Object get(int timeout) throws RemotingException { if (timeout <= 0) { timeout = Constants.DEFAULT_TIMEOUT; } - if (! isDone()) { + if (!isDone()) { long start = System.currentTimeMillis(); lock.lock(); try { - while (! isDone()) { + while (!isDone()) { done.await(timeout, TimeUnit.MILLISECONDS); if (isDone() || System.currentTimeMillis() - start > timeout) { break; @@ -103,17 +103,17 @@ public Object get(int timeout) throws RemotingException { } finally { lock.unlock(); } - if (! isDone()) { + if (!isDone()) { throw new TimeoutException(sent > 0, channel, getTimeoutMessage(false)); } } return returnFromResponse(); } - - public void cancel(){ + + public void cancel() { Response errorResult = new Response(id); - errorResult.setErrorMessage("request future has been canceled."); - response = errorResult ; + errorResult.setErrorMessage("request future has been canceled."); + response = errorResult; FUTURES.remove(id); CHANNELS.remove(id); } @@ -122,82 +122,83 @@ public boolean isDone() { return response != null; } - public void setCallback(ResponseCallback callback) { - if (isDone()) { + public void setCallback(ResponseCallback callback) { + if (isDone()) { invokeCallback(callback); - } else { - boolean isdone = false; - lock.lock(); - try{ - if (!isDone()) { - this.callback = callback; - } else { - isdone = true; - } - }finally { - lock.unlock(); - } - if (isdone){ - invokeCallback(callback); - } + } else { + boolean isDone = false; + lock.lock(); + try { + if (!isDone()) { + this.callback = callback; + } else { + isDone = true; + } + } finally { + lock.unlock(); + } + if (isDone) { + invokeCallback(callback); + } } - } - private void invokeCallback(ResponseCallback c){ - ResponseCallback callbackCopy = c; - if (callbackCopy == null){ - throw new NullPointerException("callback cannot be null."); - } - c = null; - Response res = response; - if (res == null) { - throw new IllegalStateException("response cannot be null. url:"+channel.getUrl()); - } - - if (res.getStatus() == Response.OK) { - try { - callbackCopy.done(res.getResult()); - } catch (Exception e) { - logger.error("callback invoke error .reasult:" + res.getResult() + ",url:" + channel.getUrl(), e); - } - } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - try { - TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); - callbackCopy.caught(te); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } - } else { - try { - RuntimeException re = new RuntimeException(res.getErrorMessage()); - callbackCopy.caught(re); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } - } } - private Object returnFromResponse() throws RemotingException { - Response res = response; - if (res == null) { - throw new IllegalStateException("response cannot be null"); - } - if (res.getStatus() == Response.OK) { - return res.getResult(); - } - if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - throw new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); - } - throw new RemotingException(channel, res.getErrorMessage()); - } - + private void invokeCallback(ResponseCallback c) { + ResponseCallback callbackCopy = c; + if (callbackCopy == null) { + throw new NullPointerException("callback cannot be null."); + } + c = null; + Response res = response; + if (res == null) { + throw new IllegalStateException("response cannot be null. url:" + channel.getUrl()); + } + + if (res.getStatus() == Response.OK) { + try { + callbackCopy.done(res.getResult()); + } catch (Exception e) { + logger.error("callback invoke error .reasult:" + res.getResult() + ",url:" + channel.getUrl(), e); + } + } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { + try { + TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); + callbackCopy.caught(te); + } catch (Exception e) { + logger.error("callback invoke error ,url:" + channel.getUrl(), e); + } + } else { + try { + RuntimeException re = new RuntimeException(res.getErrorMessage()); + callbackCopy.caught(re); + } catch (Exception e) { + logger.error("callback invoke error ,url:" + channel.getUrl(), e); + } + } + } + + private Object returnFromResponse() throws RemotingException { + Response res = response; + if (res == null) { + throw new IllegalStateException("response cannot be null"); + } + if (res.getStatus() == Response.OK) { + return res.getResult(); + } + if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { + throw new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); + } + throw new RemotingException(channel, res.getErrorMessage()); + } + private long getId() { return id; } - + private Channel getChannel() { return channel; } - + private boolean isSent() { return sent > 0; } @@ -213,10 +214,10 @@ private int getTimeout() { private long getStartTimestamp() { return start; } - - public static DefaultFuture getFuture(long id) { - return FUTURES.get(id); - } + + public static DefaultFuture getFuture(long id) { + return FUTURES.get(id); + } public static boolean hasFuture(Channel channel) { return CHANNELS.containsValue(channel); @@ -239,11 +240,11 @@ public static void received(Channel channel, Response response) { if (future != null) { future.doReceived(response); } else { - logger.warn("The timeout response finally returned at " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) - + ", response " + response - + (channel == null ? "" : ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress())); + logger.warn("The timeout response finally returned at " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + + ", response " + response + + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress())); } } finally { CHANNELS.remove(response.getId()); @@ -260,7 +261,7 @@ private void doReceived(Response res) { } finally { lock.unlock(); } - if (callback != null) { + if (callback != null) { invokeCallback(callback); } } @@ -268,14 +269,14 @@ private void doReceived(Response res) { private String getTimeoutMessage(boolean scan) { long nowTimestamp = System.currentTimeMillis(); return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side") - + (scan ? " by scan timer" : "") + ". start time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + "," - + (sent > 0 ? " client elapsed: " + (sent - start) - + " ms, server elapsed: " + (nowTimestamp - sent) - : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " - + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress(); + + (scan ? " by scan timer" : "") + ". start time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + "," + + (sent > 0 ? " client elapsed: " + (sent - start) + + " ms, server elapsed: " + (nowTimestamp - sent) + : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " + + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress(); } private static class RemotingInvocationTimeoutScan implements Runnable { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index aa8341b72b4..b46ddc715fd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -15,8 +15,6 @@ */ package com.alibaba.dubbo.remoting.exchange.support.header; -import java.net.InetSocketAddress; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -24,29 +22,27 @@ import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import java.net.InetSocketAddress; + /** * ExchangeReceiver - * + * * @author william.liangf */ final class HeaderExchangeChannel implements ExchangeChannel { - private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeChannel.class); + private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeChannel.class); private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; - private final Channel channel; + private final Channel channel; - private volatile boolean closed = false; + private volatile boolean closed = false; - HeaderExchangeChannel(Channel channel){ + HeaderExchangeChannel(Channel channel) { if (channel == null) { throw new IllegalArgumentException("channel == null"); } @@ -66,20 +62,21 @@ static HeaderExchangeChannel getOrAddChannel(Channel ch) { } return ret; } - + static void removeChannelIfDisconnected(Channel ch) { - if (ch != null && ! ch.isConnected()) { + if (ch != null && !ch.isConnected()) { ch.removeAttribute(CHANNEL_KEY); } } - + public void send(Object message) throws RemotingException { send(message, getUrl().getParameter(Constants.SENT_KEY, false)); } - + public void send(Object message, boolean sent) throws RemotingException { if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The channel " + this + " is closed!"); + throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + + ", cause: The channel " + this + " is closed!"); } if (message instanceof Request || message instanceof Response @@ -100,7 +97,8 @@ public ResponseFuture request(Object request) throws RemotingException { public ResponseFuture request(Object request, int timeout) throws RemotingException { if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); + throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + + ", cause: The channel " + this + " is closed!"); } // create request. Request req = new Request(); @@ -108,9 +106,9 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept req.setTwoWay(true); req.setData(request); DefaultFuture future = new DefaultFuture(channel, req, timeout); - try{ + try { channel.send(req); - }catch (RemotingException e) { + } catch (RemotingException e) { future.cancel(); throw e; } @@ -137,7 +135,7 @@ public void close(int timeout) { closed = true; if (timeout > 0) { long start = System.currentTimeMillis(); - while (DefaultFuture.hasFuture(HeaderExchangeChannel.this) + while (DefaultFuture.hasFuture(HeaderExchangeChannel.this) && System.currentTimeMillis() - start < timeout) { try { Thread.sleep(10); @@ -172,7 +170,7 @@ public ChannelHandler getChannelHandler() { public ExchangeHandler getExchangeHandler() { return (ExchangeHandler) channel.getChannelHandler(); } - + public Object getAttribute(String key) { return channel.getAttribute(key); } @@ -193,7 +191,7 @@ public boolean hasAttribute(String key) { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((channel == null) ? 0 : channel.hashCode()); + result = prime * result + (channel.hashCode()); return result; } @@ -203,10 +201,7 @@ public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; HeaderExchangeChannel other = (HeaderExchangeChannel) obj; - if (channel == null) { - if (other.channel != null) return false; - } else if (!channel.equals(other.channel)) return false; - return true; + return channel.equals(other.channel); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index b1e7f167121..cbb8a59e2a4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -15,13 +15,6 @@ */ package com.alibaba.dubbo.remoting.exchange.support.header; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -31,52 +24,56 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Client; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.exchange.*; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * DefaultMessageClient - * + * * @author william.liangf * @author chao.liuc */ public class HeaderExchangeClient implements ExchangeClient { - private static final Logger logger = LoggerFactory.getLogger( HeaderExchangeClient.class ); + private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeClient.class); private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); // 心跳定时器 - private ScheduledFuture heatbeatTimer; + private ScheduledFuture heartbeatTimer; // 心跳超时,毫秒。缺省0,不会执行心跳。 private int heartbeat; private int heartbeatTimeout; - + private final Client client; private final ExchangeChannel channel; - public HeaderExchangeClient(Client client){ + private final List interceptors = new ArrayList(); + + public HeaderExchangeClient(Client client) { if (client == null) { throw new IllegalArgumentException("client == null"); } this.client = client; this.channel = new HeaderExchangeChannel(client); String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); - this.heartbeat = client.getUrl().getParameter( Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0 ); - this.heartbeatTimeout = client.getUrl().getParameter( Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3 ); - if ( heartbeatTimeout < heartbeat * 2 ) { - throw new IllegalStateException( "heartbeatTimeout < heartbeatInterval * 2" ); + this.heartbeat = client.getUrl().getParameter(Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); + this.heartbeatTimeout = client.getUrl().getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3); + if (heartbeatTimeout < heartbeat * 2) { + throw new IllegalStateException("heartbeatTimeout < heartbeatInterval * 2"); } - startHeatbeatTimer(); - } - - public ResponseFuture request(Object request) throws RemotingException { - return channel.request(request); + startHeartbeatTimer(); } public URL getUrl() { @@ -87,10 +84,6 @@ public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } - public ResponseFuture request(Object request, int timeout) throws RemotingException { - return channel.request(request, timeout); - } - public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @@ -106,11 +99,11 @@ public InetSocketAddress getLocalAddress() { public ExchangeHandler getExchangeHandler() { return channel.getExchangeHandler(); } - + public void send(Object message) throws RemotingException { channel.send(message); } - + public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } @@ -132,9 +125,9 @@ public void close(int timeout) { public void reset(URL url) { client.reset(url); } - + @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters){ + public void reset(com.alibaba.dubbo.common.Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @@ -158,39 +151,88 @@ public boolean hasAttribute(String key) { return channel.hasAttribute(key); } - private void startHeatbeatTimer() { + private void startHeartbeatTimer() { stopHeartbeatTimer(); - if ( heartbeat > 0 ) { - heatbeatTimer = scheduled.scheduleWithFixedDelay( - new HeartBeatTask( new HeartBeatTask.ChannelProvider() { + if (heartbeat > 0) { + heartbeatTimer = scheduled.scheduleWithFixedDelay( + new HeartBeatTask(new HeartBeatTask.ChannelProvider() { public Collection getChannels() { - return Collections.singletonList( HeaderExchangeClient.this ); + return Collections.singletonList(HeaderExchangeClient.this); } }, heartbeat, heartbeatTimeout), - heartbeat, heartbeat, TimeUnit.MILLISECONDS ); + heartbeat, heartbeat, TimeUnit.MILLISECONDS); } } private void stopHeartbeatTimer() { - if (heatbeatTimer != null && ! heatbeatTimer.isCancelled()) { + if (heartbeatTimer != null && !heartbeatTimer.isCancelled()) { try { - heatbeatTimer.cancel(true); + heartbeatTimer.cancel(true); scheduled.purge(); - } catch ( Throwable e ) { + } catch (Throwable e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } } } - heatbeatTimer =null; + heartbeatTimer = null; + } + + public ResponseFuture request(Object request) throws RemotingException { + return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + } + + public ResponseFuture request(Object request, int timeout) throws RemotingException { + Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, request); + return chain.proceed(request, timeout); + } + + @Override + public void addInterceptor(Interceptor interceptor) { + interceptors.add(interceptor); } + /** + * @author Xs request interceptor + */ + class ExchangeClientInterceptorChain implements Interceptor.Chain { + + private final int index; + + private final Object request; + + ExchangeClientInterceptorChain(int index, Object request) { + this.index = index; + this.request = request; + } + + @Override + public Object request() { + return request; + } + + @Override + public ResponseFuture proceed(Object request, int timeout) throws RemotingException { + if (index < interceptors.size()) { + Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request); + Interceptor interceptor = interceptors.get(index); + ResponseFuture responseFuture = interceptor.intercept(chain); + if (responseFuture == null) { + throw new NullPointerException("interceptor " + interceptor + + " returned null"); + } + } + return channel.request(request, timeout); + } + } + + private void doClose() { stopHeartbeatTimer(); } - @Override - public String toString() { - return "HeaderExchangeClient [channel=" + channel + "]"; - } + @Override + public String toString() { + return "HeaderExchangeClient [channel=" + channel + "]"; + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 5cd03fd126d..5144cc6807b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -75,7 +75,7 @@ public HeaderExchangeServer(Server server) { if (heartbeatTimeout < heartbeat * 2) { throw new IllegalStateException("heartbeatTimeout < heartbeatInterval * 2"); } - startHeatbeatTimer(); + startHeartbeatTimer(); } public Server getServer() { @@ -205,7 +205,7 @@ public void reset(URL url) { if (h != heartbeat || t != heartbeatTimeout) { heartbeat = h; heartbeatTimeout = t; - startHeatbeatTimer(); + startHeartbeatTimer(); } } } catch (Throwable t) { @@ -232,7 +232,7 @@ public void send(Object message, boolean sent) throws RemotingException { server.send(message, sent); } - private void startHeatbeatTimer() { + private void startHeartbeatTimer() { stopHeartbeatTimer(); if (heartbeat > 0) { heartbeatTimer = scheduled.scheduleWithFixedDelay( diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ExecuteLimitFilter.java index 64c13c2309a..de176d57bba 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -47,8 +47,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept boolean isException = false; RpcStatus.beginCount(url, methodName); try { - Result result = invoker.invoke(invocation); - return result; + return invoker.invoke(invocation); } catch (Throwable t) { isException = true; if(t instanceof RuntimeException) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractExporter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractExporter.java index d529354a9ca..cbcfd4fb8af 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractExporter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractExporter.java @@ -22,13 +22,13 @@ /** * AbstractExporter. - * + * * @author qianlei * @author william.liangf */ public abstract class AbstractExporter implements Exporter { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); private final Invoker invoker; @@ -50,7 +50,7 @@ public Invoker getInvoker() { public void unexport() { if (unexported) { - return ; + return; } unexported = true; getInvoker().destroy(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProtocol.java index 29050a7f1d6..031400fc95c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProtocol.java @@ -89,14 +89,14 @@ protected static int getServerShutdownTimeout() { if (value != null && value.length() > 0) { try{ timeout = Integer.parseInt(value); - }catch (Exception e) { + }catch (Exception ignored) { } } else { value = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY); if (value != null && value.length() > 0) { try{ timeout = Integer.parseInt(value) * 1000; - }catch (Exception e) { + }catch (Exception ignored) { } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProxyProtocol.java index 72dac1d04c7..95e14d8ce5a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -85,12 +85,12 @@ public void unexport() { } public Invoker refer(final Class type, final URL url) throws RpcException { - final Invoker tagert = proxyFactory.getInvoker(doRefer(type, url), type, url); + final Invoker target = proxyFactory.getInvoker(doRefer(type, url), type, url); Invoker invoker = new AbstractInvoker(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { - Result result = tagert.invoke(invocation); + Result result = target.invoke(invocation); Throwable e = result.getException(); if (e != null) { for (Class rpcException : rpcExceptions) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 33d234aaae3..0d4ded816b0 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -1,22 +1,20 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.net.InetSocketAddress; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; @@ -26,27 +24,25 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeClient; import com.alibaba.dubbo.remoting.transport.ClientDelegate; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; +import java.net.InetSocketAddress; + /** - * 基于已有channel的invoker. - * + * 基于已有channel的invoker. + * * @author chao.liuc */ class ChannelWrappedInvoker extends AbstractInvoker { private final Channel channel; - private final String serviceKey ; + private final String serviceKey; public ChannelWrappedInvoker(Class serviceType, Channel channel, URL url, String serviceKey) { - super(serviceType, url, new String[] { Constants.GROUP_KEY, - Constants.TOKEN_KEY, Constants.TIMEOUT_KEY }); + super(serviceType, url, new String[]{Constants.GROUP_KEY, + Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); this.channel = channel; this.serviceKey = serviceKey; } @@ -62,7 +58,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { try { if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { // 不可靠异步 - currentClient.send(inv,getUrl().getMethodParameter(invocation.getMethodName(), Constants.SENT_KEY, false)); + currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), Constants.SENT_KEY, false)); return new RpcResult(); } int timeout = getUrl().getMethodParameter(invocation.getMethodName(), @@ -86,7 +82,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { public static class ChannelWrapper extends ClientDelegate { private final Channel channel; - private final URL url; + private final URL url; public ChannelWrapper(Channel channel) { this.channel = channel; @@ -110,7 +106,7 @@ public void close() { } public boolean isClosed() { - return channel == null ? true : channel.isClosed(); + return channel.isClosed(); } public void reset(URL url) { @@ -122,7 +118,7 @@ public InetSocketAddress getRemoteAddress() { } public boolean isConnected() { - return channel == null ? false : channel.isConnected(); + return channel.isConnected(); } public boolean hasAttribute(String key) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index 6c1d0b46be3..514f8151e58 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -16,11 +16,6 @@ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Type; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.serialize.Cleanable; @@ -36,6 +31,11 @@ import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.support.RpcUtils; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Type; + /** * @author kimi */ @@ -43,15 +43,15 @@ public class DecodeableRpcResult extends RpcResult implements Codec, Decodeable private static final Logger log = LoggerFactory.getLogger(DecodeableRpcResult.class); - private Channel channel; + private Channel channel; - private byte serializationType; + private byte serializationType; private InputStream inputStream; - private Response response; + private Response response; - private Invocation invocation; + private Invocation invocation; private volatile boolean hasDecoded; @@ -72,7 +72,7 @@ public void encode(Channel channel, OutputStream output, Object message) throws public Object decode(Channel channel, InputStream input) throws IOException { ObjectInput in = CodecSupport.getSerialization(channel.getUrl(), serializationType) - .deserialize(channel.getUrl(), input); + .deserialize(channel.getUrl(), input); try { byte flag = in.readByte(); @@ -83,8 +83,8 @@ public Object decode(Channel channel, InputStream input) throws IOException { try { Type[] returnType = RpcUtils.getReturnTypes(invocation); setValue(returnType == null || returnType.length == 0 ? in.readObject() : - (returnType.length == 1 ? in.readObject((Class) returnType[0]) - : in.readObject((Class) returnType[0], returnType[1]))); + (returnType.length == 1 ? in.readObject((Class) returnType[0]) + : in.readObject((Class) returnType[0], returnType[1]))); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read response data failed.", e)); } @@ -92,7 +92,7 @@ public Object decode(Channel channel, InputStream input) throws IOException { case DubboCodec.RESPONSE_WITH_EXCEPTION: try { Object obj = in.readObject(); - if (obj instanceof Throwable == false) + if (!(obj instanceof Throwable)) throw new IOException("Response data error, expect Throwable, but get " + obj); setException((Throwable) obj); } catch (ClassNotFoundException e) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboExporter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboExporter.java index e965da96263..e8abc4c772b 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboExporter.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboExporter.java @@ -15,24 +15,24 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.util.Map; - import com.alibaba.dubbo.rpc.Exporter; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.protocol.AbstractExporter; +import java.util.Map; + /** * DubboExporter - * + * * @author william.liangf */ public class DubboExporter extends AbstractExporter { - private final String key; + private final String key; private final Map> exporterMap; - public DubboExporter(Invoker invoker, String key, Map> exporterMap){ + public DubboExporter(Invoker invoker, String key, Map> exporterMap) { super(invoker); this.key = key; this.exporterMap = exporterMap; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 57519200f67..f9fc7821224 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; @@ -25,44 +22,41 @@ import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; import com.alibaba.dubbo.rpc.support.RpcUtils; +import java.util.Set; +import java.util.concurrent.locks.ReentrantLock; + /** * DubboInvoker - * + * * @author william.liangf * @author chao.liuc */ public class DubboInvoker extends AbstractInvoker { - private final ExchangeClient[] clients; + private final ExchangeClient[] clients; private final AtomicPositiveInteger index = new AtomicPositiveInteger(); - private final String version; - - private final ReentrantLock destroyLock = new ReentrantLock(); - + private final String version; + + private final ReentrantLock destroyLock = new ReentrantLock(); + private final Set> invokers; - - public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients){ + + public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients) { this(serviceType, url, clients, null); } - - public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients, Set> invokers){ - super(serviceType, url, new String[] {Constants.INTERFACE_KEY, Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); + + public DubboInvoker(Class serviceType, URL url, ExchangeClient[] clients, Set> invokers) { + super(serviceType, url, new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); this.clients = clients; // get version. this.version = url.getParameter(Constants.VERSION_KEY, "0.0.0"); - this.invokers = invokers; + this.invokers = invokers; } @Override @@ -71,7 +65,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { final String methodName = RpcUtils.getMethodName(invocation); inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); inv.setAttachment(Constants.VERSION_KEY, version); - + ExchangeClient currentClient; if (clients.length == 1) { currentClient = clients[0]; @@ -81,18 +75,18 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { try { boolean isAsync = RpcUtils.isAsync(getUrl(), invocation); boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); - int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY,Constants.DEFAULT_TIMEOUT); + int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); if (isOneway) { - boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); + boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); currentClient.send(inv, isSent); RpcContext.getContext().setFuture(null); return new RpcResult(); } else if (isAsync) { - ResponseFuture future = currentClient.request(inv, timeout) ; + ResponseFuture future = currentClient.request(inv, timeout); RpcContext.getContext().setFuture(new FutureAdapter(future)); return new RpcResult(); } else { - RpcContext.getContext().setFuture(null); + RpcContext.getContext().setFuture(null); return (Result) currentClient.request(inv, timeout).get(); } } catch (TimeoutException e) { @@ -101,15 +95,15 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } } - + @Override public boolean isAvailable() { if (!super.isAvailable()) return false; - for (ExchangeClient client : clients){ - if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)){ + for (ExchangeClient client : clients) { + if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? - return true ; + return true; } } return false; @@ -117,17 +111,17 @@ public boolean isAvailable() { public void destroy() { //防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭 - if (super.isDestroyed()){ - return ; + if (super.isDestroyed()) { + return; } else { //dubbo check ,避免多次关闭 destroyLock.lock(); - try{ - if (super.isDestroyed()){ - return ; + try { + if (super.isDestroyed()) { + return; } super.destroy(); - if (invokers != null){ + if (invokers != null) { invokers.remove(this); } for (ExchangeClient client : clients) { @@ -137,8 +131,8 @@ public void destroy() { logger.warn(t.getMessage(), t); } } - - }finally { + + } finally { destroyLock.unlock(); } } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 6b70d1d95ac..642c9a4bee0 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -23,10 +23,7 @@ import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.exchange.*; import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicLong; @@ -219,4 +216,9 @@ private void checkClient() { "LazyConnectExchangeClient state error. the client has not be init .url:" + url); } } + + @Override + public void addInterceptor(Interceptor interceptor) { + client.addInterceptor(interceptor); + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index ccfb35c2923..d1b744c22b3 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.rpc.protocol.dubbo; - +package com.alibaba.dubbo.rpc.protocol.dubbo; + import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; @@ -26,16 +26,17 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.Interceptor; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; - -/** - * dubbo protocol support class. - * - * @author chao.liuc - */ + +/** + * dubbo protocol support class. + * + * @author chao.liuc + */ @SuppressWarnings("deprecation") -final class ReferenceCountExchangeClient implements ExchangeClient { - +final class ReferenceCountExchangeClient implements ExchangeClient { + private ExchangeClient client; private final URL url; @@ -55,8 +56,8 @@ public ReferenceCountExchangeClient(ExchangeClient client, ConcurrentMapcom.squareup.okhttp3 okhttp + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index 7b85811cbd4..3300ec3656a 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -1,10 +1,14 @@ package com.alibaba.dubbo.rpc.protocol.hessian; import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.tracker.RpcTracker; import com.caucho.hessian.client.HessianConnection; import com.caucho.hessian.client.HessianConnectionFactory; import com.caucho.hessian.client.HessianProxyFactory; +import okhttp3.Interceptor; import okhttp3.OkHttpClient; +import okhttp3.Response; import java.io.IOException; import java.net.URL; @@ -17,13 +21,11 @@ public class OkHttpConnectionFactory implements HessianConnectionFactory { private final OkHttpClient client; - public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); - Boolean enableTrace = url.getParameter(Constants.ENABLE_TRACE_KEY, true); if (enableTrace) { - + RpcTracker rpcTracker = ExtensionLoader.getExtensionLoader(RpcTracker.class).getDefaultExtension(); } int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); builder.readTimeout(timeout, TimeUnit.MILLISECONDS); diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index 8bf675546c1..280401bd3f7 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -18,6 +18,16 @@ dubbo-common ${project.parent.version} + + com.alibaba + dubbo-rpc-api + ${project.version} + + + com.alibaba + dubbo-remoting-api + ${project.version} + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java new file mode 100644 index 00000000000..0e0ae848d69 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java @@ -0,0 +1,9 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface ClientRequestInterceptor { + + void handle(Object request); +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java new file mode 100644 index 00000000000..e9b98a28d2b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface ClientResponseInterceptor { + + void handle(Object response); + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java new file mode 100644 index 00000000000..95b7f04f3c5 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java @@ -0,0 +1,28 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.rpc.RpcInvocation; + +/** + * @author Xs + */ +public class DecodeableRequest { + + private final RpcInvocation invocation; + + public DecodeableRequest(Request request) { + this.invocation = (RpcInvocation) request.getData(); + } + + public RpcInvocation getInvocation() { + return invocation; + } + + public String getProviderAddress() { + return invocation.getInvoker().getUrl().getAddress(); + } + + public void addAttachment(String key, String value) { + invocation.setAttachment(key, value); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java new file mode 100644 index 00000000000..328d5c61e5b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public class DecodeableResponse { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java new file mode 100644 index 00000000000..5dd4fa93d7c --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.Invocation; + +/** + * @author Xs + */ +public class DubboSpanNameProvider { + + public String spanName(Invocation invocation) { + return invocation.getMethodName(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java new file mode 100644 index 00000000000..1183c5f647b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + * @seeBraveHttpHeaders + */ +public enum RpcAttachment { + + TraceId("X-B3-TraceId"), + + SpanId("X-B3-SpanId"), + + ParentSpanId("X-B3-ParentSpanId"), + + Sampled("X-B3-Sampled"); + + private final String name; + + RpcAttachment(final String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index e9be2ba6736..0ee8e0e159c 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -1,10 +1,11 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.common.extension.SPI; - /** * @author Xs */ -@SPI("zipkin") public interface RpcTracker { + + ClientRequestInterceptor requestInterceptor(); + + ClientResponseInterceptor responseInterceptor(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java new file mode 100644 index 00000000000..c0f5c644549 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -0,0 +1,16 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * @author Xs + */ +@SPI("zipkin") +public interface RpcTrackerFactory { + + @Adaptive + RpcTracker getRpcTracker(URL url); + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java new file mode 100644 index 00000000000..3e915c4d081 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public class TrackerKeys { + + public static final String PROVIDER_ADDR = "provider.address"; + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java new file mode 100644 index 00000000000..cd476505cfc --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java @@ -0,0 +1,9 @@ +package com.alibaba.dubbo.tracker.filter; + +import com.alibaba.dubbo.rpc.Filter; + +/** + * @author Xs + */ +public interface ClientRpcTrackerFilter extends Filter { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java new file mode 100644 index 00000000000..86e6f643618 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java @@ -0,0 +1,9 @@ +package com.alibaba.dubbo.tracker.filter; + +import com.alibaba.dubbo.rpc.Filter; + +/** + * @author Xs + */ +public interface ServerRpcTrackerFilter extends Filter { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml new file mode 100644 index 00000000000..01c522d0d6e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml @@ -0,0 +1,75 @@ + + + + dubbo-tracker + com.alibaba + 2.8.4 + + 4.0.0 + + dubbo-tracker-zipkin + + + + com.alibaba + dubbo-tracker-api + ${project.version} + + + + com.alibaba + dubbo-remoting-api + ${project.version} + + + + io.zipkin.brave + brave-core + 3.9.0 + + + + io.zipkin.brave + brave-http + 3.9.0 + + + + io.zipkin.brave + brave-web-servlet-filter + 3.9.0 + + + + io.zipkin.brave + brave-okhttp + 3.9.0 + + + + io.zipkin.brave + brave-spancollector-http + 3.9.0 + + + + com.google.auto.value + auto-value + 1.3 + + + + io.zipkin.brave + brave-core-spring + 3.9.0 + + + + io.zipkin.brave + brave-mysql + 3.9.0 + + + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java new file mode 100644 index 00000000000..409fac07c00 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java @@ -0,0 +1,59 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DecodeableRequest; +import com.alibaba.dubbo.tracker.DubboSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.ClientRequestAdapter; +import com.github.kristofa.brave.IdConversion; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.SpanId; +import com.twitter.zipkin.gen.Endpoint; + +import java.util.Collection; +import java.util.Collections; + +/** + * @author Xs + */ +public class BraveClientRequestAdapter implements ClientRequestAdapter { + + private final DubboSpanNameProvider spanNameProvider; + + private final DecodeableRequest request; + + public BraveClientRequestAdapter(DecodeableRequest request, DubboSpanNameProvider spanNameProvider) { + this.request = request; + this.spanNameProvider = spanNameProvider; + } + + @Override + public String getSpanName() { + return spanNameProvider.spanName(request.getInvocation()); + } + + @Override + public void addSpanIdToRequest(SpanId spanId) { + if (spanId == null) { + request.addAttachment(RpcAttachment.Sampled.getName(), "0"); + } else { + request.addAttachment(RpcAttachment.Sampled.getName(), "1"); + request.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); + request.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); + if (spanId.nullableParentId() != null) { + request.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); + } + } + } + + @Override + public Collection requestAnnotations() { + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.getProviderAddress()); + return Collections.singletonList(annotation); + } + + @Override + public Endpoint serverAddress() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java new file mode 100644 index 00000000000..acffcf88c76 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java @@ -0,0 +1,38 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; +import com.alibaba.dubbo.tracker.DecodeableRequest; +import com.alibaba.dubbo.tracker.DubboSpanNameProvider; + +/** + * @author Xs + */ +public class BraveClientRequestInterceptor implements ClientRequestInterceptor { + + private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; + + private final DubboSpanNameProvider spanNameProvider; + + public BraveClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor, + DubboSpanNameProvider spanNameProvider) { + this.clientRequestInterceptor = clientRequestInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public void handle(Object request) { + if (!(request instanceof Request)) { + return; + } + Request req = (Request) request; + if (req.isEvent()) { + return; + } + if (!(req.getData() instanceof RpcInvocation)) { + return; + } + clientRequestInterceptor.handle(new BraveClientRequestAdapter(new DecodeableRequest(req), spanNameProvider)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java new file mode 100644 index 00000000000..f5e7c1139da --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java @@ -0,0 +1,25 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DecodeableResponse; +import com.github.kristofa.brave.ClientResponseAdapter; +import com.github.kristofa.brave.KeyValueAnnotation; + +import java.util.Collection; + +/** + * @author Xs + */ +public class BraveClientResponseAdapter implements ClientResponseAdapter { + + + private DecodeableResponse response; + + public BraveClientResponseAdapter(DecodeableResponse response) { + this.response = response; + } + + @Override + public Collection responseAnnotations() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java new file mode 100644 index 00000000000..85f24a8a6c6 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java @@ -0,0 +1,25 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; + +/** + * @author Xs + */ +public class BraveClientResponseInterceptor implements ClientResponseInterceptor { + + private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; + + + public BraveClientResponseInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor) { + this.clientRequestInterceptor = clientRequestInterceptor; + } + + @Override + public void handle(Object response) { + if (!(response instanceof Response)) { + return; + } + Response res = (Response) response; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java new file mode 100644 index 00000000000..8ef8c3694b5 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java @@ -0,0 +1,37 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.DubboSpanNameProvider; +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.github.kristofa.brave.Brave; +import com.github.kristofa.brave.Sampler; + +/** + * @author Xs + */ +public class BraveRpcTracker implements RpcTracker { + + private final BraveClientRequestInterceptor requestInterceptor; + + public BraveRpcTracker(URL url) { + Brave.Builder builder = new Brave.Builder(url.getParameter("service-name", "demo")); + SpanCollectorFactory spanCollectorFactory = new SpanCollectorFactory(); + builder.spanCollector(spanCollectorFactory.create(url)); + builder.traceSampler(Sampler.ALWAYS_SAMPLE); + Brave brave = builder.build(); + requestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new DubboSpanNameProvider()); + } + + + @Override + public ClientRequestInterceptor requestInterceptor() { + return requestInterceptor; + } + + @Override + public ClientResponseInterceptor responseInterceptor() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java new file mode 100644 index 00000000000..61766c34554 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; + +/** + * @author Xs + */ +public class BraveRpcTrackerFactory implements RpcTrackerFactory { + + private volatile BraveRpcTracker braveRpcTracker; + + @Override + public RpcTracker getRpcTracker(URL url) { + if (braveRpcTracker != null) { + return braveRpcTracker; + } + braveRpcTracker = new BraveRpcTracker(url); + return braveRpcTracker; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java new file mode 100644 index 00000000000..7a42f6b2608 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.github.kristofa.brave.SpanCollectorMetricsHandler; + +/** + * @author Xs + */ +public class LoggingSpanCollectorMetricsHandler implements SpanCollectorMetricsHandler { + + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + + @Override + public void incrementAcceptedSpans(int quantity) { + // NOP + } + + @Override + public void incrementDroppedSpans(int quantity) { + LOGGER.warn(quantity + " spans were dropped !"); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java new file mode 100644 index 00000000000..8c348af338f --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java @@ -0,0 +1,62 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.github.kristofa.brave.ServerClientAndLocalSpanState; +import com.github.kristofa.brave.ServerSpan; +import com.github.kristofa.brave.internal.Util; +import com.twitter.zipkin.gen.Endpoint; +import com.twitter.zipkin.gen.Span; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Xs + */ +public class MappedServerClientAndLocalSpanState implements ServerClientAndLocalSpanState { + + private final Endpoint endpoint; + + public MappedServerClientAndLocalSpanState(int ip, int port, String serviceName) { + Util.checkNotBlank(serviceName, "Service name must be specified."); + endpoint = Endpoint.create(serviceName, ip, port); + } + + @Override + public Span getCurrentClientSpan() { + return null; + } + + @Override + public void setCurrentClientSpan(Span span) { + + } + + @Override + public Span getCurrentLocalSpan() { + return null; + } + + @Override + public void setCurrentLocalSpan(Span span) { + + } + + @Override + public ServerSpan getCurrentServerSpan() { + return null; + } + + @Override + public void setCurrentServerSpan(ServerSpan span) { + + } + + @Override + public Boolean sample() { + return null; + } + + @Override + public Endpoint endpoint() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java new file mode 100644 index 00000000000..37bd3f5669c --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java @@ -0,0 +1,15 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.github.kristofa.brave.SpanCollector; +import com.github.kristofa.brave.http.HttpSpanCollector; + +/** + * @author Xs + */ +public class SpanCollectorFactory { + + public SpanCollector create(URL url) { + return HttpSpanCollector.create("http://192.168.150.132:9411", new LoggingSpanCollectorMetricsHandler()); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java new file mode 100644 index 00000000000..c38f540e2d3 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java @@ -0,0 +1,32 @@ +package com.alibaba.dubbo.tracker.zipkin.filter; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.filter.ClientRpcTrackerFilter; + +/** + * @author Xs + */ +@Activate(group = Constants.CONSUMER, order = Integer.MAX_VALUE) +public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { + + private static final Logger logger = LoggerFactory.getLogger(BraveClientRpcTrackerFilter.class); + + private RpcTrackerFactory rpcTrackerFactory; + + public void setRpcTrackerFactory(RpcTrackerFactory rpcTrackerFactory) { + this.rpcTrackerFactory = rpcTrackerFactory; + } + + @Override + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + return invoker.invoke(invocation); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java new file mode 100644 index 00000000000..055e1393234 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java @@ -0,0 +1,28 @@ +package com.alibaba.dubbo.tracker.zipkin.filter; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.filter.ServerRpcTrackerFilter; + +/** + * @author Xs + */ +@Activate(group = Constants.PROVIDER, order = Integer.MIN_VALUE) +public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { + + private RpcTrackerFactory rpcTrackerFactory; + + public void setRpcTrackerFactory(RpcTrackerFactory rpcTrackerFactory) { + this.rpcTrackerFactory = rpcTrackerFactory; + } + + @Override + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + return invoker.invoke(invocation); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter new file mode 100644 index 00000000000..4667af8ec8a --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter @@ -0,0 +1,2 @@ +clientTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveClientRpcTrackerFilter +serverTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveServerRpcTrackerFilter \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory new file mode 100644 index 00000000000..b6f04f98e64 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerFactory \ No newline at end of file diff --git a/dubbo-tracker/pom.xml b/dubbo-tracker/pom.xml index 019ee0552a2..3252d9b44fa 100644 --- a/dubbo-tracker/pom.xml +++ b/dubbo-tracker/pom.xml @@ -13,6 +13,7 @@ pom dubbo-tracker-api + dubbo-tracker-zipkin \ No newline at end of file diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 1ff4074b884..871e071bdab 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -318,6 +318,13 @@ + + + com.alibaba + dubbo-tracker-zipkin + ${project.parent.version} + + @@ -408,28 +415,37 @@ com.alibaba:dubbo-container-jetty com.alibaba:dubbo-container-log4j com.alibaba:dubbo-container-logback + + com.alibaba:dubbo-tracker-api + com.alibaba:dubbo-tracker-zipkin - META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler + META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler + - META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory + + META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory + - META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization + META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization + - META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker + META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker + - META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool + META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool + @@ -445,23 +461,29 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter + @@ -489,7 +511,8 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance + @@ -497,11 +520,14 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory + - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory + @@ -509,15 +535,18 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler + META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler + - META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory + META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory + - META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory + META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory + @@ -529,11 +558,20 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore + META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore + + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter + + + - META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter + META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory + From d18fc2ca00b6b930e3ab730a7a488865e1660f54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Wed, 11 Jan 2017 17:00:52 +0800 Subject: [PATCH 05/69] add servletFilter and create braveRpcTracker --- .../alibaba/dubbo/common/bytecode/Proxy.java | 483 ++++++++---------- .../dubbo/common/logger/LoggerFactory.java | 145 +++--- .../extensionloader/ExtensionLoaderTest.java | 104 ++-- .../dubbo/container/jetty/JettyContainer.java | 21 +- .../remoting/http/jetty/JettyHttpServer.java | 38 +- .../http/servlet/ServletHttpServer.java | 5 +- .../http/support/AbstractHttpServer.java | 16 +- .../http/tomcat/TomcatHttpServer.java | 4 - .../rpc/proxy/InvokerInvocationHandler.java | 42 +- .../rpc/protocol/hessian/HessianProtocol.java | 3 +- .../hessian/OkHttpConnectionFactory.java | 9 +- .../monitor/simple/SimpleMonitorService.java | 144 +++--- dubbo-tracker/dubbo-tracker-api/pom.xml | 5 + .../com/alibaba/dubbo/tracker/RpcTracker.java | 4 + .../dubbo/tracker/RpcTrackerFactory.java | 6 +- .../alibaba/dubbo/tracker/TrackerManager.java | 10 + .../dubbo/tracker/filter/ServletFilter.java | 6 + dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 16 +- .../zipkin/BraveClientResponseAdapter.java | 1 - .../dubbo/tracker/zipkin/BraveRpcTracker.java | 79 ++- .../zipkin/BraveRpcTrackerFactory.java | 12 +- .../tracker/zipkin/SpanCollectorFactory.java | 15 - .../zipkin/filter/BraveServletFilter.java | 30 ++ .../tracker/zipkin/test/ExtensionTest.java | 26 + .../internal/com.alibaba.dubbo.rpc.Filter | 2 + ...om.alibaba.dubbo.tracker.RpcTrackerFactory | 1 + pom.xml | 46 +- 27 files changed, 675 insertions(+), 598 deletions(-) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Proxy.java index a65e7b2aabe..75b7b0398db 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Proxy.java @@ -15,273 +15,244 @@ */ package com.alibaba.dubbo.common.bytecode; +import com.alibaba.dubbo.common.utils.ClassHelper; +import com.alibaba.dubbo.common.utils.ReflectUtils; + import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; +import java.util.*; import java.util.concurrent.atomic.AtomicLong; -import com.alibaba.dubbo.common.utils.ClassHelper; -import com.alibaba.dubbo.common.utils.ReflectUtils; - /** * Proxy. - * + * * @author qian.lei */ -public abstract class Proxy -{ - private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); - - private static final String PACKAGE_NAME = Proxy.class.getPackage().getName(); - - public static final InvocationHandler RETURN_NULL_INVOKER = new InvocationHandler(){ - public Object invoke(Object proxy, Method method, Object[] args){ return null; } - }; - - public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler(){ - public Object invoke(Object proxy, Method method, Object[] args){ throw new UnsupportedOperationException("Method [" + ReflectUtils.getName(method) + "] unimplemented."); } - }; - - private static final Map> ProxyCacheMap = new WeakHashMap>(); - - private static final Object PendingGenerationMarker = new Object(); - - /** - * Get proxy. - * - * @param ics interface class array. - * @return Proxy instance. - */ - public static Proxy getProxy(Class... ics) - { - return getProxy(ClassHelper.getCallerClassLoader(Proxy.class), ics); - } - - /** - * Get proxy. - * @param cl class loader. - * @param ics interface class array. - * - * @return Proxy instance. - */ - 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 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(';'); - } - - // use interface class name list as key. - String key = sb.toString(); - - // get cache by class loader. - Map cache; - synchronized( ProxyCacheMap ) - { - cache = ProxyCacheMap.get(cl); - if( cache == null ) - { - cache = new HashMap(); - ProxyCacheMap.put(cl, cache); - } - } - - Proxy proxy = null; - synchronized( cache ) - { - do - { - 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(); }catch(InterruptedException e){} - } - else - { - cache.put(key, PendingGenerationMarker); - break; - } - } - while( true ); - } - - 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 rt = method.getReturnType(); - Class[] pts = method.getParameterTypes(); - - StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];"); - for(int j=0;j[]{ InvocationHandler.class }, new Class[0], "handler=$1;"); +public abstract class Proxy { + private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); + + private static final String PACKAGE_NAME = Proxy.class.getPackage().getName(); + + public static final InvocationHandler RETURN_NULL_INVOKER = new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) { + return null; + } + }; + + public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) { + throw new UnsupportedOperationException("Method [" + ReflectUtils.getName(method) + "] unimplemented."); + } + }; + + private static final Map> ProxyCacheMap = new WeakHashMap>(); + + private static final Object PendingGenerationMarker = new Object(); + + /** + * Get proxy. + * + * @param ics interface class array. + * @return Proxy instance. + */ + public static Proxy getProxy(Class... ics) { + return getProxy(ClassHelper.getCallerClassLoader(Proxy.class), ics); + } + + /** + * Get proxy. + * + * @param cl class loader. + * @param ics interface class array. + * @return Proxy instance. + */ + public static Proxy getProxy(ClassLoader cl, Class... ics) { + if (ics.length > 65535) + throw new IllegalArgumentException("interface limit exceeded"); + + StringBuilder sb = new StringBuilder(); + for (Class ic : ics) { + String itf = ic.getName(); + if (!ic.isInterface()) + throw new RuntimeException(itf + " is not a interface."); + + Class tmp = null; + try { + tmp = Class.forName(itf, false, cl); + } catch (ClassNotFoundException ignored) { + } + + if (tmp != ic) + throw new IllegalArgumentException(ic + " is not visible from class loader"); + + sb.append(itf).append(';'); + } + + // use interface class name list as key. + String key = sb.toString(); + + // get cache by class loader. + Map cache; + synchronized (ProxyCacheMap) { + cache = ProxyCacheMap.get(cl); + if (cache == null) { + cache = new HashMap(); + ProxyCacheMap.put(cl, cache); + } + } + + Proxy proxy = null; + synchronized (cache) { + do { + 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(); + } catch (InterruptedException ignored) { + } + } else { + cache.put(key, PendingGenerationMarker); + break; + } + } + while (true); + } + + 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 (Class ic : ics) { + if (!Modifier.isPublic(ic.getModifiers())) { + String npkg = ic.getPackage().getName(); + if (pkg == null) { + pkg = npkg; + } else { + if (!pkg.equals(npkg)) + throw new IllegalArgumentException("non-public interfaces from different packages"); + } + } + ccp.addInterface(ic); + + for (Method method : ic.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(); - } - 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)); - cache.notifyAll(); - } - } - return proxy; - } - - /** - * get instance with default handler. - * - * @return instance. - */ - public Object newInstance() - { - return newInstance(THROW_UNSUPPORTED_INVOKER); - } - - /** - * get instance with special handler. - * - * @return instance. - */ - abstract public Object newInstance(InvocationHandler handler); - - protected Proxy(){} - - private static String asArgument(Class cl, String name) - { - if( cl.isPrimitive() ) - { - if( Boolean.TYPE == cl ) - return name + "==null?false:((Boolean)" + name + ").booleanValue()"; - if( Byte.TYPE == cl ) - return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; - if( Character.TYPE == cl ) - return name + "==null?(char)0:((Character)" + name + ").charValue()"; - if( Double.TYPE == cl ) - return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; - if( Float.TYPE == cl ) - return name + "==null?(float)0:((Float)" + name + ").floatValue()"; - if( Integer.TYPE == cl ) - return name + "==null?(int)0:((Integer)" + name + ").intValue()"; - if( Long.TYPE == cl ) - return name + "==null?(long)0:((Long)" + name + ").longValue()"; - if( Short.TYPE == cl ) - return name + "==null?(short)0:((Short)" + name + ").shortValue()"; - throw new RuntimeException(name+" is unknown primitive type."); - } - return "(" + ReflectUtils.getName(cl) + ")"+name; - } + 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(); + } 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)); + cache.notifyAll(); + } + } + return proxy; + } + + /** + * get instance with default handler. + * + * @return instance. + */ + public Object newInstance() { + return newInstance(THROW_UNSUPPORTED_INVOKER); + } + + /** + * get instance with special handler. + * + * @return instance. + */ + abstract public Object newInstance(InvocationHandler handler); + + protected Proxy() { + } + + private static String asArgument(Class cl, String name) { + if (cl.isPrimitive()) { + if (Boolean.TYPE == cl) + return name + "==null?false:((Boolean)" + name + ").booleanValue()"; + if (Byte.TYPE == cl) + return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; + if (Character.TYPE == cl) + return name + "==null?(char)0:((Character)" + name + ").charValue()"; + if (Double.TYPE == cl) + return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; + if (Float.TYPE == cl) + return name + "==null?(float)0:((Float)" + name + ").floatValue()"; + if (Integer.TYPE == cl) + return name + "==null?(int)0:((Integer)" + name + ").intValue()"; + if (Long.TYPE == cl) + return name + "==null?(long)0:((Long)" + name + ").longValue()"; + if (Short.TYPE == cl) + return name + "==null?(short)0:((Short)" + name + ").shortValue()"; + throw new RuntimeException(name + " is unknown primitive type."); + } + return "(" + ReflectUtils.getName(cl) + ")" + name; + } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java index 3bb6addc10e..274bac892ea 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java @@ -1,31 +1,31 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.common.logger; -import java.io.File; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.jcl.JclLoggerAdapter; -import com.alibaba.dubbo.common.logger.jdk.JdkLoggerAdapter; -import com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter; -import com.alibaba.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; -import com.alibaba.dubbo.common.logger.support.FailsafeLogger; +import java.io.File; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.jcl.JclLoggerAdapter; +import com.alibaba.dubbo.common.logger.jdk.JdkLoggerAdapter; +import com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter; +import com.alibaba.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; +import com.alibaba.dubbo.common.logger.support.FailsafeLogger; /** * 日志输出器工厂 @@ -37,42 +37,41 @@ public class LoggerFactory { private LoggerFactory() { } - private static volatile LoggerAdapter LOGGER_ADAPTER; - + private static volatile LoggerAdapter LOGGER_ADAPTER; + private static final ConcurrentMap LOGGERS = new ConcurrentHashMap(); - // 查找常用的日志框架 - static { - String logger = System.getProperty("dubbo.application.logger"); - if ("slf4j".equals(logger)) { - setLoggerAdapter(new Slf4jLoggerAdapter()); - } else if ("jcl".equals(logger)) { - setLoggerAdapter(new JclLoggerAdapter()); - } else if ("log4j".equals(logger)) { - setLoggerAdapter(new Log4jLoggerAdapter()); - } else if ("jdk".equals(logger)) { - setLoggerAdapter(new JdkLoggerAdapter()); - } else { - try { - setLoggerAdapter(new Log4jLoggerAdapter()); - } catch (Throwable e1) { - try { - setLoggerAdapter(new Slf4jLoggerAdapter()); - } catch (Throwable e2) { - try { - setLoggerAdapter(new JclLoggerAdapter()); - } catch (Throwable e3) { - setLoggerAdapter(new JdkLoggerAdapter()); - } - } - } + static { + String logger = System.getProperty("dubbo.application.logger"); + if ("slf4j".equals(logger)) { + setLoggerAdapter(new Slf4jLoggerAdapter()); + } else if ("jcl".equals(logger)) { + setLoggerAdapter(new JclLoggerAdapter()); + } else if ("log4j".equals(logger)) { + setLoggerAdapter(new Log4jLoggerAdapter()); + } else if ("jdk".equals(logger)) { + setLoggerAdapter(new JdkLoggerAdapter()); + } else { + try { + setLoggerAdapter(new Log4jLoggerAdapter()); + } catch (Throwable e1) { + try { + setLoggerAdapter(new Slf4jLoggerAdapter()); + } catch (Throwable e2) { + try { + setLoggerAdapter(new JclLoggerAdapter()); + } catch (Throwable e3) { + setLoggerAdapter(new JdkLoggerAdapter()); + } + } + } } - } - - public static void setLoggerAdapter(String loggerAdapter) { - if (loggerAdapter != null && loggerAdapter.length() > 0) { - setLoggerAdapter(ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); - } + } + + public static void setLoggerAdapter(String loggerAdapter) { + if (loggerAdapter != null && loggerAdapter.length() > 0) { + setLoggerAdapter(ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); + } } /** @@ -85,9 +84,9 @@ public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { if (loggerAdapter != null) { Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName()); logger.info("using logger: " + loggerAdapter.getClass().getName()); - LoggerFactory.LOGGER_ADAPTER = loggerAdapter; - for (Map.Entry entry : LOGGERS.entrySet()) { - entry.getValue().setLogger(LOGGER_ADAPTER.getLogger(entry.getKey())); + LoggerFactory.LOGGER_ADAPTER = loggerAdapter; + for (Map.Entry entry : LOGGERS.entrySet()) { + entry.getValue().setLogger(LOGGER_ADAPTER.getLogger(entry.getKey())); } } } @@ -99,12 +98,12 @@ public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { * 分类键 * @return 日志输出器, 后验条件: 不返回null. */ - public static Logger getLogger(Class key) { - FailsafeLogger logger = LOGGERS.get(key.getName()); - if (logger == null) { - LOGGERS.putIfAbsent(key.getName(), new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); - logger = LOGGERS.get(key.getName()); - } + public static Logger getLogger(Class key) { + FailsafeLogger logger = LOGGERS.get(key.getName()); + if (logger == null) { + LOGGERS.putIfAbsent(key.getName(), new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); + logger = LOGGERS.get(key.getName()); + } return logger; } @@ -116,11 +115,11 @@ public static Logger getLogger(Class key) { * @return 日志输出器, 后验条件: 不返回null. */ public static Logger getLogger(String key) { - FailsafeLogger logger = LOGGERS.get(key); - if (logger == null) { - LOGGERS.putIfAbsent(key, new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); - logger = LOGGERS.get(key); - } + FailsafeLogger logger = LOGGERS.get(key); + if (logger == null) { + LOGGERS.putIfAbsent(key, new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); + logger = LOGGERS.get(key); + } return logger; } diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java index 689d97e3f49..d6eeb4dc1b0 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java @@ -15,28 +15,18 @@ */ package com.alibaba.dubbo.common.extensionloader; -import static org.hamcrest.CoreMatchers.anyOf; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.*; -import static org.junit.matchers.JUnitMatchers.containsString; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.extensionloader.activate.ActivateExt1; -import com.alibaba.dubbo.common.extensionloader.activate.impl.ActivateExt1Impl1; -import com.alibaba.dubbo.common.extensionloader.activate.impl.GroupActivateExtImpl; -import com.alibaba.dubbo.common.extensionloader.activate.impl.OrderActivateExtImpl1; -import com.alibaba.dubbo.common.extensionloader.activate.impl.OrderActivateExtImpl2; -import com.alibaba.dubbo.common.extensionloader.activate.impl.ValueActivateExtImpl; +import com.alibaba.dubbo.common.extensionloader.activate.impl.*; +import com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt; import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl1; +import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl2; +import com.alibaba.dubbo.common.extensionloader.ext2.Ext2; import com.alibaba.dubbo.common.extensionloader.ext6_wrap.WrappedExt; +import com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper1; +import com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper2; import com.alibaba.dubbo.common.extensionloader.ext7.InitErrorExt; import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt2; @@ -44,16 +34,15 @@ import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt4; import com.alibaba.dubbo.common.extensionloader.ext8_add.impl.*; import junit.framework.Assert; - import org.junit.Test; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt; -import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl2; -import com.alibaba.dubbo.common.extensionloader.ext2.Ext2; -import com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper1; -import com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper2; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import static org.junit.matchers.JUnitMatchers.containsString; /** * @author ding.lid @@ -98,35 +87,35 @@ public void test_getExtensionLoader_NotSpiAnnotation() throws Exception { public void test_getDefaultExtension() throws Exception { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getDefaultExtension(); assertThat(ext, instanceOf(SimpleExtImpl1.class)); - + String name = ExtensionLoader.getExtensionLoader(SimpleExt.class).getDefaultExtensionName(); assertEquals("impl1", name); } - + @Test public void test_getDefaultExtension_NULL() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getDefaultExtension(); assertNull(ext); - + String name = ExtensionLoader.getExtensionLoader(Ext2.class).getDefaultExtensionName(); assertNull(name); } - + @Test public void test_getExtension() throws Exception { assertTrue(ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl1") instanceof SimpleExtImpl1); assertTrue(ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl2") instanceof SimpleExtImpl2); } - + @Test public void test_getExtension_WithWrapper() throws Exception { WrappedExt impl1 = ExtensionLoader.getExtensionLoader(WrappedExt.class).getExtension("impl1"); assertThat(impl1, anyOf(instanceOf(Ext5Wrapper1.class), instanceOf(Ext5Wrapper2.class))); - - WrappedExt impl2 = ExtensionLoader.getExtensionLoader(WrappedExt.class).getExtension("impl2") ; + + WrappedExt impl2 = ExtensionLoader.getExtensionLoader(WrappedExt.class).getExtension("impl2"); assertThat(impl2, anyOf(instanceOf(Ext5Wrapper1.class), instanceOf(Ext5Wrapper2.class))); - - + + URL url = new URL("p1", "1.2.3.4", 1010, "path1"); int echoCount1 = Ext5Wrapper1.echoCount.get(); int echoCount2 = Ext5Wrapper2.echoCount.get(); @@ -135,7 +124,7 @@ public void test_getExtension_WithWrapper() throws Exception { assertEquals(echoCount1 + 1, Ext5Wrapper1.echoCount.get()); assertEquals(echoCount2 + 1, Ext5Wrapper2.echoCount.get()); } - + @Test public void test_getExtension_ExceptionNoExtension() throws Exception { try { @@ -145,7 +134,7 @@ public void test_getExtension_ExceptionNoExtension() throws Exception { assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt by name XXX")); } } - + @Test public void test_getExtension_ExceptionNoExtension_WrapperNotAffactName() throws Exception { try { @@ -155,7 +144,7 @@ public void test_getExtension_ExceptionNoExtension_WrapperNotAffactName() throws assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext6_wrap.WrappedExt by name XXX")); } } - + @Test public void test_getExtension_ExceptionNullArg() throws Exception { try { @@ -165,13 +154,13 @@ public void test_getExtension_ExceptionNullArg() throws Exception { assertThat(expected.getMessage(), containsString("Extension name == null")); } } - + @Test public void test_hasExtension() throws Exception { assertTrue(ExtensionLoader.getExtensionLoader(SimpleExt.class).hasExtension("impl1")); assertFalse(ExtensionLoader.getExtensionLoader(SimpleExt.class).hasExtension("impl1,impl2")); assertFalse(ExtensionLoader.getExtensionLoader(SimpleExt.class).hasExtension("xxx")); - + try { ExtensionLoader.getExtensionLoader(SimpleExt.class).hasExtension(null); fail(); @@ -195,16 +184,16 @@ public void test_hasExtension_wrapperIsNotExt() throws Exception { assertThat(expected.getMessage(), containsString("Extension name == null")); } } - + @Test public void test_getSupportedExtensions() throws Exception { Set exts = ExtensionLoader.getExtensionLoader(SimpleExt.class).getSupportedExtensions(); - + Set expected = new HashSet(); expected.add("impl1"); expected.add("impl2"); expected.add("impl3"); - + assertEquals(expected, exts); } @@ -224,8 +213,7 @@ public void test_AddExtension() throws Exception { try { ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("Manual1"); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 by name Manual")); } @@ -243,8 +231,7 @@ public void test_AddExtension_ExceptionWhenExistedExtension() throws Exception { try { ExtensionLoader.getExtensionLoader(AddExt1.class).addExtension("impl1", AddExt1_ManualAdd1.class); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Extension name impl1 already existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)!")); } } @@ -267,8 +254,7 @@ public void test_AddExtension_Adaptive_ExceptionWhenExistedAdaptive() throws Exc try { loader.addExtension(null, AddExt1_ManualAdaptive.class); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Adaptive Extension already existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)!")); } } @@ -278,8 +264,7 @@ public void test_replaceExtension() throws Exception { try { ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("Manual2"); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 by name Manual")); } @@ -318,8 +303,7 @@ public void test_replaceExtension_ExceptionWhenNotExistedExtension() throws Exce try { ExtensionLoader.getExtensionLoader(AddExt1.class).replaceExtension("NotExistedExtension", AddExt1_ManualAdd1.class); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Extension name NotExistedExtension not existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)")); } } @@ -331,8 +315,7 @@ public void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() th try { loader.replaceExtension(null, AddExt4_ManualAdaptive.class); fail(); - } - catch (IllegalStateException expected) { + } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Adaptive Extension not existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt4)")); } } @@ -340,9 +323,9 @@ public void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() th @Test public void test_InitError() throws Exception { ExtensionLoader loader = ExtensionLoader.getExtensionLoader(InitErrorExt.class); - + loader.getExtension("ok"); - + try { loader.getExtension("error"); fail(); @@ -396,7 +379,7 @@ public void testLoadDefaultActivateExtension() throws Exception { Assert.assertEquals(2, list.size()); Assert.assertTrue(list.get(0).getClass() == OrderActivateExtImpl1.class); Assert.assertTrue(list.get(1).getClass() == ActivateExt1Impl1.class); - + url = URL.valueOf("test://localhost/test?ext=default,order1"); list = ExtensionLoader.getExtensionLoader(ActivateExt1.class) .getActivateExtension(url, "ext", "default_group"); @@ -405,4 +388,9 @@ public void testLoadDefaultActivateExtension() throws Exception { Assert.assertTrue(list.get(1).getClass() == OrderActivateExtImpl1.class); } + @Test + public void test_rpc_factory() throws Exception { + + } + } \ No newline at end of file diff --git a/dubbo-container/dubbo-container-jetty/src/main/java/com/alibaba/dubbo/container/jetty/JettyContainer.java b/dubbo-container/dubbo-container-jetty/src/main/java/com/alibaba/dubbo/container/jetty/JettyContainer.java index e9fae863480..49879baa94e 100644 --- a/dubbo-container/dubbo-container-jetty/src/main/java/com/alibaba/dubbo/container/jetty/JettyContainer.java +++ b/dubbo-container/dubbo-container-jetty/src/main/java/com/alibaba/dubbo/container/jetty/JettyContainer.java @@ -15,13 +15,6 @@ */ package com.alibaba.dubbo.container.jetty; -import org.mortbay.jetty.Handler; -import org.mortbay.jetty.Server; -import org.mortbay.jetty.nio.SelectChannelConnector; -import org.mortbay.jetty.servlet.FilterHolder; -import org.mortbay.jetty.servlet.ServletHandler; -import org.mortbay.jetty.servlet.ServletHolder; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.ConfigUtils; @@ -29,10 +22,16 @@ import com.alibaba.dubbo.container.Container; import com.alibaba.dubbo.container.page.PageServlet; import com.alibaba.dubbo.container.page.ResourceFilter; +import org.mortbay.jetty.Handler; +import org.mortbay.jetty.Server; +import org.mortbay.jetty.nio.SelectChannelConnector; +import org.mortbay.jetty.servlet.FilterHolder; +import org.mortbay.jetty.servlet.ServletHandler; +import org.mortbay.jetty.servlet.ServletHolder; /** * JettyContainer. (SPI, Singleton, ThreadSafe) - * + * * @author william.liangf */ public class JettyContainer implements Container { @@ -60,17 +59,17 @@ public void start() { connector = new SelectChannelConnector(); connector.setPort(port); ServletHandler handler = new ServletHandler(); - + String resources = ConfigUtils.getProperty(JETTY_DIRECTORY); if (resources != null && resources.length() > 0) { FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT); resourceHolder.setInitParameter("resources", resources); } - + ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*"); pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES)); pageHolder.setInitOrder(2); - + Server server = new Server(); server.addConnector(connector); server.addHandler(handler); diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java index fd3ca9465a4..bd393a904c4 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -15,7 +15,15 @@ */ package com.alibaba.dubbo.remoting.http.jetty; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.http.HttpHandler; +import com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet; import com.alibaba.dubbo.remoting.http.servlet.ServletManager; +import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; import org.mortbay.jetty.Server; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.servlet.Context; @@ -25,34 +33,21 @@ import org.mortbay.log.StdErrLog; import org.mortbay.thread.QueuedThreadPool; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.http.HttpHandler; -import com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet; -import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; - public class JettyHttpServer extends AbstractHttpServer { private static final Logger logger = LoggerFactory.getLogger(JettyHttpServer.class); - private Server server; + private final Server server; - private URL url; + private final URL url; - public JettyHttpServer(URL url, final HttpHandler handler){ + public JettyHttpServer(URL url, final HttpHandler handler) { super(url, handler); - - // modified by lishen this.url = url; - // TODO we should leave this setting to slf4j Log.setLog(new StdErrLog()); Log.getLog().setDebugEnabled(false); DispatcherServlet.addHttpHandler(url.getPort(), handler); - int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setDaemon(true); @@ -60,7 +55,7 @@ public JettyHttpServer(URL url, final HttpHandler handler){ threadPool.setMinThreads(threads); SelectChannelConnector connector = new SelectChannelConnector(); - if (! url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) { + if (!url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) { connector.setHost(url.getHost()); } connector.setPort(url.getPort()); @@ -73,10 +68,6 @@ public JettyHttpServer(URL url, final HttpHandler handler){ ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*"); servletHolder.setInitOrder(2); - // modified by lishen - // dubbo's original impl can't support the use of ServletContext -// server.addHandler(servletHandler); - // TODO Context.SESSIONS is the best option here? Context context = new Context(server, "/", Context.SESSIONS); context.setServletHandler(servletHandler); ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); @@ -85,16 +76,13 @@ public JettyHttpServer(URL url, final HttpHandler handler){ server.start(); } catch (Exception e) { throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: " - + e.getMessage(), e); + + e.getMessage(), e); } } public void close() { super.close(); - - // modified by lishen ServletManager.getInstance().removeServletContext(url.getPort()); - if (server != null) { try { server.stop(); diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletHttpServer.java index fa913556c51..eedb40e3a36 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletHttpServer.java @@ -20,10 +20,9 @@ import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; public class ServletHttpServer extends AbstractHttpServer { - - public ServletHttpServer(URL url, HttpHandler handler){ + + public ServletHttpServer(URL url, HttpHandler handler) { super(url, handler); DispatcherServlet.addHttpHandler(url.getPort(), handler); } - } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/support/AbstractHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/support/AbstractHttpServer.java index 295cb18854e..be5c5b97bb9 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/support/AbstractHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/support/AbstractHttpServer.java @@ -15,26 +15,26 @@ */ package com.alibaba.dubbo.remoting.http.support; -import java.net.InetSocketAddress; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.http.HttpHandler; import com.alibaba.dubbo.remoting.http.HttpServer; +import java.net.InetSocketAddress; + /** * AbstractHttpServer - * + * * @author william.liangf */ public abstract class AbstractHttpServer implements HttpServer { private final URL url; - + private final HttpHandler handler; private volatile boolean closed; - - public AbstractHttpServer(URL url, HttpHandler handler){ + + public AbstractHttpServer(URL url, HttpHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } @@ -44,7 +44,7 @@ public AbstractHttpServer(URL url, HttpHandler handler){ this.url = url; this.handler = handler; } - + public HttpHandler getHttpHandler() { return handler; } @@ -55,7 +55,7 @@ public URL getUrl() { public void reset(URL url) { } - + public boolean isBound() { return true; } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java index ac56f74d6b3..bd03ce7f312 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -44,7 +44,6 @@ public class TomcatHttpServer extends AbstractHttpServer { public TomcatHttpServer(URL url, final HttpHandler handler) { super(url, handler); - this.url = url; DispatcherServlet.addHttpHandler(url.getPort(), handler); String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); @@ -67,7 +66,6 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); context.addServletMapping("/*", "dispatcher"); ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); - try { tomcat.start(); } catch (LifecycleException e) { @@ -77,9 +75,7 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { public void close() { super.close(); - ServletManager.getInstance().removeServletContext(url.getPort()); - try { tomcat.stop(); } catch (Exception e) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java index 9e21becc3be..1049ade7d76 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -1,36 +1,36 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.proxy; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + /** * InvokerHandler - * + * * @author william.liangf */ public class InvokerInvocationHandler implements InvocationHandler { private final Invoker invoker; - - public InvokerInvocationHandler(Invoker handler){ + + public InvokerInvocationHandler(Invoker handler) { this.invoker = handler; } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java index ab0a0ba74db..2c482e185cd 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -80,7 +80,6 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } } } - } protected Runnable doExport(T impl, Class type, URL url) throws RpcException { @@ -107,7 +106,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { if ("httpclient".equalsIgnoreCase(client)) { hessianProxyFactory.setConnectionFactory(new HttpClientConnectionFactory()); } else if ("okHttpClient".equalsIgnoreCase(client)) { - hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory(url)); + hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory()); } else if (client != null && client.length() > 0 && !Constants.DEFAULT_HTTP_CLIENT.equals(client)) { throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index 3300ec3656a..3aa491fe4c9 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -21,15 +21,8 @@ public class OkHttpConnectionFactory implements HessianConnectionFactory { private final OkHttpClient client; - public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url) { + public OkHttpConnectionFactory() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); - Boolean enableTrace = url.getParameter(Constants.ENABLE_TRACE_KEY, true); - if (enableTrace) { - RpcTracker rpcTracker = ExtensionLoader.getExtensionLoader(RpcTracker.class).getDefaultExtension(); - } - int timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - builder.readTimeout(timeout, TimeUnit.MILLISECONDS); - builder.writeTimeout(timeout, TimeUnit.MILLISECONDS); client = builder.build(); } diff --git a/dubbo-simple/dubbo-monitor-simple/src/main/java/com/alibaba/dubbo/monitor/simple/SimpleMonitorService.java b/dubbo-simple/dubbo-monitor-simple/src/main/java/com/alibaba/dubbo/monitor/simple/SimpleMonitorService.java index 34a45001bf2..875e2839460 100644 --- a/dubbo-simple/dubbo-monitor-simple/src/main/java/com/alibaba/dubbo/monitor/simple/SimpleMonitorService.java +++ b/dubbo-simple/dubbo-monitor-simple/src/main/java/com/alibaba/dubbo/monitor/simple/SimpleMonitorService.java @@ -15,38 +15,6 @@ */ package com.alibaba.dubbo.monitor.simple; -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import javax.imageio.ImageIO; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.axis.DateAxis; -import org.jfree.chart.plot.XYPlot; -import org.jfree.data.time.Minute; -import org.jfree.data.time.TimeSeries; -import org.jfree.data.time.TimeSeriesCollection; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -55,10 +23,30 @@ import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.monitor.MonitorService; +import org.jfree.chart.ChartFactory; +import org.jfree.chart.JFreeChart; +import org.jfree.chart.axis.DateAxis; +import org.jfree.chart.plot.XYPlot; +import org.jfree.data.time.Minute; +import org.jfree.data.time.TimeSeries; +import org.jfree.data.time.TimeSeriesCollection; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; /** * SimpleMonitorService - * + * * @author william.liangf */ public class SimpleMonitorService implements MonitorService { @@ -66,9 +54,9 @@ public class SimpleMonitorService implements MonitorService { private static final Logger logger = LoggerFactory.getLogger(SimpleMonitorService.class); private static final String[] types = {SUCCESS, FAILURE, ELAPSED, CONCURRENT, MAX_ELAPSED, MAX_CONCURRENT}; - + private static final String POISON_PROTOCOL = "poison"; - + // 定时任务执行器 private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMonitorTimer", true)); @@ -76,15 +64,15 @@ public class SimpleMonitorService implements MonitorService { private final ScheduledFuture chartFuture; private final Thread writeThread; - + private final BlockingQueue queue; - + private String statisticsDirectory = "statistics"; private String chartsDirectory = "charts"; - + private volatile boolean running = true; - + private static SimpleMonitorService INSTANCE = null; public static SimpleMonitorService getInstance() { @@ -94,7 +82,7 @@ public static SimpleMonitorService getInstance() { public String getStatisticsDirectory() { return statisticsDirectory; } - + public void setStatisticsDirectory(String statistics) { if (statistics != null) { this.statisticsDirectory = statistics; @@ -110,7 +98,7 @@ public void setChartsDirectory(String charts) { this.chartsDirectory = charts; } } - + public SimpleMonitorService() { queue = new LinkedBlockingQueue(Integer.parseInt(ConfigUtils.getProperty("dubbo.monitor.queue", "100000"))); writeThread = new Thread(new Runnable() { @@ -156,7 +144,7 @@ public void close() { logger.warn(t.getMessage(), t); } } - + private void write() throws Exception { URL statistics = queue.take(); if (POISON_PROTOCOL.equals(statistics.getProtocol())) { @@ -195,16 +183,16 @@ private void write() throws Exception { } provider = statistics.getHost(); } - String filename = statisticsDirectory - + "/" + day - + "/" + statistics.getServiceInterface() - + "/" + statistics.getParameter(METHOD) - + "/" + consumer - + "/" + provider + String filename = statisticsDirectory + + "/" + day + + "/" + statistics.getServiceInterface() + + "/" + statistics.getParameter(METHOD) + + "/" + consumer + + "/" + provider + "/" + type + "." + key; File file = new File(filename); File dir = file.getParentFile(); - if (dir != null && ! dir.exists()) { + if (dir != null && !dir.exists()) { dir.mkdirs(); } FileWriter writer = new FileWriter(file, true); @@ -222,7 +210,7 @@ private void write() throws Exception { private void draw() { File rootDir = new File(statisticsDirectory); - if (! rootDir.exists()) { + if (!rootDir.exists()) { return; } File[] dateDirs = rootDir.listFiles(); @@ -232,38 +220,38 @@ private void draw() { File[] methodDirs = serviceDir.listFiles(); for (File methodDir : methodDirs) { String methodUri = chartsDirectory + "/" + dateDir.getName() + "/" + serviceDir.getName() + "/" + methodDir.getName(); - + File successFile = new File(methodUri + "/" + SUCCESS + ".png"); long successModified = successFile.lastModified(); boolean successChanged = false; Map successData = new HashMap(); double[] successSummary = new double[4]; - + File elapsedFile = new File(methodUri + "/" + ELAPSED + ".png"); long elapsedModified = elapsedFile.lastModified(); boolean elapsedChanged = false; Map elapsedData = new HashMap(); double[] elapsedSummary = new double[4]; long elapsedMax = 0; - + File[] consumerDirs = methodDir.listFiles(); for (File consumerDir : consumerDirs) { File[] providerDirs = consumerDir.listFiles(); for (File providerDir : providerDirs) { File consumerSuccessFile = new File(providerDir, CONSUMER + "." + SUCCESS); File providerSuccessFile = new File(providerDir, PROVIDER + "." + SUCCESS); - appendData(new File[] {consumerSuccessFile, providerSuccessFile}, successData, successSummary); - if (consumerSuccessFile.lastModified() > successModified + appendData(new File[]{consumerSuccessFile, providerSuccessFile}, successData, successSummary); + if (consumerSuccessFile.lastModified() > successModified || providerSuccessFile.lastModified() > successModified) { successChanged = true; } - + File consumerElapsedFile = new File(providerDir, CONSUMER + "." + ELAPSED); File providerElapsedFile = new File(providerDir, PROVIDER + "." + ELAPSED); - appendData(new File[] {consumerElapsedFile, providerElapsedFile}, elapsedData, elapsedSummary); + appendData(new File[]{consumerElapsedFile, providerElapsedFile}, elapsedData, elapsedSummary); elapsedMax = Math.max(elapsedMax, CountUtils.max(new File(providerDir, CONSUMER + "." + MAX_ELAPSED))); elapsedMax = Math.max(elapsedMax, CountUtils.max(new File(providerDir, PROVIDER + "." + MAX_ELAPSED))); - if (consumerElapsedFile.lastModified() > elapsedModified + if (consumerElapsedFile.lastModified() > elapsedModified || providerElapsedFile.lastModified() > elapsedModified) { elapsedChanged = true; } @@ -275,42 +263,42 @@ private void draw() { elapsedSummary[1] = -1; elapsedSummary[2] = successSummary[3] == 0 ? 0 : elapsedSummary[3] / successSummary[3]; elapsedSummary[3] = -1; - createChart("ms/t", serviceDir.getName(), methodDir.getName(), dateDir.getName(), new String[] {CONSUMER, PROVIDER}, elapsedData, elapsedSummary, elapsedFile.getAbsolutePath()); + createChart("ms/t", serviceDir.getName(), methodDir.getName(), dateDir.getName(), new String[]{CONSUMER, PROVIDER}, elapsedData, elapsedSummary, elapsedFile.getAbsolutePath()); } if (successChanged) { divData(successData, 60); successSummary[0] = successSummary[0] / 60; successSummary[1] = successSummary[1] / 60; successSummary[2] = successSummary[2] / 60; - createChart("t/s", serviceDir.getName(), methodDir.getName(), dateDir.getName(), new String[] {CONSUMER, PROVIDER}, successData, successSummary, successFile.getAbsolutePath()); + createChart("t/s", serviceDir.getName(), methodDir.getName(), dateDir.getName(), new String[]{CONSUMER, PROVIDER}, successData, successSummary, successFile.getAbsolutePath()); } } } } } - + private void divData(Map successMap, long unit) { for (long[] success : successMap.values()) { - for (int i = 0; i < success.length; i ++) { + for (int i = 0; i < success.length; i++) { success[i] = success[i] / unit; } } } - + private void divData(Map elapsedMap, Map successMap) { for (Map.Entry entry : elapsedMap.entrySet()) { long[] elapsed = entry.getValue(); long[] success = successMap.get(entry.getKey()); - for (int i = 0; i < elapsed.length; i ++) { + for (int i = 0; i < elapsed.length; i++) { elapsed[i] = success[i] == 0 ? 0 : elapsed[i] / success[i]; } } } private void appendData(File[] files, Map data, double[] summary) { - for (int i = 0; i < files.length; i ++) { + for (int i = 0; i < files.length; i++) { File file = files[i]; - if (! file.exists()) { + if (!file.exists()) { continue; } try { @@ -333,7 +321,7 @@ private void appendData(File[] files, Map data, double[] summary summary[0] = Math.max(summary[0], values[i]); summary[1] = summary[1] == 0 ? values[i] : Math.min(summary[1], values[i]); sum += value; - cnt ++; + cnt++; } } if (i == 0) { @@ -348,12 +336,12 @@ private void appendData(File[] files, Map data, double[] summary } } } - + private static void createChart(String key, String service, String method, String date, String[] types, Map data, double[] summary, String path) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm"); DecimalFormat numberFormat = new DecimalFormat("###,##0.##"); TimeSeriesCollection xydataset = new TimeSeriesCollection(); - for (int i = 0; i < types.length; i ++) { + for (int i = 0; i < types.length; i++) { String type = types[i]; TimeSeries timeseries = new TimeSeries(type); for (Map.Entry entry : data.entrySet()) { @@ -366,8 +354,8 @@ private static void createChart(String key, String service, String method, Strin xydataset.addSeries(timeseries); } JFreeChart jfreechart = ChartFactory.createTimeSeriesChart( - "max: " + numberFormat.format(summary[0]) + (summary[1] >=0 ? " min: " + numberFormat.format(summary[1]) : "") - + " avg: " + numberFormat.format(summary[2]) + (summary[3] >=0 ? " sum: " + numberFormat.format(summary[3]) : ""), + "max: " + numberFormat.format(summary[0]) + (summary[1] >= 0 ? " min: " + numberFormat.format(summary[1]) : "") + + " avg: " + numberFormat.format(summary[2]) + (summary[3] >= 0 ? " sum: " + numberFormat.format(summary[3]) : ""), toDisplayService(service) + " " + method + " " + toDisplayDate(date), key, xydataset, true, true, false); jfreechart.setBackgroundPaint(Color.WHITE); XYPlot xyplot = (XYPlot) jfreechart.getPlot(); @@ -385,7 +373,7 @@ private static void createChart(String key, String service, String method, Strin } File methodChartFile = new File(path); File methodChartDir = methodChartFile.getParentFile(); - if (methodChartDir != null && ! methodChartDir.exists()) { + if (methodChartDir != null && !methodChartDir.exists()) { methodChartDir.mkdirs(); } FileOutputStream output = new FileOutputStream(methodChartFile); @@ -399,7 +387,7 @@ private static void createChart(String key, String service, String method, Strin logger.warn(e.getMessage(), e); } } - + private static String toDisplayService(String service) { int i = service.lastIndexOf('.'); if (i >= 0) { @@ -407,7 +395,7 @@ private static String toDisplayService(String service) { } return service; } - + private static String toDisplayDate(String date) { try { return new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(date)); @@ -427,9 +415,9 @@ public void collect(URL statistics) { } } - public List lookup(URL query) { - // TODO Auto-generated method stub - return null; - } + public List lookup(URL query) { + // TODO Auto-generated method stub + return null; + } } \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index 280401bd3f7..801f44db09e 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -28,6 +28,11 @@ dubbo-remoting-api ${project.version} + + + javax.servlet + javax.servlet-api + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index 0ee8e0e159c..e8774997755 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -1,5 +1,7 @@ package com.alibaba.dubbo.tracker; +import com.alibaba.dubbo.tracker.filter.ServletFilter; + /** * @author Xs */ @@ -8,4 +10,6 @@ public interface RpcTracker { ClientRequestInterceptor requestInterceptor(); ClientResponseInterceptor responseInterceptor(); + + ServletFilter servletFilter(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java index c0f5c644549..02fb6ccd5ad 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -1,7 +1,6 @@ package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; /** @@ -10,7 +9,8 @@ @SPI("zipkin") public interface RpcTrackerFactory { - @Adaptive - RpcTracker getRpcTracker(URL url); + RpcTracker createRpcTracker(URL url); + + RpcTracker getTracker(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java new file mode 100644 index 00000000000..49c79219169 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.common.extension.ExtensionLoader; + +public class TrackerManager { + + public static RpcTrackerFactory getTrackerFactory() { + return ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java new file mode 100644 index 00000000000..d5179de7f8e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.tracker.filter; + +import javax.servlet.Filter; + +public interface ServletFilter extends Filter { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml index 01c522d0d6e..8cadb5a6ec6 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml +++ b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml @@ -27,37 +27,41 @@ io.zipkin.brave brave-core - 3.9.0 io.zipkin.brave brave-http - 3.9.0 io.zipkin.brave brave-web-servlet-filter - 3.9.0 io.zipkin.brave brave-okhttp - 3.9.0 io.zipkin.brave brave-spancollector-http - 3.9.0 + + + + io.zipkin.brave + brave-spancollector-kafka + + + + io.zipkin.brave + brave-spancollector-scribe com.google.auto.value auto-value - 1.3 diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java index f5e7c1139da..03d97c1da9c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java @@ -11,7 +11,6 @@ */ public class BraveClientResponseAdapter implements ClientResponseAdapter { - private DecodeableResponse response; public BraveClientResponseAdapter(DecodeableResponse response) { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java index 8ef8c3694b5..eada44734e3 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java @@ -1,27 +1,87 @@ package com.alibaba.dubbo.tracker.zipkin; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.DubboSpanNameProvider; +import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +import com.alibaba.dubbo.tracker.DubboSpanNameProvider; import com.alibaba.dubbo.tracker.RpcTracker; -import com.github.kristofa.brave.Brave; -import com.github.kristofa.brave.Sampler; +import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.alibaba.dubbo.tracker.zipkin.filter.BraveServletFilter; +import com.github.kristofa.brave.*; +import com.github.kristofa.brave.http.DefaultSpanNameProvider; +import com.github.kristofa.brave.http.HttpSpanCollector; +import com.github.kristofa.brave.kafka.KafkaSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; /** * @author Xs */ public class BraveRpcTracker implements RpcTracker { + private final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); + private final BraveClientRequestInterceptor requestInterceptor; - public BraveRpcTracker(URL url) { + private final BraveServletFilter braveServletFilter; + + BraveRpcTracker create(URL url) { + return new BraveRpcTracker(url); + } + + private BraveRpcTracker(URL url) { Brave.Builder builder = new Brave.Builder(url.getParameter("service-name", "demo")); - SpanCollectorFactory spanCollectorFactory = new SpanCollectorFactory(); - builder.spanCollector(spanCollectorFactory.create(url)); - builder.traceSampler(Sampler.ALWAYS_SAMPLE); + builder.spanCollector(createSpanCollector(url)); + builder.traceSampler(createSampler(url)); Brave brave = builder.build(); requestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new DubboSpanNameProvider()); + braveServletFilter = new BraveServletFilter(new com.github.kristofa.brave.servlet.BraveServletFilter( + brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider())); + } + + private SpanCollector createSpanCollector(URL url) { + String collector = url.getParameter("collector", "http"); + if (collector.equals("http")) { + HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); + + String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); + + return HttpSpanCollector.create(baseUrl, config, DEFAULT_HANDLER); + + } else if (collector.equals("kafka")) { + + return KafkaSpanCollector.create(url.getHost() + ":" + url.getPort(), DEFAULT_HANDLER); + + } else if (collector.equals("scribe")) { + + ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); + + params.setMetricsHandler(DEFAULT_HANDLER); + + return new ScribeSpanCollector(url.getHost(), url.getPort(), params); + } else { + throw new IllegalArgumentException("unknown collector type, collector: " + collector); + } + } + + private Sampler createSampler(URL url) { + String sampler = url.getParameter("sampler"); + if (StringUtils.isEmpty(sampler)) { + return Sampler.ALWAYS_SAMPLE; + } else { + String rate = url.getParameter("rate"); + if (StringUtils.isEmpty(rate)) { + throw new IllegalArgumentException("sample rate must not be null"); + } + if (sampler.equals("counting")) { + return CountingSampler.create(Float.valueOf(rate)); + } else if (sampler.equals("boundary")) { + return BoundarySampler.create(Float.valueOf(rate)); + } else { + throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); + } + } } @@ -34,4 +94,9 @@ public ClientRequestInterceptor requestInterceptor() { public ClientResponseInterceptor responseInterceptor() { return null; } + + @Override + public ServletFilter servletFilter() { + return braveServletFilter; + } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index 61766c34554..6adac2dcdb7 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -12,11 +12,19 @@ public class BraveRpcTrackerFactory implements RpcTrackerFactory { private volatile BraveRpcTracker braveRpcTracker; @Override - public RpcTracker getRpcTracker(URL url) { + public synchronized RpcTracker createRpcTracker(URL url) { if (braveRpcTracker != null) { return braveRpcTracker; } - braveRpcTracker = new BraveRpcTracker(url); + braveRpcTracker = BraveRpcTracker.create(url); + return braveRpcTracker; + } + + @Override + public RpcTracker getTracker() { + if (braveRpcTracker == null) { + throw new IllegalStateException("braveRpcTracker must not be null"); + } return braveRpcTracker; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java deleted file mode 100644 index 37bd3f5669c..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.github.kristofa.brave.SpanCollector; -import com.github.kristofa.brave.http.HttpSpanCollector; - -/** - * @author Xs - */ -public class SpanCollectorFactory { - - public SpanCollector create(URL url) { - return HttpSpanCollector.create("http://192.168.150.132:9411", new LoggingSpanCollectorMetricsHandler()); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java new file mode 100644 index 00000000000..671db9a7b6e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin.filter; + +import com.alibaba.dubbo.tracker.filter.ServletFilter; + +import javax.servlet.*; +import java.io.IOException; + +public class BraveServletFilter implements ServletFilter { + + private final com.github.kristofa.brave.servlet.BraveServletFilter servletFilter; + + public BraveServletFilter(com.github.kristofa.brave.servlet.BraveServletFilter servletFilter) { + this.servletFilter = servletFilter; + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + servletFilter.init(filterConfig); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + servletFilter.doFilter(servletRequest, servletResponse, filterChain); + } + + @Override + public void destroy() { + servletFilter.destroy(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java new file mode 100644 index 00000000000..b964c96c479 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker.zipkin.test; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.TrackerManager; +import org.junit.Assert; +import org.junit.Test; + +public class ExtensionTest { + + @Test + public void test_rpc_factory() { + RpcTrackerFactory factory = TrackerManager.getTrackerFactory(); + RpcTrackerFactory factory1 = TrackerManager.getTrackerFactory(); + Assert.assertEquals(factory, factory1); + } + + @Test + public void test_create_tracker() { + RpcTrackerFactory factory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); + URL url = URL.valueOf("zipkin://localhost:9411?service-name=test&collector=http&sampler=counting&rate=0.2"); + RpcTracker rpcTracker = factory.createRpcTracker(url); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter new file mode 100644 index 00000000000..4667af8ec8a --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter @@ -0,0 +1,2 @@ +clientTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveClientRpcTrackerFilter +serverTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveServerRpcTrackerFilter \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory new file mode 100644 index 00000000000..b6f04f98e64 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerFactory \ No newline at end of file diff --git a/pom.xml b/pom.xml index c9f1cb48084..d926161a443 100644 --- a/pom.xml +++ b/pom.xml @@ -41,24 +41,24 @@ http://www.alibaba.com - - - alimaven - aliyun maven - http://maven.aliyun.com/nexus/content/groups/public/ - - - maven.net.cn - one of the central mirrors in china - http://maven.net.cn/content/groups/public/ - + + + + + + + + + + + - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public - - + + + + + + dubbo-common @@ -502,6 +502,18 @@ 3.9.0 + + io.zipkin.brave + brave-spancollector-kafka + 3.9.0 + + + + io.zipkin.brave + brave-spancollector-scribe + 3.9.0 + + com.google.auto.value auto-value From 532066849892d6f56fa2359e9ab5a0457478635b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Thu, 12 Jan 2017 17:17:01 +0800 Subject: [PATCH 06/69] TrackerConfig --- .../alibaba/dubbo/config/AbstractConfig.java | 139 +++++++-------- .../dubbo/config/AbstractInterfaceConfig.java | 161 +++++++++--------- .../dubbo/config/AbstractServiceConfig.java | 82 ++++----- .../dubbo/config/ApplicationConfig.java | 10 ++ .../alibaba/dubbo/config/MethodConfig.java | 81 +++++---- .../alibaba/dubbo/config/ProviderConfig.java | 128 +++++++------- .../alibaba/dubbo/config/RegistryConfig.java | 146 ++++++++-------- .../alibaba/dubbo/config/TrackerConfig.java | 111 ++++++++++++ .../dubbo/config/RpcConfigGetSetProxy.java | 156 +++++++++-------- .../alibaba/dubbo/config/TrackConfigTest.java | 19 +++ .../dubbo/config/spring/ReferenceBean.java | 42 ++--- .../dubbo/config/spring/ServiceBean.java | 8 + .../schema/DubboBeanDefinitionParser.java | 4 - .../spring/schema/DubboNamespaceHandler.java | 24 +-- .../support/header/HeaderExchangeHandler.java | 26 +-- .../java/com/alibaba/dubbo/rpc/RpcResult.java | 2 +- .../dubbo/tracker/DecodeableRequest.java | 28 --- .../dubbo/tracker/DecodeableResponse.java | 7 - .../com/alibaba/dubbo/tracker/RpcTracker.java | 4 +- .../dubbo/tracker/RpcTrackerFactory.java | 2 + .../alibaba/dubbo/tracker/TrackerManager.java | 34 +++- dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 6 + .../zipkin/BraveClientRequestAdapter.java | 21 ++- .../zipkin/BraveClientRequestInterceptor.java | 14 +- .../zipkin/BraveClientResponseAdapter.java | 11 +- .../BraveClientResponseInterceptor.java | 13 +- .../tracker/zipkin/BraveRpcInvocation.java | 24 +++ .../dubbo/tracker/zipkin/BraveRpcResult.java | 12 ++ .../dubbo/tracker/zipkin/BraveRpcTracker.java | 75 ++------ .../zipkin/BraveRpcTrackerFactory.java | 7 +- .../dubbo/tracker/zipkin/SamplerFactory.java | 29 ++++ .../tracker/zipkin/SpanCollectorFactory.java | 31 ++++ .../filter/BraveClientRpcTrackerFilter.java | 19 +-- .../filter/BraveServerRpcTrackerFilter.java | 10 +- .../tracker/zipkin/test/ExtensionTest.java | 8 +- 35 files changed, 838 insertions(+), 656 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java create mode 100644 dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 3eee351cb50..96dce69fb35 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -15,14 +15,6 @@ */ package com.alibaba.dubbo.config; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; @@ -34,9 +26,17 @@ import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.support.Parameter; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * 配置解析的工具方法、公共方法 - * + * * @author william.liangf * @export */ @@ -55,7 +55,7 @@ public abstract class AbstractConfig implements Serializable { private static final Pattern PATTERN_MULTI_NAME = Pattern.compile("[,\\-._0-9a-zA-Z]+"); private static final Pattern PATTERN_METHOD_NAME = Pattern.compile("[a-zA-Z][0-9a-zA-Z]*"); - + private static final Pattern PATTERN_PATH = Pattern.compile("[/\\-$._0-9a-zA-Z]+"); private static final Pattern PATTERN_NAME_HAS_SYMBOL = Pattern.compile("[:*,/\\-._0-9a-zA-Z]+"); @@ -72,8 +72,9 @@ public String getId() { public void setId(String id) { this.id = id; } - + private static final Map legacyProperties = new HashMap(); + static { legacyProperties.put("dubbo.protocol.name", "dubbo.service.protocol"); legacyProperties.put("dubbo.protocol.host", "dubbo.service.server.host"); @@ -84,13 +85,13 @@ public void setId(String id) { legacyProperties.put("dubbo.consumer.check", "dubbo.service.allow.no.provider"); legacyProperties.put("dubbo.service.url", "dubbo.service.address"); } - + private static String convertLegacyValue(String key, String value) { if (value != null && value.length() > 0) { if ("dubbo.service.max.retry.providers".equals(key)) { return String.valueOf(Integer.parseInt(value) - 1); } else if ("dubbo.service.allow.no.provider".equals(key)) { - return String.valueOf(! Boolean.parseBoolean(value)); + return String.valueOf(!Boolean.parseBoolean(value)); } } return value; @@ -103,15 +104,15 @@ protected void appendAnnotation(Class annotationClass, Object annotation) { && method.getReturnType() != void.class && method.getParameterTypes().length == 0 && Modifier.isPublic(method.getModifiers()) - && ! Modifier.isStatic(method.getModifiers())) { + && !Modifier.isStatic(method.getModifiers())) { try { String property = method.getName(); if ("interfaceClass".equals(property) || "interfaceName".equals(property)) { property = "interface"; } String setter = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); - Object value = method.invoke(annotation, new Object[0]); - if (value != null && ! value.equals(method.getDefaultValue())) { + Object value = method.invoke(annotation); + if (value != null && !value.equals(method.getDefaultValue())) { Class parameterType = ReflectUtils.getBoxedClass(method.getReturnType()); if ("filter".equals(property) || "listener".equals(property)) { parameterType = String.class; @@ -121,8 +122,8 @@ protected void appendAnnotation(Class annotationClass, Object annotation) { value = CollectionUtils.toStringMap((String[]) value); } try { - Method setterMethod = getClass().getMethod(setter, new Class[] { parameterType }); - setterMethod.invoke(this, new Object[] { value }); + Method setterMethod = getClass().getMethod(setter, parameterType); + setterMethod.invoke(this, value); } catch (NoSuchMethodException e) { // ignore } @@ -143,7 +144,7 @@ protected static void appendProperties(AbstractConfig config) { for (Method method : methods) { try { String name = method.getName(); - if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) + if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 1 && isPrimitive(method.getParameterTypes()[0])) { String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-"); @@ -151,30 +152,30 @@ protected static void appendProperties(AbstractConfig config) { if (config.getId() != null && config.getId().length() > 0) { String pn = prefix + config.getId() + "." + property; value = System.getProperty(pn); - if(! StringUtils.isBlank(value)) { + if (!StringUtils.isBlank(value)) { logger.info("Use System Property " + pn + " to config dubbo"); } } if (value == null || value.length() == 0) { String pn = prefix + property; value = System.getProperty(pn); - if(! StringUtils.isBlank(value)) { + if (!StringUtils.isBlank(value)) { logger.info("Use System Property " + pn + " to config dubbo"); } } if (value == null || value.length() == 0) { Method getter; try { - getter = config.getClass().getMethod("get" + name.substring(3), new Class[0]); + getter = config.getClass().getMethod("get" + name.substring(3)); } catch (NoSuchMethodException e) { try { - getter = config.getClass().getMethod("is" + name.substring(3), new Class[0]); + getter = config.getClass().getMethod("is" + name.substring(3)); } catch (NoSuchMethodException e2) { getter = null; } } if (getter != null) { - if (getter.invoke(config, new Object[0]) == null) { + if (getter.invoke(config) == null) { if (config.getId() != null && config.getId().length() > 0) { value = ConfigUtils.getProperty(prefix + config.getId() + "." + property); } @@ -187,12 +188,12 @@ protected static void appendProperties(AbstractConfig config) { value = convertLegacyValue(legacyKey, ConfigUtils.getProperty(legacyKey)); } } - + } } } if (value != null && value.length() > 0) { - method.invoke(config, new Object[] {convertPrimitive(method.getParameterTypes()[0], value)}); + method.invoke(config, convertPrimitive(method.getParameterTypes()[0], value)); } } } catch (Exception e) { @@ -200,7 +201,7 @@ protected static void appendProperties(AbstractConfig config) { } } } - + private static String getTagName(Class cls) { String tag = cls.getSimpleName(); for (String suffix : SUFFIXS) { @@ -212,11 +213,11 @@ private static String getTagName(Class cls) { tag = tag.toLowerCase(); return tag; } - + protected static void appendParameters(Map parameters, Object config) { appendParameters(parameters, config, null); } - + @SuppressWarnings("unchecked") protected static void appendParameters(Map parameters, Object config, String prefix) { if (config == null) { @@ -226,9 +227,9 @@ protected static void appendParameters(Map parameters, Object co for (Method method : methods) { try { String name = method.getName(); - if ((name.startsWith("get") || name.startsWith("is")) - && ! "getClass".equals(name) - && Modifier.isPublic(method.getModifiers()) + if ((name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) + && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { Parameter parameter = method.getAnnotation(Parameter.class); @@ -243,18 +244,18 @@ && isPrimitive(method.getReturnType())) { } else { key = prop; } - Object value = method.invoke(config, new Object[0]); + Object value = method.invoke(config); String str = String.valueOf(value).trim(); if (value != null && str.length() > 0) { if (parameter != null && parameter.escaped()) { str = URL.encode(str); } if (parameter != null && parameter.append()) { - String pre = (String)parameters.get(Constants.DEFAULT_KEY + "." + key); + String pre = (String) parameters.get(Constants.DEFAULT_KEY + "." + key); if (pre != null && pre.length() > 0) { str = pre + "," + str; } - pre = (String)parameters.get(key); + pre = (String) parameters.get(key); if (pre != null && pre.length() > 0) { str = pre + "," + str; } @@ -267,10 +268,10 @@ && isPrimitive(method.getReturnType())) { throw new IllegalStateException(config.getClass().getSimpleName() + "." + key + " == null"); } } else if ("getParameters".equals(name) - && Modifier.isPublic(method.getModifiers()) + && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getReturnType() == Map.class) { - Map map = (Map) method.invoke(config, new Object[0]); + Map map = (Map) method.invoke(config); if (map != null && map.size() > 0) { String pre = (prefix != null && prefix.length() > 0 ? prefix + "." : ""); for (Map.Entry entry : map.entrySet()) { @@ -283,11 +284,11 @@ && isPrimitive(method.getReturnType())) { } } } - + protected static void appendAttributes(Map parameters, Object config) { appendAttributes(parameters, config, null); } - + protected static void appendAttributes(Map parameters, Object config, String prefix) { if (config == null) { return; @@ -296,22 +297,22 @@ protected static void appendAttributes(Map parameters, Object co for (Method method : methods) { try { String name = method.getName(); - if ((name.startsWith("get") || name.startsWith("is")) - && ! "getClass".equals(name) - && Modifier.isPublic(method.getModifiers()) + if ((name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) + && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { Parameter parameter = method.getAnnotation(Parameter.class); if (parameter == null || !parameter.attribute()) continue; String key; - if (parameter != null && parameter.key() != null && parameter.key().length() > 0) { + if (parameter.key() != null && parameter.key().length() > 0) { key = parameter.key(); } else { int i = name.startsWith("get") ? 3 : 2; key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); } - Object value = method.invoke(config, new Object[0]); + Object value = method.invoke(config); if (value != null) { if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; @@ -324,21 +325,21 @@ && isPrimitive(method.getReturnType())) { } } } - + private static boolean isPrimitive(Class type) { - return type.isPrimitive() - || type == String.class + return type.isPrimitive() + || type == String.class || type == Character.class || type == Boolean.class || type == Byte.class || type == Short.class - || type == Integer.class + || type == Integer.class || type == Long.class - || type == Float.class + || type == Float.class || type == Double.class || type == Object.class; } - + private static Object convertPrimitive(Class type, String value) { if (type == char.class || type == Character.class) { return value.length() > 0 ? value.charAt(0) : '\0'; @@ -359,15 +360,15 @@ private static Object convertPrimitive(Class type, String value) { } return value; } - + protected static void checkExtension(Class type, String property, String value) { checkName(property, value); - if (value != null && value.length() > 0 - && ! ExtensionLoader.getExtensionLoader(type).hasExtension(value)) { + if (value != null && value.length() > 0 + && !ExtensionLoader.getExtensionLoader(type).hasExtension(value)) { throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName()); } } - + protected static void checkMultiExtension(Class type, String property, String value) { checkMultiName(property, value); if (value != null && value.length() > 0) { @@ -377,9 +378,9 @@ protected static void checkMultiExtension(Class type, String property, String v = v.substring(1); } if (Constants.DEFAULT_KEY.equals(v)) { - continue; + continue; } - if (! ExtensionLoader.getExtensionLoader(type).hasExtension(v)) { + if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) { throw new IllegalStateException("No such extension " + v + " for " + property + "/" + type.getName()); } } @@ -397,7 +398,7 @@ protected static void checkPathLength(String property, String value) { protected static void checkName(String property, String value) { checkProperty(property, value, MAX_LENGTH, PATTERN_NAME); } - + protected static void checkNameHasSymbol(String property, String value) { checkProperty(property, value, MAX_LENGTH, PATTERN_NAME_HAS_SYMBOL); } @@ -405,7 +406,7 @@ protected static void checkNameHasSymbol(String property, String value) { protected static void checkKey(String property, String value) { checkProperty(property, value, MAX_LENGTH, PATTERN_KEY); } - + protected static void checkMultiName(String property, String value) { checkProperty(property, value, MAX_LENGTH, PATTERN_MULTI_NAME); } @@ -417,7 +418,7 @@ protected static void checkPathName(String property, String value) { protected static void checkMethodName(String property, String value) { checkProperty(property, value, MAX_LENGTH, PATTERN_METHOD_NAME); } - + protected static void checkParameterName(Map parameters) { if (parameters == null || parameters.size() == 0) { return; @@ -427,22 +428,22 @@ protected static void checkParameterName(Map parameters) { checkNameHasSymbol(entry.getKey(), entry.getValue()); } } - + protected static void checkProperty(String property, String value, int maxlength, Pattern pattern) { if (value == null || value.length() == 0) { return; } - if(value.length() > maxlength){ + if (value.length() > maxlength) { throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" is longer than " + maxlength); } if (pattern != null) { Matcher matcher = pattern.matcher(value); - if(! matcher.matches()) { + if (!matcher.matches()) { throw new IllegalStateException("Invalid " + property + "=\"" + value + "\" contain illegal charactor, only digit, letter, '-', '_' and '.' is legal."); } } } - + static { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { @@ -453,9 +454,9 @@ public void run() { } }, "DubboShutdownHook")); } - - private static final String[] SUFFIXS = new String[] {"Config", "Bean"}; - + + private static final String[] SUFFIXS = new String[]{"Config", "Bean"}; + @Override public String toString() { try { @@ -466,9 +467,9 @@ public String toString() { for (Method method : methods) { try { String name = method.getName(); - if ((name.startsWith("get") || name.startsWith("is")) - && ! "getClass".equals(name) && ! "get".equals(name) && ! "is".equals(name) - && Modifier.isPublic(method.getModifiers()) + if ((name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) && !"get".equals(name) && !"is".equals(name) + && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { int i = name.startsWith("get") ? 3 : 2; diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java index fca17165e0d..bd37378fd9a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java @@ -15,20 +15,11 @@ */ package com.alibaba.dubbo.config; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.utils.ConfigUtils; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.ReflectUtils; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.common.utils.UrlUtils; +import com.alibaba.dubbo.common.utils.*; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.monitor.MonitorFactory; import com.alibaba.dubbo.monitor.MonitorService; @@ -40,66 +31,73 @@ import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.support.MockInvoker; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * AbstractDefaultConfig - * + * * @author william.liangf * @export */ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { - private static final long serialVersionUID = -1559314110797223229L; + private static final long serialVersionUID = -1559314110797223229L; // 服务接口的本地实现类名 - protected String local; + protected String local; // 服务接口的本地实现类名 - protected String stub; + protected String stub; // 服务监控 - protected MonitorConfig monitor; - + protected MonitorConfig monitor; + + protected TrackerConfig tracker; + // 代理类型 - protected String proxy; - + protected String proxy; + // 集群方式 - protected String cluster; + protected String cluster; // 过滤器 - protected String filter; - + protected String filter; + // 监听器 - protected String listener; + protected String listener; // 负责人 - protected String owner; + protected String owner; // 连接数限制,0表示共享连接,否则为该服务独享连接数 - protected Integer connections; - + protected Integer connections; + // 连接数限制 - protected String layer; - + protected String layer; + // 应用信息 - protected ApplicationConfig application; - + protected ApplicationConfig application; + // 模块信息 - protected ModuleConfig module; + protected ModuleConfig module; // 注册中心 protected List registries; - + // callback实例个数限制 - private Integer callbacks; - + private Integer callbacks; + // 连接事件 - protected String onconnect; - + protected String onconnect; + // 断开事件 - protected String ondisconnect; + protected String ondisconnect; // 服务暴露或引用的scope,如果为local,则表示只在当前JVM内查找. - private String scope; + private String scope; protected void checkRegistry() { // 兼容旧版本 @@ -116,13 +114,13 @@ protected void checkRegistry() { } } if ((registries == null || registries.size() == 0)) { - throw new IllegalStateException((getClass().getSimpleName().startsWith("Reference") - ? "No such any registry to refer service in consumer " - : "No such any registry to export service in provider ") - + NetUtils.getLocalHost() - + " use dubbo version " - + Version.getVersion() - + ", Please add to your spring config. If you want unregister, please set "); + throw new IllegalStateException((getClass().getSimpleName().startsWith("Reference") + ? "No such any registry to refer service in consumer " + : "No such any registry to export service in provider ") + + NetUtils.getLocalHost() + + " use dubbo version " + + Version.getVersion() + + ", Please add to your spring config. If you want unregister, please set "); } for (RegistryConfig registryConfig : registries) { appendProperties(registryConfig); @@ -140,10 +138,10 @@ protected void checkApplication() { } if (application == null) { throw new IllegalStateException( - "No such application config! Please add to your spring config."); + "No such application config! Please add to your spring config."); } appendProperties(application); - + String wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_KEY); if (wait != null && wait.trim().length() > 0) { System.setProperty(Constants.SHUTDOWN_WAIT_KEY, wait.trim()); @@ -154,7 +152,7 @@ protected void checkApplication() { } } } - + protected List loadRegistries(boolean provider) { checkRegistry(); List registryList = new ArrayList(); @@ -162,14 +160,13 @@ protected List loadRegistries(boolean provider) { for (RegistryConfig config : registries) { String address = config.getAddress(); if (address == null || address.length() == 0) { - address = Constants.ANYHOST_VALUE; + address = Constants.ANYHOST_VALUE; } String sysaddress = System.getProperty("dubbo.registry.address"); if (sysaddress != null && sysaddress.length() > 0) { address = sysaddress; } - if (address != null && address.length() > 0 - && ! RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) { + if (address.length() > 0 && !RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) { Map map = new HashMap(); appendParameters(map, application); appendParameters(map, config); @@ -179,7 +176,7 @@ protected List loadRegistries(boolean provider) { if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); } - if (! map.containsKey("protocol")) { + if (!map.containsKey("protocol")) { if (ExtensionLoader.getExtensionLoader(RegistryFactory.class).hasExtension("remote")) { map.put("protocol", "remote"); } else { @@ -191,7 +188,7 @@ protected List loadRegistries(boolean provider) { url = url.addParameter(Constants.REGISTRY_KEY, url.getProtocol()); url = url.setProtocol(Constants.REGISTRY_PROTOCOL); if ((provider && url.getParameter(Constants.REGISTER_KEY, true)) - || (! provider && url.getParameter(Constants.SUBSCRIBE_KEY, true))) { + || (!provider && url.getParameter(Constants.SUBSCRIBE_KEY, true))) { registryList.add(url); } } @@ -200,7 +197,7 @@ protected List loadRegistries(boolean provider) { } return registryList; } - + protected URL loadMonitor(URL registryURL) { if (monitor == null) { String monitorAddress = ConfigUtils.getProperty("dubbo.monitor.address"); @@ -227,7 +224,7 @@ protected URL loadMonitor(URL registryURL) { address = sysaddress; } if (ConfigUtils.isNotEmpty(address)) { - if (! map.containsKey(Constants.PROTOCOL_KEY)) { + if (!map.containsKey(Constants.PROTOCOL_KEY)) { if (ExtensionLoader.getExtensionLoader(MonitorFactory.class).hasExtension("logstat")) { map.put(Constants.PROTOCOL_KEY, "logstat"); } else { @@ -240,14 +237,14 @@ protected URL loadMonitor(URL registryURL) { } return null; } - + protected void checkInterfaceAndMethods(Class interfaceClass, List methods) { // 接口不能为空 if (interfaceClass == null) { throw new IllegalStateException("interface not allow null!"); } // 检查接口类型必需为接口 - if(! interfaceClass.isInterface()) { + if (!interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } // 检查方法是否在接口中存在 @@ -271,11 +268,11 @@ protected void checkInterfaceAndMethods(Class interfaceClass, List interfaceClass) { if (ConfigUtils.isNotEmpty(local)) { Class localClass = ConfigUtils.isDefault(local) ? ReflectUtils.forName(interfaceClass.getName() + "Local") : ReflectUtils.forName(local); - if (! interfaceClass.isAssignableFrom(localClass)) { + if (!interfaceClass.isAssignableFrom(localClass)) { throw new IllegalStateException("The local implemention class " + localClass.getName() + " not implement interface " + interfaceClass.getName()); } try { @@ -286,7 +283,7 @@ protected void checkStubAndMock(Class interfaceClass) { } if (ConfigUtils.isNotEmpty(stub)) { Class localClass = ConfigUtils.isDefault(stub) ? ReflectUtils.forName(interfaceClass.getName() + "Stub") : ReflectUtils.forName(stub); - if (! interfaceClass.isAssignableFrom(localClass)) { + if (!interfaceClass.isAssignableFrom(localClass)) { throw new IllegalStateException("The local implemention class " + localClass.getName() + " not implement interface " + interfaceClass.getName()); } try { @@ -305,11 +302,11 @@ protected void checkStubAndMock(Class interfaceClass) { } } else { Class mockClass = ConfigUtils.isDefault(mock) ? ReflectUtils.forName(interfaceClass.getName() + "Mock") : ReflectUtils.forName(mock); - if (! interfaceClass.isAssignableFrom(mockClass)) { + if (!interfaceClass.isAssignableFrom(mockClass)) { throw new IllegalStateException("The mock implemention class " + mockClass.getName() + " not implement interface " + interfaceClass.getName()); } try { - mockClass.getConstructor(new Class[0]); + mockClass.getConstructor(); } catch (NoSuchMethodException e) { throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implemention class " + mockClass.getName()); } @@ -318,8 +315,8 @@ protected void checkStubAndMock(Class interfaceClass) { } /** - * @deprecated Replace to getStub() * @return local + * @deprecated Replace to getStub() */ @Deprecated public String getLocal() { @@ -327,8 +324,8 @@ public String getLocal() { } /** - * @deprecated Replace to setStub(String) * @param local + * @deprecated Replace to setStub(String) */ @Deprecated public void setLocal(String local) { @@ -337,8 +334,8 @@ public void setLocal(String local) { } /** - * @deprecated Replace to setStub(Boolean) * @param local + * @deprecated Replace to setStub(Boolean) */ @Deprecated public void setLocal(Boolean local) { @@ -348,7 +345,7 @@ public void setLocal(Boolean local) { setLocal(String.valueOf(local)); } } - + public String getStub() { return stub; } @@ -365,7 +362,7 @@ public void setStub(Boolean stub) { setStub(String.valueOf(stub)); } } - + public String getCluster() { return cluster; } @@ -378,7 +375,7 @@ public void setCluster(String cluster) { public String getProxy() { return proxy; } - + public void setProxy(String proxy) { checkExtension(ProxyFactory.class, "proxy", proxy); this.proxy = proxy; @@ -396,7 +393,7 @@ public void setConnections(Integer connections) { public String getFilter() { return filter; } - + public void setFilter(String filter) { checkMultiExtension(Filter.class, "filter", filter); this.filter = filter; @@ -407,7 +404,7 @@ public String getListener() { checkMultiExtension(InvokerListener.class, "listener", listener); return listener; } - + public void setListener(String listener) { this.listener = listener; } @@ -451,9 +448,9 @@ public List getRegistries() { return registries; } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public void setRegistries(List registries) { - this.registries = (List)registries; + this.registries = (List) registries; } public MonitorConfig getMonitor() { @@ -468,12 +465,20 @@ public void setMonitor(String monitor) { this.monitor = new MonitorConfig(monitor); } + public TrackerConfig getTracker() { + return tracker; + } + + public void setTracker(TrackerConfig tracker) { + this.tracker = tracker; + } + public String getOwner() { return owner; } public void setOwner(String owner) { - checkMultiName("owner", owner); + checkMultiName("owner", owner); this.owner = owner; } @@ -501,12 +506,12 @@ public void setOndisconnect(String ondisconnect) { this.ondisconnect = ondisconnect; } - public String getScope() { - return scope; - } + public String getScope() { + return scope; + } - public void setScope(String scope) { - this.scope = scope; - } + public void setScope(String scope) { + this.scope = scope; + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractServiceConfig.java index 68f0ffe78b0..73f3babf2df 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractServiceConfig.java @@ -15,60 +15,60 @@ */ package com.alibaba.dubbo.config; -import java.util.Arrays; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.rpc.ExporterListener; +import java.util.Arrays; +import java.util.List; + /** * AbstractServiceConfig - * + * * @author william.liangf * @export */ public abstract class AbstractServiceConfig extends AbstractInterfaceConfig { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; // 服务版本 - protected String version; + protected String version; // 服务分组 - protected String group; + protected String group; // 服务是否已经deprecated - protected Boolean deprecated; + protected Boolean deprecated; // 延迟暴露 - protected Integer delay; + protected Integer delay; // 是否暴露 - protected Boolean export; + protected Boolean export; // 权重 - protected Integer weight; + protected Integer weight; // 应用文档 - protected String document; + protected String document; // 在注册中心上注册成动态的还是静态的服务 - protected Boolean dynamic; + protected Boolean dynamic; // 是否使用令牌 - protected String token; + protected String token; // 访问日志 - protected String accesslog; + protected String accesslog; // 允许执行请求数 - private Integer executes; + private Integer executes; protected List protocols; // 是否注册 - private Boolean register; + private Boolean register; public String getVersion() { return version; @@ -88,13 +88,13 @@ public void setGroup(String group) { this.group = group; } - public Integer getDelay() { - return delay; - } + public Integer getDelay() { + return delay; + } - public void setDelay(Integer delay) { - this.delay = delay; - } + public void setDelay(Integer delay) { + this.delay = delay; + } public Boolean getExport() { return export; @@ -103,34 +103,34 @@ public Boolean getExport() { public void setExport(Boolean export) { this.export = export; } - + public Integer getWeight() { return weight; } - + public void setWeight(Integer weight) { this.weight = weight; } - + @Parameter(escaped = true) public String getDocument() { return document; } - + public void setDocument(String document) { this.document = document; } - public String getToken() { - return token; - } + public String getToken() { + return token; + } + + public void setToken(String token) { + checkName("token", token); + this.token = token; + } - public void setToken(String token) { - checkName("token", token); - this.token = token; - } - - public void setToken(Boolean token) { + public void setToken(Boolean token) { if (token == null) { setToken((String) null); } else { @@ -158,9 +158,9 @@ public List getProtocols() { return protocols; } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public void setProtocols(List protocols) { - this.protocols = (List)protocols; + this.protocols = (List) protocols; } public ProtocolConfig getProtocol() { @@ -168,7 +168,7 @@ public ProtocolConfig getProtocol() { } public void setProtocol(ProtocolConfig protocol) { - this.protocols = Arrays.asList(new ProtocolConfig[] {protocol}); + this.protocols = Arrays.asList(new ProtocolConfig[]{protocol}); } public String getAccesslog() { @@ -178,7 +178,7 @@ public String getAccesslog() { public void setAccesslog(String accesslog) { this.accesslog = accesslog; } - + public void setAccesslog(Boolean accesslog) { if (accesslog == null) { setAccesslog((String) null); @@ -190,7 +190,7 @@ public void setAccesslog(Boolean accesslog) { public Integer getExecutes() { return executes; } - + public void setExecutes(Integer executes) { this.executes = executes; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java index 605fe34f8dd..e664da5ccbc 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java @@ -64,6 +64,8 @@ public class ApplicationConfig extends AbstractConfig { // 服务监控 private MonitorConfig monitor; + private TrackerConfig tracker; + // 是否为缺省 private Boolean isDefault; @@ -170,6 +172,14 @@ public void setMonitor(String monitor) { this.monitor = new MonitorConfig(monitor); } + public TrackerConfig getTracker() { + return tracker; + } + + public void setTracker(TrackerConfig tracker) { + this.tracker = tracker; + } + public String getCompiler() { return compiler; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java index c0c6218010b..6221a6d4d17 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java @@ -15,14 +15,14 @@ */ package com.alibaba.dubbo.config; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.support.Parameter; +import java.util.List; + /** * MethodConfig - * + * * @author william.liangf * @export */ @@ -31,49 +31,52 @@ public class MethodConfig extends AbstractMethodConfig { private static final long serialVersionUID = 884908855422675941L; // 方法名 - private String name; - + private String name; + // 统计参数 - private Integer stat; + private Integer stat; // 是否重试 - private Boolean retry; + private Boolean retry; + + // 是否开启track,默认开启 + private Boolean trackOn = Boolean.TRUE; // 是否为可靠异步 - private Boolean reliable; + private Boolean reliable; // 方法使用线程数限制 - private Integer executes; - + private Integer executes; + // 是否过时 - private Boolean deprecated; + private Boolean deprecated; // 是否需要开启stiky策略 - private Boolean sticky; + private Boolean sticky; // 是否需要返回 - private Boolean isReturn; - + private Boolean isReturn; + //异步调用回调实例 - private Object oninvoke; + private Object oninvoke; //异步调用回调方法 - private String oninvokeMethod; - + private String oninvokeMethod; + //异步调用回调实例 - private Object onreturn; + private Object onreturn; //异步调用回调方法 - private String onreturnMethod; - + private String onreturnMethod; + //异步调用异常回调实例 - private Object onthrow; - + private Object onthrow; + //异步调用异常回调方法 - private String onthrowMethod; - + private String onthrowMethod; + private List arguments; - + @Parameter(excluded = true) public String getName() { return name; @@ -86,11 +89,11 @@ public void setName(String name) { id = name; } } - + public Integer getStat() { return stat; } - + @Deprecated public void setStat(Integer stat) { this.stat = stat; @@ -140,7 +143,7 @@ public void setArguments(List arguments) { public List getArguments() { return arguments; } - + public Boolean getSticky() { return sticky; } @@ -149,15 +152,23 @@ public void setSticky(Boolean sticky) { this.sticky = sticky; } + public Boolean getTrackOn() { + return trackOn; + } + + public void setTrackOn(Boolean trackOn) { + this.trackOn = trackOn; + } + @Parameter(key = Constants.ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) public Object getOnreturn() { return onreturn; } - + public void setOnreturn(Object onreturn) { this.onreturn = onreturn; } - + @Parameter(key = Constants.ON_RETURN_METHOD_KEY, excluded = true, attribute = true) public String getOnreturnMethod() { return onreturnMethod; @@ -175,7 +186,7 @@ public Object getOnthrow() { public void setOnthrow(Object onthrow) { this.onthrow = onthrow; } - + @Parameter(key = Constants.ON_THROW_METHOD_KEY, excluded = true, attribute = true) public String getOnthrowMethod() { return onthrowMethod; @@ -184,21 +195,21 @@ public String getOnthrowMethod() { public void setOnthrowMethod(String onthrowMethod) { this.onthrowMethod = onthrowMethod; } - + @Parameter(key = Constants.ON_INVOKE_INSTANCE_KEY, excluded = true, attribute = true) public Object getOninvoke() { return oninvoke; } - + public void setOninvoke(Object oninvoke) { this.oninvoke = oninvoke; } - + @Parameter(key = Constants.ON_INVOKE_METHOD_KEY, excluded = true, attribute = true) public String getOninvokeMethod() { return oninvokeMethod; } - + public void setOninvokeMethod(String oninvokeMethod) { this.oninvokeMethod = oninvokeMethod; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index e25abbda2a1..adbb9648498 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -15,8 +15,6 @@ */ package com.alibaba.dubbo.config; -import java.util.Arrays; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.common.threadpool.ThreadPool; @@ -26,95 +24,97 @@ import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; +import java.util.Arrays; + /** * ProviderConfig - * - * @see com.alibaba.dubbo.config.ProtocolConfig - * @see com.alibaba.dubbo.config.ServiceConfig + * * @author william.liangf * @export + * @see com.alibaba.dubbo.config.ProtocolConfig + * @see com.alibaba.dubbo.config.ServiceConfig */ public class ProviderConfig extends AbstractServiceConfig { - private static final long serialVersionUID = 6913423882496634749L; + private static final long serialVersionUID = 6913423882496634749L; // ======== 协议缺省值,当协议属性未设置时使用该缺省值替代 ======== // 服务IP地址(多网卡时使用) - private String host; + private String host; // 服务端口 - private Integer port; + private Integer port; // 上下 - private String contextpath; + private String contextpath; // 线程池类型 - private String threadpool; - + private String threadpool; + // 线程池大小(固定大小) - private Integer threads; + private Integer threads; // IO线程池大小(固定大小) - private Integer iothreads; - + private Integer iothreads; + // 线程池队列大小 - private Integer queues; + private Integer queues; // 最大接收连接数 - private Integer accepts; - + private Integer accepts; + // 协议编码 - private String codec; - + private String codec; + // 序列化方式 - private String serialization; + private String serialization; // 字符集 - private String charset; - + private String charset; + // 最大请求数据长度 - private Integer payload; + private Integer payload; // 缓存区大小 - private Integer buffer; - + private Integer buffer; + // 网络传输方式 - private String transporter; - + private String transporter; + // 信息交换方式 - private String exchanger; + private String exchanger; // 信息线程模型派发方式 - private String dispatcher; + private String dispatcher; // 对称网络组网方式 - private String networker; - + private String networker; + // 服务器端实现 - private String server; - + private String server; + // 客户端实现 - private String client; - + private String client; + // 支持的telnet命令,多个命令用逗号分隔 - private String telnet; + private String telnet; // 命令行提示符 - private String prompt; + private String prompt; // status检查 - private String status; - + private String status; + // 停止时等候时间 - private Integer wait; - + private Integer wait; + // 是否为缺省 - private Boolean isDefault; - + private Boolean isDefault; + @Deprecated public void setProtocol(String protocol) { - this.protocols = Arrays.asList(new ProtocolConfig[] {new ProtocolConfig(protocol)}); + this.protocols = Arrays.asList(new ProtocolConfig[]{new ProtocolConfig(protocol)}); } @Parameter(excluded = true) @@ -126,21 +126,21 @@ public Boolean isDefault() { public void setDefault(Boolean isDefault) { this.isDefault = isDefault; } - + @Parameter(excluded = true) public String getHost() { return host; } - + public void setHost(String host) { this.host = host; } - + @Parameter(excluded = true) public Integer getPort() { return port; } - + @Deprecated public void setPort(Integer port) { this.port = port; @@ -175,11 +175,11 @@ public void setThreadpool(String threadpool) { checkExtension(ThreadPool.class, "threadpool", threadpool); this.threadpool = threadpool; } - + public Integer getThreads() { return threads; } - + public void setThreads(Integer threads) { this.threads = threads; } @@ -195,15 +195,15 @@ public void setIothreads(Integer iothreads) { public Integer getQueues() { return queues; } - + public void setQueues(Integer queues) { this.queues = queues; } - + public Integer getAccepts() { return accepts; } - + public void setAccepts(Integer accepts) { this.accepts = accepts; } @@ -219,7 +219,7 @@ public void setCodec(String codec) { public String getSerialization() { return serialization; } - + public void setSerialization(String serialization) { this.serialization = serialization; } @@ -235,7 +235,7 @@ public void setCharset(String charset) { public Integer getPayload() { return payload; } - + public void setPayload(Integer payload) { this.payload = payload; } @@ -255,7 +255,7 @@ public String getServer() { public void setServer(String server) { this.server = server; } - + public String getClient() { return client; } @@ -267,7 +267,7 @@ public void setClient(String client) { public String getTelnet() { return telnet; } - + public void setTelnet(String telnet) { checkMultiExtension(TelnetHandler.class, "telnet", telnet); this.telnet = telnet; @@ -285,7 +285,7 @@ public void setPrompt(String prompt) { public String getStatus() { return status; } - + public void setStatus(String status) { checkMultiExtension(StatusChecker.class, "status", status); this.status = status; @@ -325,20 +325,20 @@ public Boolean isAsync() { public Integer getActives() { return super.getActives(); } - + public String getTransporter() { return transporter; } - + public void setTransporter(String transporter) { checkExtension(Transporter.class, "transporter", transporter); this.transporter = transporter; } - + public String getExchanger() { return exchanger; } - + public void setExchanger(String exchanger) { checkExtension(Exchanger.class, "exchanger", exchanger); this.exchanger = exchanger; @@ -346,6 +346,7 @@ public void setExchanger(String exchanger) { /** * 单词拼写错误,请使用{@link #getDispatcher()} + * * @deprecated {@link #getDispatcher()} */ @Deprecated @@ -356,6 +357,7 @@ public String getDispather() { /** * 单词拼写错误,请使用{@link #setDispatcher(String)} + * * @deprecated {@link #setDispatcher(String)} */ @Deprecated @@ -384,7 +386,7 @@ public void setNetworker(String networker) { public Integer getWait() { return wait; } - + public void setWait(Integer wait) { this.wait = wait; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java index e53f7ba3970..8e57874904e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java @@ -15,85 +15,85 @@ */ package com.alibaba.dubbo.config; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.registry.support.AbstractRegistryFactory; +import java.util.Map; + /** * RegistryConfig - * + * * @author william.liangf * @export */ public class RegistryConfig extends AbstractConfig { - private static final long serialVersionUID = 5508512956753757169L; - - public static final String NO_AVAILABLE = "N/A"; + private static final long serialVersionUID = 5508512956753757169L; + + public static final String NO_AVAILABLE = "N/A"; // 注册中心地址 - private String address; - - // 注册中心登录用户名 - private String username; + private String address; + + // 注册中心登录用户名 + private String username; // 注册中心登录密码 - private String password; + private String password; // 注册中心缺省端口 - private Integer port; - + private Integer port; + // 注册中心协议 - private String protocol; + private String protocol; // 客户端实现 - private String transporter; - - private String server; - - private String client; + private String transporter; + + private String server; + + private String client; - private String cluster; - - private String group; + private String cluster; - private String version; + private String group; + + private String version; // 注册中心请求超时时间(毫秒) - private Integer timeout; + private Integer timeout; // 注册中心会话超时时间(毫秒) - private Integer session; - + private Integer session; + // 动态注册中心列表存储文件 - private String file; - + private String file; + // 停止时等候完成通知时间 - private Integer wait; - + private Integer wait; + // 启动时检查注册中心是否存在 - private Boolean check; + private Boolean check; // 在该注册中心上注册是动态的还是静态的服务 - private Boolean dynamic; - + private Boolean dynamic; + // 在该注册中心上服务是否暴露 - private Boolean register; - + private Boolean register; + // 在该注册中心上服务是否引用 - private Boolean subscribe; + private Boolean subscribe; // 自定义参数 private Map parameters; // 是否为缺省 - private Boolean isDefault; - + private Boolean isDefault; + public RegistryConfig() { } - + public RegistryConfig(String address) { setAddress(address); } @@ -143,9 +143,9 @@ public void setPassword(String password) { } /** - * @deprecated - * @see com.alibaba.dubbo.config.ProviderConfig#getWait() * @return wait + * @see com.alibaba.dubbo.config.ProviderConfig#getWait() + * @deprecated */ @Deprecated public Integer getWait() { @@ -153,24 +153,24 @@ public Integer getWait() { } /** - * @deprecated - * @see com.alibaba.dubbo.config.ProviderConfig#setWait(Integer) * @param wait + * @see com.alibaba.dubbo.config.ProviderConfig#setWait(Integer) + * @deprecated */ @Deprecated public void setWait(Integer wait) { this.wait = wait; - if( wait!=null && wait>0) + if (wait != null && wait > 0) System.setProperty(Constants.SHUTDOWN_WAIT_KEY, String.valueOf(wait)); } - + public Boolean isCheck() { - return check; - } + return check; + } - public void setCheck(Boolean check) { - this.check = check; - } + public void setCheck(Boolean check) { + this.check = check; + } public String getFile() { return file; @@ -182,26 +182,26 @@ public void setFile(String file) { } /** - * @deprecated - * @see #getTransporter() * @return transport + * @see #getTransporter() + * @deprecated */ @Deprecated @Parameter(excluded = true) public String getTransport() { return getTransporter(); } - + /** - * @deprecated - * @see #setTransporter(String) * @param transport + * @see #setTransporter(String) + * @deprecated */ @Deprecated public void setTransport(String transport) { setTransporter(transport); } - + public String getTransporter() { return transporter; } @@ -213,11 +213,11 @@ public void setTransporter(String transporter) { }*/ this.transporter = transporter; } - + public String getServer() { return server; } - + public void setServer(String server) { checkName("server", server); /*if(server != null && server.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(server)){ @@ -225,11 +225,11 @@ public void setServer(String server) { }*/ this.server = server; } - + public String getClient() { return client; } - + public void setClient(String client) { checkName("client", client); /*if(client != null && client.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(client)){ @@ -238,13 +238,13 @@ public void setClient(String client) { this.client = client; } - public Integer getTimeout() { - return timeout; - } + public Integer getTimeout() { + return timeout; + } - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } public Integer getSession() { return session; @@ -269,22 +269,22 @@ public Boolean isRegister() { public void setRegister(Boolean register) { this.register = register; } - + public Boolean isSubscribe() { return subscribe; } - + public void setSubscribe(Boolean subscribe) { this.subscribe = subscribe; } public String getCluster() { - return cluster; - } + return cluster; + } - public void setCluster(String cluster) { - this.cluster = cluster; - } + public void setCluster(String cluster) { + this.cluster = cluster; + } public String getGroup() { return group; diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java new file mode 100644 index 00000000000..ca7b34f4c08 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java @@ -0,0 +1,111 @@ +package com.alibaba.dubbo.config; + +import java.util.Map; + +public class TrackerConfig extends AbstractConfig { + + private String application; + + private String protocol; + + private String address; + + private String collector; + + private String sampler; + + private Float sampleRate; + + private Integer flushInterval; + + private String group; + + private String version; + + // 自定义参数 + private Map parameters; + + public TrackerConfig() { + } + + public String getApplication() { + return application; + } + + public void setApplication(String application) { + this.application = application; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCollector() { + return collector; + } + + public void setCollector(String collector) { + this.collector = collector; + } + + public String getSampler() { + return sampler; + } + + public void setSampler(String sampler) { + this.sampler = sampler; + } + + public Float getSampleRate() { + return sampleRate; + } + + public void setSampleRate(Float sampleRate) { + this.sampleRate = sampleRate; + } + + public Integer getFlushInterval() { + return flushInterval; + } + + public void setFlushInterval(Integer flushInterval) { + this.flushInterval = flushInterval; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + checkParameterName(parameters); + this.parameters = parameters; + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/RpcConfigGetSetProxy.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/RpcConfigGetSetProxy.java index 7108ae044c4..f8ccaa43906 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/RpcConfigGetSetProxy.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/RpcConfigGetSetProxy.java @@ -1,113 +1,111 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.config; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.config.AbstractConfig; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; /** * @author haomin.liuhm - * */ public class RpcConfigGetSetProxy { private static final String RPC_CONFIG_BASECLASS = AbstractConfig.class.getName(); private static final Logger log = LoggerFactory.getLogger(RpcConfigGetSetProxy.class); - - - private Object proxiee = null; - private Class proxieeClass = null; - private Boolean isOk = false; - - public RpcConfigGetSetProxy(Object p){ - - if(p == null){ + + + private Object proxiee = null; + private Class proxieeClass = null; + private Boolean isOk = false; + + public RpcConfigGetSetProxy(Object p) { + + if (p == null) { return; } - - if (!isKindOf(p.getClass(), RPC_CONFIG_BASECLASS)){ + + if (!isKindOf(p.getClass(), RPC_CONFIG_BASECLASS)) { return; } - + proxiee = p; //proxieeClass = c; proxieeClass = p.getClass(); isOk = true; - + } - - public boolean isOk(){ + + public boolean isOk() { return isOk; } - - public Object setValue(String key, Object value){ - - if (!isOk()){ + + public Object setValue(String key, Object value) { + + if (!isOk()) { return null; } - + Method m = findSetMethod(key, value, proxieeClass); return invoke(m, value); } - public Object getValue(String key){ - - if (!isOk()){ + public Object getValue(String key) { + + if (!isOk()) { return null; } - + Method m = findGetMethod(key, proxieeClass); return invoke(m, null); } - public static boolean isKindOf(Class c, String type){ + public static boolean isKindOf(Class c, String type) { // get the class def for obj and type - + Class tClass; try { tClass = Class.forName(type); } catch (ClassNotFoundException e) { return false; } - + // check against type and superclasses - while ( c != null ) { - if ( c == tClass ) return true; + while (c != null) { + if (c == tClass) return true; c = c.getSuperclass(); } - + return false; } - + private Object invoke(Method m, Object value) { - - if (m == null){ + + if (m == null) { return null; } - + try { - if(value == null){ - return m.invoke(proxiee, (Object[])null); - }else{ + if (value == null) { + return m.invoke(proxiee, (Object[]) null); + } else { return m.invoke(proxiee, value); } } catch (IllegalArgumentException e) { @@ -121,31 +119,31 @@ private Object invoke(Method m, Object value) { return null; } } - - private Method findGetMethod(String key, Class clazz){ - + + private Method findGetMethod(String key, Class clazz) { + Method m = findMethod(key, null, "get", clazz); - if (m != null){ + if (m != null) { return m; } - + return findMethod(key, null, "is", clazz); } - - private Method findSetMethod(String key, Object value, Class clazz){ - + + private Method findSetMethod(String key, Object value, Class clazz) { + return findMethod(key, value, "set", clazz); } - - private Method getMethod(String methodName, Object value, Class clazz){ - - try{ - if (value == null){ - return clazz.getMethod(methodName, (Class[])null); - }else{ + + private Method getMethod(String methodName, Object value, Class clazz) { + + try { + if (value == null) { + return clazz.getMethod(methodName, (Class[]) null); + } else { return clazz.getMethod(methodName, value.getClass()); } - }catch (SecurityException e) { + } catch (SecurityException e) { log.error("SecurityException: " + e.getMessage()); return null; } catch (NoSuchMethodException e) { @@ -154,15 +152,15 @@ private Method getMethod(String methodName, Object value, Class clazz){ } } - private Method findMethod(String key, Object value, String prefix, Class clazz){ - - if(key.length() < 2){ + private Method findMethod(String key, Object value, String prefix, Class clazz) { + + if (key.length() < 2) { return null; } - - key = key.substring(0,1).toUpperCase() + key.substring(1); + + key = key.substring(0, 1).toUpperCase() + key.substring(1); String methodName = prefix + key; - + return getMethod(methodName, value, clazz); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java new file mode 100644 index 00000000000..56603d313fd --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.config; + +import org.junit.Test; + +public class TrackConfigTest { + + @Test + public void test_trackConfig(){ + TrackerConfig trackerConfig = new TrackerConfig(); + trackerConfig.setProtocol("zipkin"); + trackerConfig.setAddress("localhost:9411"); + trackerConfig.setApplication("test"); + trackerConfig.setCollector("kafka"); + trackerConfig.setSampler("counting"); + trackerConfig.setSampleRate(0.1f); + trackerConfig.setFlushInterval(2); + System.out.println(trackerConfig.toString()); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java index 7f58d92cdf9..c2b9cd09f6d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java @@ -15,10 +15,10 @@ */ package com.alibaba.dubbo.config.spring; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import com.alibaba.dubbo.config.*; +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; +import com.alibaba.dubbo.config.support.Parameter; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; @@ -26,29 +26,23 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import com.alibaba.dubbo.config.ApplicationConfig; -import com.alibaba.dubbo.config.ConsumerConfig; -import com.alibaba.dubbo.config.ModuleConfig; -import com.alibaba.dubbo.config.MonitorConfig; -import com.alibaba.dubbo.config.ReferenceConfig; -import com.alibaba.dubbo.config.RegistryConfig; -import com.alibaba.dubbo.config.annotation.Reference; -import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; -import com.alibaba.dubbo.config.support.Parameter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** * ReferenceFactoryBean - * + * * @author william.liangf * @export */ public class ReferenceBean extends ReferenceConfig implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean { - private static final long serialVersionUID = 213195494150089726L; - - private transient ApplicationContext applicationContext; + private static final long serialVersionUID = 213195494150089726L; + + private transient ApplicationContext applicationContext; - public ReferenceBean() { + public ReferenceBean() { super(); } @@ -57,10 +51,10 @@ public ReferenceBean(Reference reference) { } public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - SpringExtensionFactory.addApplicationContext(applicationContext); - } - + this.applicationContext = applicationContext; + SpringExtensionFactory.addApplicationContext(applicationContext); + } + public Object getObject() throws Exception { return get(); } @@ -74,10 +68,10 @@ public boolean isSingleton() { return true; } - @SuppressWarnings({ "unchecked"}) + @SuppressWarnings({"unchecked"}) public void afterPropertiesSet() throws Exception { if (getConsumer() == null) { - Map consumerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ConsumerConfig.class, false, false); + Map consumerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ConsumerConfig.class, false, false); if (consumerConfigMap != null && consumerConfigMap.size() > 0) { ConsumerConfig consumerConfig = null; for (ConsumerConfig config : consumerConfigMap.values()) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index 87ab8102e9a..0a2a0334e09 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -218,6 +218,14 @@ public void afterPropertiesSet() throws Exception { } } } + + //TODO ADD TRACKER HERE + if (getTracker() == null && + (getProvider() == null || getProvider().getTracker() == null) && + (getApplication() == null || getApplication().getTracker() == null)) { + + } + if ((getProtocols() == null || getProtocols().size() == 0) && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().size() == 0)) { Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java index 9b842f04663..2110d034c8a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java @@ -42,8 +42,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Date; -import java.util.HashSet; -import java.util.Set; import java.util.regex.Pattern; /** @@ -129,7 +127,6 @@ private static BeanDefinition parse(Element element, ParserContext parserContext } else if (ConsumerConfig.class.equals(beanClass)) { parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition); } - Set props = new HashSet(); ManagedMap parameters = null; for (Method setter : beanClass.getMethods()) { String name = setter.getName(); @@ -138,7 +135,6 @@ private static BeanDefinition parse(Element element, ParserContext parserContext && setter.getParameterTypes().length == 1) { Class type = setter.getParameterTypes()[0]; String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-"); - props.add(property); Method getter = null; try { getter = beanClass.getMethod("get" + name.substring(3)); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java index 4afe4a42828..58ead17c123 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java @@ -15,34 +15,27 @@ */ package com.alibaba.dubbo.config.spring.schema; -import org.springframework.beans.factory.xml.NamespaceHandlerSupport; - import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.config.ApplicationConfig; -import com.alibaba.dubbo.config.ConsumerConfig; -import com.alibaba.dubbo.config.ModuleConfig; -import com.alibaba.dubbo.config.MonitorConfig; -import com.alibaba.dubbo.config.ProtocolConfig; -import com.alibaba.dubbo.config.ProviderConfig; -import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.*; import com.alibaba.dubbo.config.spring.AnnotationBean; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.ServiceBean; +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * DubboNamespaceHandler - * + * * @author william.liangf * @export */ public class DubboNamespaceHandler extends NamespaceHandlerSupport { - static { - Version.checkDuplicate(DubboNamespaceHandler.class); - } + static { + Version.checkDuplicate(DubboNamespaceHandler.class); + } - public void init() { - registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); + public void init() { + registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true)); registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true)); registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true)); @@ -52,6 +45,7 @@ public void init() { registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); + registerBeanDefinitionParser("tracker", new DubboBeanDefinitionParser(TrackerConfig.class, true)); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index d47d46881f4..774d7abd9c3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -15,8 +15,6 @@ */ package com.alibaba.dubbo.remoting.exchange.support.header; -import java.net.InetSocketAddress; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -34,23 +32,25 @@ import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; +import java.net.InetSocketAddress; + /** * ExchangeReceiver - * + * * @author william.liangf * @author chao.liuc */ public class HeaderExchangeHandler implements ChannelHandlerDelegate { - protected static final Logger logger = LoggerFactory.getLogger(HeaderExchangeHandler.class); + protected static final Logger logger = LoggerFactory.getLogger(HeaderExchangeHandler.class); - public static String KEY_READ_TIMESTAMP = HeartbeatHandler.KEY_READ_TIMESTAMP; + public static String KEY_READ_TIMESTAMP = HeartbeatHandler.KEY_READ_TIMESTAMP; - public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; + public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; private final ExchangeHandler handler; - public HeaderExchangeHandler(ExchangeHandler handler){ + public HeaderExchangeHandler(ExchangeHandler handler) { if (handler == null) { throw new IllegalArgumentException("handler == null"); } @@ -91,7 +91,7 @@ Response handleRequest(ExchangeChannel channel, Request req) throws RemotingExce return res; } - static void handleResponse(Channel channel, Response response) throws RemotingException { + void handleResponse(Channel channel, Response response) throws RemotingException { if (response != null && !response.isHeartbeat()) { DefaultFuture.received(channel, response); } @@ -143,7 +143,7 @@ public void sent(Channel channel, Object message) throws RemotingException { throw (RemotingException) exception; } else { throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), - exception.getMessage(), exception); + exception.getMessage(), exception); } } } @@ -151,9 +151,9 @@ public void sent(Channel channel, Object message) throws RemotingException { private static boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(url.getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + return url.getPort() == address.getPort() && + NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } public void received(Channel channel, Object message) throws RemotingException { @@ -199,7 +199,7 @@ public void caught(Channel channel, Throwable exception) throws RemotingExceptio Object msg = e.getRequest(); if (msg instanceof Request) { Request req = (Request) msg; - if (req.isTwoWay() && ! req.isHeartbeat()) { + if (req.isTwoWay() && !req.isHeartbeat()) { Response res = new Response(req.getId(), req.getVersion()); res.setStatus(Response.SERVER_ERROR); res.setErrorMessage(StringUtils.toString(e)); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java index 706fcd1efd2..ac96b8962d1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java @@ -63,7 +63,7 @@ public Object getResult() { } /** - * @see com.alibaba.dubbo.rpc.RpcResult#setValue() + * @see com.alibaba.dubbo.rpc.RpcResult * @deprecated Replace to setValue() */ @Deprecated diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java deleted file mode 100644 index 95b7f04f3c5..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableRequest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.alibaba.dubbo.tracker; - -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.rpc.RpcInvocation; - -/** - * @author Xs - */ -public class DecodeableRequest { - - private final RpcInvocation invocation; - - public DecodeableRequest(Request request) { - this.invocation = (RpcInvocation) request.getData(); - } - - public RpcInvocation getInvocation() { - return invocation; - } - - public String getProviderAddress() { - return invocation.getInvoker().getUrl().getAddress(); - } - - public void addAttachment(String key, String value) { - invocation.setAttachment(key, value); - } -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java deleted file mode 100644 index 328d5c61e5b..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DecodeableResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public class DecodeableResponse { -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index e8774997755..bf76278a679 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -7,9 +7,9 @@ */ public interface RpcTracker { - ClientRequestInterceptor requestInterceptor(); + ClientRequestInterceptor clientRequestInterceptor(); - ClientResponseInterceptor responseInterceptor(); + ClientResponseInterceptor clientResponseInterceptor(); ServletFilter servletFilter(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java index 02fb6ccd5ad..51c525ccdff 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -1,6 +1,7 @@ package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; /** @@ -9,6 +10,7 @@ @SPI("zipkin") public interface RpcTrackerFactory { + @Adaptive("protocol") RpcTracker createRpcTracker(URL url); RpcTracker getTracker(); diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java index 49c79219169..12359e3d632 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java @@ -1,10 +1,42 @@ package com.alibaba.dubbo.tracker; +import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; +/** + * @author Xs + */ public class TrackerManager { + private static RpcTrackerFactory rpcTrackerFactory; + + private static RpcTracker rpcTracker; + + static { + rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getAdaptiveExtension(); + } + public static RpcTrackerFactory getTrackerFactory() { - return ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); + return rpcTrackerFactory; + } + + public static synchronized RpcTracker create(URL url) { + if (rpcTracker == null) { + rpcTracker = rpcTrackerFactory.createRpcTracker(url); + } + return rpcTracker; + } + + public static RpcTracker getRpcTracker() { + if (rpcTracker == null) { + throw new IllegalStateException("rpcTracker should be create first!"); + } + return rpcTracker; + } + + public static RpcTracker mockRpcTracker(String application) { + String urlStr = "zipkin://localhost:9411?application=" + application + "&collector=http"; + URL url = URL.valueOf(urlStr); + return create(url); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml index 8cadb5a6ec6..e6efb0cd1be 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml +++ b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml @@ -24,6 +24,12 @@ ${project.version} + + com.alibaba + dubbo-rpc-default + ${project.version} + + io.zipkin.brave brave-core diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java index 409fac07c00..0e20e55f81f 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java @@ -1,6 +1,5 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.DecodeableRequest; import com.alibaba.dubbo.tracker.DubboSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; import com.alibaba.dubbo.tracker.TrackerKeys; @@ -20,35 +19,35 @@ public class BraveClientRequestAdapter implements ClientRequestAdapter { private final DubboSpanNameProvider spanNameProvider; - private final DecodeableRequest request; + private final BraveRpcInvocation invocation; - public BraveClientRequestAdapter(DecodeableRequest request, DubboSpanNameProvider spanNameProvider) { - this.request = request; + public BraveClientRequestAdapter(BraveRpcInvocation invocation, DubboSpanNameProvider spanNameProvider) { + this.invocation = invocation; this.spanNameProvider = spanNameProvider; } @Override public String getSpanName() { - return spanNameProvider.spanName(request.getInvocation()); + return spanNameProvider.spanName(invocation.getRpcInvocation()); } @Override public void addSpanIdToRequest(SpanId spanId) { if (spanId == null) { - request.addAttachment(RpcAttachment.Sampled.getName(), "0"); + invocation.addAttachment(RpcAttachment.Sampled.getName(), "0"); } else { - request.addAttachment(RpcAttachment.Sampled.getName(), "1"); - request.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); - request.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); + invocation.addAttachment(RpcAttachment.Sampled.getName(), "1"); + invocation.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); + invocation.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); if (spanId.nullableParentId() != null) { - request.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); + invocation.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); } } } @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.getProviderAddress()); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, invocation.providerAddress()); return Collections.singletonList(annotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java index acffcf88c76..ac48785fb5b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java @@ -1,9 +1,7 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.DecodeableRequest; import com.alibaba.dubbo.tracker.DubboSpanNameProvider; /** @@ -23,16 +21,10 @@ public BraveClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInte @Override public void handle(Object request) { - if (!(request instanceof Request)) { + if (!(request instanceof RpcInvocation)) { return; } - Request req = (Request) request; - if (req.isEvent()) { - return; - } - if (!(req.getData() instanceof RpcInvocation)) { - return; - } - clientRequestInterceptor.handle(new BraveClientRequestAdapter(new DecodeableRequest(req), spanNameProvider)); + RpcInvocation invocation = (RpcInvocation) request; + clientRequestInterceptor.handle(new BraveClientRequestAdapter(new BraveRpcInvocation(invocation), spanNameProvider)); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java index 03d97c1da9c..39ee2ed9f37 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java @@ -1,24 +1,25 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.DecodeableResponse; import com.github.kristofa.brave.ClientResponseAdapter; import com.github.kristofa.brave.KeyValueAnnotation; import java.util.Collection; +import java.util.Collections; /** * @author Xs */ public class BraveClientResponseAdapter implements ClientResponseAdapter { - private DecodeableResponse response; + private final BraveRpcResult rpcResult; - public BraveClientResponseAdapter(DecodeableResponse response) { - this.response = response; + public BraveClientResponseAdapter(BraveRpcResult rpcResult) { + this.rpcResult = rpcResult; } @Override public Collection responseAnnotations() { - return null; + + return Collections.EMPTY_LIST; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java index 85f24a8a6c6..9fa0480ed2b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.rpc.protocol.dubbo.DecodeableRpcResult; import com.alibaba.dubbo.tracker.ClientResponseInterceptor; /** @@ -8,18 +8,19 @@ */ public class BraveClientResponseInterceptor implements ClientResponseInterceptor { - private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; + private final com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor; - public BraveClientResponseInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor) { - this.clientRequestInterceptor = clientRequestInterceptor; + public BraveClientResponseInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { + this.clientResponseInterceptor = clientResponseInterceptor; } @Override public void handle(Object response) { - if (!(response instanceof Response)) { + if (!(response instanceof DecodeableRpcResult)) { return; } - Response res = (Response) response; + DecodeableRpcResult result = (DecodeableRpcResult) response; + clientResponseInterceptor.handle(new BraveClientResponseAdapter(new BraveRpcResult(result))); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java new file mode 100644 index 00000000000..27a96621ce7 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java @@ -0,0 +1,24 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.rpc.RpcInvocation; + +public class BraveRpcInvocation { + + private final RpcInvocation rpcInvocation; + + public BraveRpcInvocation(RpcInvocation rpcInvocation) { + this.rpcInvocation = rpcInvocation; + } + + public void addAttachment(String key, String value) { + rpcInvocation.setAttachment(key, value); + } + + public String providerAddress() { + return rpcInvocation.getInvoker().getUrl().getAddress(); + } + + public RpcInvocation getRpcInvocation() { + return rpcInvocation; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java new file mode 100644 index 00000000000..902501ad9be --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java @@ -0,0 +1,12 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.rpc.protocol.dubbo.DecodeableRpcResult; + +public class BraveRpcResult { + + private final DecodeableRpcResult rpcResult; + + public BraveRpcResult(DecodeableRpcResult rpcResult) { + this.rpcResult = rpcResult; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java index eada44734e3..84615c0fdff 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java @@ -1,98 +1,49 @@ package com.alibaba.dubbo.tracker.zipkin; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; import com.alibaba.dubbo.tracker.ClientResponseInterceptor; import com.alibaba.dubbo.tracker.DubboSpanNameProvider; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.filter.ServletFilter; import com.alibaba.dubbo.tracker.zipkin.filter.BraveServletFilter; -import com.github.kristofa.brave.*; +import com.github.kristofa.brave.Brave; import com.github.kristofa.brave.http.DefaultSpanNameProvider; -import com.github.kristofa.brave.http.HttpSpanCollector; -import com.github.kristofa.brave.kafka.KafkaSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; /** * @author Xs */ public class BraveRpcTracker implements RpcTracker { - private final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); + private final BraveClientRequestInterceptor clientRequestInterceptor; - private final BraveClientRequestInterceptor requestInterceptor; + private final BraveClientResponseInterceptor clientResponseInterceptor; private final BraveServletFilter braveServletFilter; - BraveRpcTracker create(URL url) { + static BraveRpcTracker create(URL url) { return new BraveRpcTracker(url); } private BraveRpcTracker(URL url) { - Brave.Builder builder = new Brave.Builder(url.getParameter("service-name", "demo")); - builder.spanCollector(createSpanCollector(url)); - builder.traceSampler(createSampler(url)); + Brave.Builder builder = new Brave.Builder(url.getParameter("application", "demo")); + builder.spanCollector(SpanCollectorFactory.create(url)); + builder.traceSampler(SamplerFactory.create(url)); Brave brave = builder.build(); - requestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new DubboSpanNameProvider()); + clientRequestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new DubboSpanNameProvider()); + clientResponseInterceptor = new BraveClientResponseInterceptor(brave.clientResponseInterceptor()); braveServletFilter = new BraveServletFilter(new com.github.kristofa.brave.servlet.BraveServletFilter( brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider())); } - private SpanCollector createSpanCollector(URL url) { - String collector = url.getParameter("collector", "http"); - if (collector.equals("http")) { - HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); - - String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); - - return HttpSpanCollector.create(baseUrl, config, DEFAULT_HANDLER); - - } else if (collector.equals("kafka")) { - - return KafkaSpanCollector.create(url.getHost() + ":" + url.getPort(), DEFAULT_HANDLER); - - } else if (collector.equals("scribe")) { - - ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); - - params.setMetricsHandler(DEFAULT_HANDLER); - - return new ScribeSpanCollector(url.getHost(), url.getPort(), params); - } else { - throw new IllegalArgumentException("unknown collector type, collector: " + collector); - } - } - - private Sampler createSampler(URL url) { - String sampler = url.getParameter("sampler"); - if (StringUtils.isEmpty(sampler)) { - return Sampler.ALWAYS_SAMPLE; - } else { - String rate = url.getParameter("rate"); - if (StringUtils.isEmpty(rate)) { - throw new IllegalArgumentException("sample rate must not be null"); - } - if (sampler.equals("counting")) { - return CountingSampler.create(Float.valueOf(rate)); - } else if (sampler.equals("boundary")) { - return BoundarySampler.create(Float.valueOf(rate)); - } else { - throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); - } - } - } - - @Override - public ClientRequestInterceptor requestInterceptor() { - return requestInterceptor; + public ClientRequestInterceptor clientRequestInterceptor() { + return clientRequestInterceptor; } @Override - public ClientResponseInterceptor responseInterceptor() { - return null; + public ClientResponseInterceptor clientResponseInterceptor() { + return clientResponseInterceptor; } @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index 6adac2dcdb7..7e4a2966d03 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -12,11 +12,10 @@ public class BraveRpcTrackerFactory implements RpcTrackerFactory { private volatile BraveRpcTracker braveRpcTracker; @Override - public synchronized RpcTracker createRpcTracker(URL url) { - if (braveRpcTracker != null) { - return braveRpcTracker; + public RpcTracker createRpcTracker(URL url) { + if (braveRpcTracker == null) { + braveRpcTracker = BraveRpcTracker.create(url); } - braveRpcTracker = BraveRpcTracker.create(url); return braveRpcTracker; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java new file mode 100644 index 00000000000..6d885268d20 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java @@ -0,0 +1,29 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.github.kristofa.brave.BoundarySampler; +import com.github.kristofa.brave.CountingSampler; +import com.github.kristofa.brave.Sampler; + +public class SamplerFactory { + + public static Sampler create(URL url) { + String sampler = url.getParameter("sampler"); + if (StringUtils.isEmpty(sampler)) { + return Sampler.ALWAYS_SAMPLE; + } else { + String rate = url.getParameter("rate"); + if (StringUtils.isEmpty(rate)) { + throw new IllegalArgumentException("sample rate must not be null"); + } + if (sampler.equals("counting")) { + return CountingSampler.create(Float.valueOf(rate)); + } else if (sampler.equals("boundary")) { + return BoundarySampler.create(Float.valueOf(rate)); + } else { + throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); + } + } + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java new file mode 100644 index 00000000000..2f7aa0d8289 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java @@ -0,0 +1,31 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.github.kristofa.brave.SpanCollector; +import com.github.kristofa.brave.SpanCollectorMetricsHandler; +import com.github.kristofa.brave.http.HttpSpanCollector; +import com.github.kristofa.brave.kafka.KafkaSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; + +public class SpanCollectorFactory { + + private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); + + public static SpanCollector create(URL url){ + String collector = url.getParameter("collector", "http"); + if (collector.equals("http")) { + HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); + String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); + return HttpSpanCollector.create(baseUrl, config, DEFAULT_HANDLER); + } else if (collector.equals("kafka")) { + return KafkaSpanCollector.create(url.getHost() + ":" + url.getPort(), DEFAULT_HANDLER); + } else if (collector.equals("scribe")) { + ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); + params.setMetricsHandler(DEFAULT_HANDLER); + return new ScribeSpanCollector(url.getHost(), url.getPort(), params); + } else { + throw new IllegalArgumentException("unknown collector type, collector: " + collector); + } + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java index c38f540e2d3..3bf84c41187 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java @@ -2,13 +2,12 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.TrackerManager; import com.alibaba.dubbo.tracker.filter.ClientRpcTrackerFilter; /** @@ -17,16 +16,12 @@ @Activate(group = Constants.CONSUMER, order = Integer.MAX_VALUE) public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { - private static final Logger logger = LoggerFactory.getLogger(BraveClientRpcTrackerFilter.class); - - private RpcTrackerFactory rpcTrackerFactory; - - public void setRpcTrackerFactory(RpcTrackerFactory rpcTrackerFactory) { - this.rpcTrackerFactory = rpcTrackerFactory; - } - @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - return invoker.invoke(invocation); + RpcTracker rpcTracker = TrackerManager.mockRpcTracker("consumer"); + rpcTracker.clientRequestInterceptor().handle(invocation); + Result result = invoker.invoke(invocation); + rpcTracker.clientResponseInterceptor().handle(result); + return result; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java index 055e1393234..4c5f1893ef3 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java @@ -6,7 +6,6 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.filter.ServerRpcTrackerFilter; /** @@ -15,14 +14,9 @@ @Activate(group = Constants.PROVIDER, order = Integer.MIN_VALUE) public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { - private RpcTrackerFactory rpcTrackerFactory; - - public void setRpcTrackerFactory(RpcTrackerFactory rpcTrackerFactory) { - this.rpcTrackerFactory = rpcTrackerFactory; - } - @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - return invoker.invoke(invocation); + Result result = invoker.invoke(invocation); + return result; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java index b964c96c479..2701c002aa5 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java @@ -1,7 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin.test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.TrackerManager; @@ -19,8 +18,9 @@ public void test_rpc_factory() { @Test public void test_create_tracker() { - RpcTrackerFactory factory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); - URL url = URL.valueOf("zipkin://localhost:9411?service-name=test&collector=http&sampler=counting&rate=0.2"); - RpcTracker rpcTracker = factory.createRpcTracker(url); + RpcTrackerFactory factory = TrackerManager.getTrackerFactory(); + URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); + RpcTracker rpcTracker = TrackerManager.create(url); + Assert.assertEquals(rpcTracker, TrackerManager.getRpcTracker()); } } From b4e8085733c86d42939298d8722cc558fe955909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Fri, 13 Jan 2017 19:35:21 +0800 Subject: [PATCH 07/69] add rpc request ... --- .../dubbo/demo/consumer/DemoAction.java | 12 +- .../META-INF/spring/dubbo-demo-action.xml | 2 +- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../AnnotationDrivenUserRestServiceImpl.java | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 28 ++-- .../protocol/dubbo/filter/FutureFilter.java | 122 +++++++++--------- .../tracker/ClientRequestInterceptor.java | 2 +- ...r.java => InvocationSpanNameProvider.java} | 2 +- .../com/alibaba/dubbo/tracker/RpcRequest.java | 25 ++++ .../alibaba/dubbo/tracker/RpcResponse.java | 24 ++++ .../com/alibaba/dubbo/tracker/RpcTracker.java | 4 + .../tracker/ServerRequestInterceptor.java | 6 + .../tracker/ServerResponseInterceptor.java | 6 + .../alibaba/dubbo/tracker/TrackerKeys.java | 3 + .../zipkin/BraveClientRequestAdapter.java | 11 +- .../zipkin/BraveClientRequestInterceptor.java | 15 +-- .../zipkin/BraveClientResponseAdapter.java | 7 +- .../BraveClientResponseInterceptor.java | 5 +- .../tracker/zipkin/BraveRpcInvocation.java | 11 ++ .../dubbo/tracker/zipkin/BraveRpcResult.java | 21 ++- .../dubbo/tracker/zipkin/BraveRpcTracker.java | 24 +++- .../zipkin/BraveServerRequestAdapter.java | 65 ++++++++++ .../zipkin/BraveServerRequestInterceptor.java | 24 ++++ .../zipkin/BraveServerResponseAdapter.java | 29 +++++ .../BraveServerResponseInterceptor.java | 19 +++ .../filter/BraveClientRpcTrackerFilter.java | 3 +- .../filter/BraveServerRpcTrackerFilter.java | 6 + 27 files changed, 366 insertions(+), 114 deletions(-) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{DubboSpanNameProvider.java => InvocationSpanNameProvider.java} (82%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java index b6138e729ad..9a617b7a78f 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java @@ -78,12 +78,12 @@ public void start() throws Exception { System.out.println("SUCCESS: caught exception " + e.getClass()); } - User user = new User(1L, "larrypage"); - System.out.println("SUCCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); - - RpcContext.getContext().setAttachment("clientName", "demo"); - RpcContext.getContext().setAttachment("clientImpl", "dubbox"); - System.out.println("SUCCESS: got user " + anotherUserRestService.getUser(1L)); +// User user = new User(1L, "larrypage"); +// System.out.println("SUCCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); +// +// RpcContext.getContext().setAttachment("clientName", "demo"); +// RpcContext.getContext().setAttachment("clientImpl", "dubbox"); +// System.out.println("SUCCESS: got user " + anotherUserRestService.getUser(1L)); } } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml index fb7662ca000..3d4725c8393 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml @@ -22,7 +22,7 @@ - + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 6dd555c68f9..b369bc867fc 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -13,7 +13,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java index e7dd278dacd..b9694a17bc1 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java @@ -32,7 +32,7 @@ /** * @author lishen */ -@Service(protocol = {"rest", "dubbo"}, group = "annotationConfig", validation = "true") +//@Service(protocol = {"rest", "dubbo"}, group = "annotationConfig", validation = "true") @Path("customers") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 265645ab00b..b35732046b4 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -30,7 +30,7 @@ - + @@ -47,28 +47,28 @@ - + + + + + + + - + - + - + - + - - + + diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index cc5cf7d9998..9b907daaad1 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -15,28 +15,23 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo.filter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.Future; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.remoting.exchange.ResponseCallback; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.StaticContext; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter; import com.alibaba.dubbo.rpc.support.RpcUtils; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.Future; + /** * EventFilter + * * @author chao.liuc * @author william.liangf */ @@ -46,9 +41,9 @@ public class FutureFilter implements Filter { protected static final Logger logger = LoggerFactory.getLogger(FutureFilter.class); public Result invoke(final Invoker invoker, final Invocation invocation) throws RpcException { - final boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation); - - fireInvokeCallback(invoker, invocation); + final boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation); + + fireInvokeCallback(invoker, invocation); //需要在调用前配置好是否有返回值,已供invoker判断是否需要返回future. Result result = invoker.invoke(invocation); if (isAsync) { @@ -66,20 +61,20 @@ private void syncCallback(final Invoker invoker, final Invocation invocation, fireReturnCallback(invoker, invocation, result.getValue()); } } - + private void asyncCallback(final Invoker invoker, final Invocation invocation) { Future f = RpcContext.getContext().getFuture(); if (f instanceof FutureAdapter) { - ResponseFuture future = ((FutureAdapter)f).getFuture(); + ResponseFuture future = ((FutureAdapter) f).getFuture(); future.setCallback(new ResponseCallback() { public void done(Object rpcResult) { - if (rpcResult == null){ - logger.error(new IllegalStateException("invalid result value : null, expected "+Result.class.getName())); + if (rpcResult == null) { + logger.error(new IllegalStateException("invalid result value : null, expected " + Result.class.getName())); return; } ///must be rpcResult - if (! (rpcResult instanceof Result)){ - logger.error(new IllegalStateException("invalid result type :" + rpcResult.getClass() + ", expected "+Result.class.getName())); + if (!(rpcResult instanceof Result)) { + logger.error(new IllegalStateException("invalid result type :" + rpcResult.getClass() + ", expected " + Result.class.getName())); return; } Result result = (Result) rpcResult; @@ -89,6 +84,7 @@ public void done(Object rpcResult) { fireReturnCallback(invoker, invocation, result.getValue()); } } + public void caught(Throwable exception) { fireThrowCallback(invoker, invocation, exception); } @@ -97,19 +93,19 @@ public void caught(Throwable exception) { } private void fireInvokeCallback(final Invoker invoker, final Invocation invocation) { - final Method onInvokeMethod = (Method)StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_METHOD_KEY)); + final Method onInvokeMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_METHOD_KEY)); final Object onInvokeInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_INSTANCE_KEY)); - - if (onInvokeMethod == null && onInvokeInst == null ){ - return ; + + if (onInvokeMethod == null && onInvokeInst == null) { + return; } - if (onInvokeMethod == null || onInvokeInst == null ){ - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() +" has a onreturn callback config , but no such "+(onInvokeMethod == null ? "method" : "instance")+" found. url:"+invoker.getUrl()); + if (onInvokeMethod == null || onInvokeInst == null) { + throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } - if (onInvokeMethod != null && ! onInvokeMethod.isAccessible()) { + if (onInvokeMethod != null && !onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); } - + Object[] params = invocation.getArguments(); try { onInvokeMethod.invoke(onInvokeInst, params); @@ -119,38 +115,38 @@ private void fireInvokeCallback(final Invoker invoker, final Invocation invoc fireThrowCallback(invoker, invocation, e); } } - + private void fireReturnCallback(final Invoker invoker, final Invocation invocation, final Object result) { - final Method onReturnMethod = (Method)StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_METHOD_KEY)); + final Method onReturnMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_METHOD_KEY)); final Object onReturnInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_INSTANCE_KEY)); //not set onreturn callback - if (onReturnMethod == null && onReturnInst == null ){ - return ; + if (onReturnMethod == null && onReturnInst == null) { + return; } - - if (onReturnMethod == null || onReturnInst == null ){ - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() +" has a onreturn callback config , but no such "+(onReturnMethod == null ? "method" : "instance")+" found. url:"+invoker.getUrl()); + + if (onReturnMethod == null || onReturnInst == null) { + throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } - if (onReturnMethod != null && ! onReturnMethod.isAccessible()) { + if (onReturnMethod != null && !onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } - + Object[] args = invocation.getArguments(); - Object[] params ; - Class[] rParaTypes = onReturnMethod.getParameterTypes() ; - if (rParaTypes.length >1 ) { - if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)){ + Object[] params; + Class[] rParaTypes = onReturnMethod.getParameterTypes(); + if (rParaTypes.length > 1) { + if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = result; - params[1] = args ; - }else { + params[1] = args; + } else { params = new Object[args.length + 1]; params[0] = result; System.arraycopy(args, 0, params, 1, args.length); } } else { - params = new Object[] { result }; + params = new Object[]{result}; } try { onReturnMethod.invoke(onReturnInst, params); @@ -160,46 +156,46 @@ private void fireReturnCallback(final Invoker invoker, final Invocation invoc fireThrowCallback(invoker, invocation, e); } } - + private void fireThrowCallback(final Invoker invoker, final Invocation invocation, final Throwable exception) { - final Method onthrowMethod = (Method)StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_METHOD_KEY)); + final Method onthrowMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_METHOD_KEY)); final Object onthrowInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_INSTANCE_KEY)); //没有设置onthrow callback. - if (onthrowMethod == null && onthrowInst == null ){ - return ; + if (onthrowMethod == null && onthrowInst == null) { + return; } - if (onthrowMethod == null || onthrowInst == null ){ - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() +" has a onthrow callback config , but no such "+(onthrowMethod == null ? "method" : "instance")+" found. url:"+invoker.getUrl()); + if (onthrowMethod == null || onthrowInst == null) { + throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } - if (onthrowMethod != null && ! onthrowMethod.isAccessible()) { + if (!onthrowMethod.isAccessible()) { onthrowMethod.setAccessible(true); } - Class[] rParaTypes = onthrowMethod.getParameterTypes() ; - if (rParaTypes[0].isAssignableFrom(exception.getClass())){ + Class[] rParaTypes = onthrowMethod.getParameterTypes(); + if (rParaTypes[0].isAssignableFrom(exception.getClass())) { try { Object[] args = invocation.getArguments(); Object[] params; - - if (rParaTypes.length >1 ) { - if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)){ + + if (rParaTypes.length > 1) { + if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = exception; - params[1] = args ; - }else { + params[1] = args; + } else { params = new Object[args.length + 1]; params[0] = exception; System.arraycopy(args, 0, params, 1, args.length); } } else { - params = new Object[] { exception }; + params = new Object[]{exception}; } - onthrowMethod.invoke(onthrowInst,params); + onthrowMethod.invoke(onthrowInst, params); } catch (Throwable e) { - logger.error(invocation.getMethodName() +".call back method invoke error . callback method :" + onthrowMethod + ", url:"+ invoker.getUrl(), e); - } + logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); + } } else { - logger.error(invocation.getMethodName() +".call back method invoke error . callback method :" + onthrowMethod + ", url:"+ invoker.getUrl(), exception); + logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); } } } \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java index 0e0ae848d69..f5cf6b3adb3 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java @@ -5,5 +5,5 @@ */ public interface ClientRequestInterceptor { - void handle(Object request); + void handle(RpcRequest request); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java similarity index 82% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java index 5dd4fa93d7c..5cb41096ba4 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java @@ -5,7 +5,7 @@ /** * @author Xs */ -public class DubboSpanNameProvider { +public class InvocationSpanNameProvider { public String spanName(Invocation invocation) { return invocation.getMethodName(); diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java new file mode 100644 index 00000000000..6c38a6b326a --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java @@ -0,0 +1,25 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; + +public class RpcRequest { + + private final Invoker invoker; + + private final Invocation invocation; + + public RpcRequest(Invoker invoker, Invocation invocation) { + this.invoker = invoker; + this.invocation = invocation; + } + + public Invoker getInvoker() { + return invoker; + } + + public Invocation getInvocation() { + return invocation; + } + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java new file mode 100644 index 00000000000..c963bfac501 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java @@ -0,0 +1,24 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; + +public class RpcResponse { + + private final Invoker invoker; + + private final Result result; + + public RpcResponse(Invoker invoker, Result result) { + this.invoker = invoker; + this.result = result; + } + + public Invoker getInvoker() { + return invoker; + } + + public Result getResult() { + return result; + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index bf76278a679..a05b29bb8e3 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -11,5 +11,9 @@ public interface RpcTracker { ClientResponseInterceptor clientResponseInterceptor(); + ServerRequestInterceptor serverRequestInterceptor(); + + ServerResponseInterceptor serverResponseInterceptor(); + ServletFilter servletFilter(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java new file mode 100644 index 00000000000..9f80836d20f --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.tracker; + +public interface ServerRequestInterceptor { + + void handle(RpcRequest request); +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java new file mode 100644 index 00000000000..dc847536278 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.tracker; + +public interface ServerResponseInterceptor { + + void handle(RpcResponse response); +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java index 3e915c4d081..a8b8b3cf080 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java @@ -7,4 +7,7 @@ public class TrackerKeys { public static final String PROVIDER_ADDR = "provider.address"; + public static final String RETURN_STATUS = "return.status"; + + } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java index 0e20e55f81f..2986aaf9dc2 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java @@ -1,7 +1,8 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.DubboSpanNameProvider; +import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.RpcRequest; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientRequestAdapter; import com.github.kristofa.brave.IdConversion; @@ -17,12 +18,12 @@ */ public class BraveClientRequestAdapter implements ClientRequestAdapter { - private final DubboSpanNameProvider spanNameProvider; + private final InvocationSpanNameProvider spanNameProvider; - private final BraveRpcInvocation invocation; + private final RpcRequest rpcRequest; - public BraveClientRequestAdapter(BraveRpcInvocation invocation, DubboSpanNameProvider spanNameProvider) { - this.invocation = invocation; + public BraveClientRequestAdapter(RpcRequest rpcRequest, InvocationSpanNameProvider spanNameProvider) { + this.rpcRequest = rpcRequest; this.spanNameProvider = spanNameProvider; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java index ac48785fb5b..9b347feb124 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java @@ -2,7 +2,8 @@ import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.DubboSpanNameProvider; +import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcRequest; /** * @author Xs @@ -11,20 +12,16 @@ public class BraveClientRequestInterceptor implements ClientRequestInterceptor { private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; - private final DubboSpanNameProvider spanNameProvider; + private final InvocationSpanNameProvider spanNameProvider; public BraveClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor, - DubboSpanNameProvider spanNameProvider) { + InvocationSpanNameProvider spanNameProvider) { this.clientRequestInterceptor = clientRequestInterceptor; this.spanNameProvider = spanNameProvider; } @Override - public void handle(Object request) { - if (!(request instanceof RpcInvocation)) { - return; - } - RpcInvocation invocation = (RpcInvocation) request; - clientRequestInterceptor.handle(new BraveClientRequestAdapter(new BraveRpcInvocation(invocation), spanNameProvider)); + public void handle(RpcRequest request) { + clientRequestInterceptor.handle(new BraveClientRequestAdapter(request, spanNameProvider)); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java index 39ee2ed9f37..6afceaee7fa 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; +import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientResponseAdapter; import com.github.kristofa.brave.KeyValueAnnotation; @@ -19,7 +20,11 @@ public BraveClientResponseAdapter(BraveRpcResult rpcResult) { @Override public Collection responseAnnotations() { + if (rpcResult.hasException()) { + KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResult.exception()); + return Collections.singletonList(statusAnnotation); + } + return Collections.emptyList(); - return Collections.EMPTY_LIST; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java index 9fa0480ed2b..0e01e96adb7 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; +import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.protocol.dubbo.DecodeableRpcResult; import com.alibaba.dubbo.tracker.ClientResponseInterceptor; @@ -17,10 +18,10 @@ public BraveClientResponseInterceptor(com.github.kristofa.brave.ClientResponseIn @Override public void handle(Object response) { - if (!(response instanceof DecodeableRpcResult)) { + if (!(response instanceof RpcResult)) { return; } - DecodeableRpcResult result = (DecodeableRpcResult) response; + RpcResult result = (RpcResult) response; clientResponseInterceptor.handle(new BraveClientResponseAdapter(new BraveRpcResult(result))); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java index 27a96621ce7..31727848102 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; +import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; public class BraveRpcInvocation { @@ -14,7 +15,17 @@ public void addAttachment(String key, String value) { rpcInvocation.setAttachment(key, value); } + + public String getAttachment(String key) { + return rpcInvocation.getAttachment(key); + } + public String providerAddress() { + String address; + Invoker invoker = rpcInvocation.getInvoker(); + if (invoker == null){ + + } return rpcInvocation.getInvoker().getUrl().getAddress(); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java index 902501ad9be..2d2904b23ac 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java @@ -1,12 +1,27 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.rpc.protocol.dubbo.DecodeableRpcResult; +import com.alibaba.dubbo.rpc.RpcResult; public class BraveRpcResult { - private final DecodeableRpcResult rpcResult; + private final RpcResult rpcResult; - public BraveRpcResult(DecodeableRpcResult rpcResult) { + public BraveRpcResult(RpcResult rpcResult) { this.rpcResult = rpcResult; } + + public boolean hasException() { + return rpcResult.hasException(); + } + + public String exception() { + if (!hasException()) { + return "result OK"; + } + Throwable throwable = rpcResult.getException(); + if (throwable instanceof NullPointerException) { + return "NullPointerException"; + } + return throwable.getMessage(); + } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java index 84615c0fdff..d74e8e4094e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java @@ -1,10 +1,7 @@ package com.alibaba.dubbo.tracker.zipkin; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; -import com.alibaba.dubbo.tracker.DubboSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.*; import com.alibaba.dubbo.tracker.filter.ServletFilter; import com.alibaba.dubbo.tracker.zipkin.filter.BraveServletFilter; import com.github.kristofa.brave.Brave; @@ -19,6 +16,11 @@ public class BraveRpcTracker implements RpcTracker { private final BraveClientResponseInterceptor clientResponseInterceptor; + private final BraveServerRequestInterceptor serverRequestInterceptor; + + private final BraveServerResponseInterceptor serverResponseInterceptor; + + private final BraveServletFilter braveServletFilter; static BraveRpcTracker create(URL url) { @@ -30,8 +32,10 @@ private BraveRpcTracker(URL url) { builder.spanCollector(SpanCollectorFactory.create(url)); builder.traceSampler(SamplerFactory.create(url)); Brave brave = builder.build(); - clientRequestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new DubboSpanNameProvider()); + clientRequestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new InvocationSpanNameProvider()); clientResponseInterceptor = new BraveClientResponseInterceptor(brave.clientResponseInterceptor()); + serverRequestInterceptor = new BraveServerRequestInterceptor(brave.serverRequestInterceptor(), new InvocationSpanNameProvider()); + serverResponseInterceptor = new BraveServerResponseInterceptor(brave.serverResponseInterceptor()); braveServletFilter = new BraveServletFilter(new com.github.kristofa.brave.servlet.BraveServletFilter( brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider())); } @@ -46,6 +50,16 @@ public ClientResponseInterceptor clientResponseInterceptor() { return clientResponseInterceptor; } + @Override + public ServerRequestInterceptor serverRequestInterceptor() { + return serverRequestInterceptor; + } + + @Override + public ServerResponseInterceptor serverResponseInterceptor() { + return serverResponseInterceptor; + } + @Override public ServletFilter servletFilter() { return braveServletFilter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java new file mode 100644 index 00000000000..875aca9c9f3 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java @@ -0,0 +1,65 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.ServerRequestAdapter; +import com.github.kristofa.brave.SpanId; +import com.github.kristofa.brave.TraceData; + +import java.util.Collection; +import java.util.Collections; + +import static com.github.kristofa.brave.IdConversion.convertToLong; + +public class BraveServerRequestAdapter implements ServerRequestAdapter { + + private final InvocationSpanNameProvider spanNameProvider; + + private final RpcRequest rpcRequest; + + public BraveServerRequestAdapter(RpcRequest rpcRequest, InvocationSpanNameProvider spanNameProvider) { + this.spanNameProvider = spanNameProvider; + this.rpcRequest = rpcRequest; + } + + @Override + public TraceData getTraceData() { + final String sampled = invocation.getAttachment(RpcAttachment.Sampled.getName()); + if (sampled != null) { + if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { + return TraceData.builder().sample(false).build(); + } else { + final String parentSpanId = invocation.getAttachment(RpcAttachment.ParentSpanId.getName()); + final String traceId = invocation.getAttachment(RpcAttachment.TraceId.getName()); + final String spanId = invocation.getAttachment(RpcAttachment.SpanId.getName()); + + if (traceId != null && spanId != null) { + SpanId span = getSpanId(traceId, spanId, parentSpanId); + return TraceData.builder().sample(true).spanId(span).build(); + } + } + } + return TraceData.builder().build(); + } + + @Override + public String getSpanName() { + return spanNameProvider.spanName(invocation.getRpcInvocation()); + } + + @Override + public Collection requestAnnotations() { + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, invocation.providerAddress()); + return Collections.singletonList(annotation); + } + + private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { + return SpanId.builder() + .traceId(convertToLong(traceId)) + .spanId(convertToLong(spanId)) + .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java new file mode 100644 index 00000000000..070f26141e0 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java @@ -0,0 +1,24 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.ServerRequestInterceptor; + +public class BraveServerRequestInterceptor implements ServerRequestInterceptor { + + private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; + + private final InvocationSpanNameProvider spanNameProvider; + + public BraveServerRequestInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor, + InvocationSpanNameProvider spanNameProvider) { + this.serverRequestInterceptor = serverRequestInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public void handle(RpcRequest request) { + serverRequestInterceptor.handle(new BraveServerRequestAdapter(request,spanNameProvider)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java new file mode 100644 index 00000000000..950d224becf --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java @@ -0,0 +1,29 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.RpcResponse; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.ServerResponseAdapter; + +import java.util.Collection; +import java.util.Collections; + +public class BraveServerResponseAdapter implements ServerResponseAdapter { + + private final RpcResponse rpcResponse; + + public BraveServerResponseAdapter(RpcResponse rpcResponse) { + this.rpcResponse = rpcResponse; + } + + @Override + public Collection responseAnnotations() { + KeyValueAnnotation statusAnnotation; + if (rpcResult.hasException()) { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResult.exception()); + } else { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); + } + return Collections.singletonList(statusAnnotation); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java new file mode 100644 index 00000000000..0f024ca33df --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.tracker.zipkin; + + +import com.alibaba.dubbo.tracker.RpcResponse; +import com.alibaba.dubbo.tracker.ServerResponseInterceptor; + +public class BraveServerResponseInterceptor implements ServerResponseInterceptor { + + private final com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor; + + public BraveServerResponseInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { + this.serverResponseInterceptor = serverResponseInterceptor; + } + + @Override + public void handle(RpcResponse response) { + serverResponseInterceptor.handle(new BraveServerResponseAdapter(response)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java index 3bf84c41187..1c3386bdf85 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java @@ -6,6 +6,7 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.tracker.RpcRequest; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.TrackerManager; import com.alibaba.dubbo.tracker.filter.ClientRpcTrackerFilter; @@ -19,7 +20,7 @@ public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { RpcTracker rpcTracker = TrackerManager.mockRpcTracker("consumer"); - rpcTracker.clientRequestInterceptor().handle(invocation); + rpcTracker.clientRequestInterceptor().handle(new RpcRequest(invoker, invocation)); Result result = invoker.invoke(invocation); rpcTracker.clientResponseInterceptor().handle(result); return result; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java index 4c5f1893ef3..a41e47fdde7 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java @@ -6,6 +6,9 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.TrackerManager; import com.alibaba.dubbo.tracker.filter.ServerRpcTrackerFilter; /** @@ -16,7 +19,10 @@ public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + RpcTracker rpcTracker = TrackerManager.mockRpcTracker("provider"); + rpcTracker.serverRequestInterceptor().handle(new RpcRequest(invoker, invocation)); Result result = invoker.invoke(invocation); + rpcTracker.serverResponseInterceptor().handle(result); return result; } } From 529ac47f7e0eaf9476a3da31395eeb8305ee3464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Mon, 16 Jan 2017 16:19:07 +0800 Subject: [PATCH 08/69] add OkHttpInvokerRequestExecutor --- dubbo-rpc/dubbo-rpc-http/pom.xml | 4 ++ .../dubbo/rpc/protocol/http/HttpProtocol.java | 2 + .../http/OkHttpInvokerRequestExecutor.java | 46 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index a2ad7c134f3..33e8f4d1cc2 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -47,5 +47,9 @@ org.springframework spring-web + + com.squareup.okhttp3 + okhttp + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java index f7f968cf54f..93b89e571e5 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java @@ -129,6 +129,8 @@ protected void prepareConnection(HttpURLConnection con, CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); + } else if ("okHttpClient".equals(client)) { + httpProxyFactoryBean.setHttpInvokerRequestExecutor(new OkHttpInvokerRequestExecutor(url)); } else if (client.length() > 0) { throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); } diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java new file mode 100644 index 00000000000..9c66643578b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java @@ -0,0 +1,46 @@ +package com.alibaba.dubbo.rpc.protocol.http; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import okhttp3.*; +import org.springframework.context.i18n.LocaleContext; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.remoting.httpinvoker.AbstractHttpInvokerRequestExecutor; +import org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration; +import org.springframework.remoting.support.RemoteInvocationResult; +import org.springframework.util.StringUtils; + +import java.io.ByteArrayOutputStream; +import java.util.concurrent.TimeUnit; + +public class OkHttpInvokerRequestExecutor extends AbstractHttpInvokerRequestExecutor { + + private final OkHttpClient client; + + public OkHttpInvokerRequestExecutor(URL url) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + client = builder.build(); + } + + @Override + protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { + Request request = createPostRequest(config, baos); + Response response = client.newCall(request).execute(); + return readRemoteInvocationResult(response.body().byteStream(), config.getCodebaseUrl()); + } + + private Request createPostRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) { + Request.Builder builder = new Request.Builder().url(config.getServiceUrl()); + LocaleContext locale = LocaleContextHolder.getLocaleContext(); + if (locale != null) { + builder.addHeader(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale.getLocale())); + } + if (isAcceptGzipEncoding()) { + builder.addHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP); + } + RequestBody requestBody = RequestBody.create(MediaType.parse(getContentType()), baos.toByteArray()); + return builder.post(requestBody).build(); + } +} From 9f5b46da10b60c3ab265a202a3b293d6823d2898 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 16 Jan 2017 23:20:50 +0800 Subject: [PATCH 09/69] confused --- .../java/com/alibaba/dubbo/common/URL.java | 592 +++++++------- .../dubbo/common/bytecode/ClassGenerator.java | 648 +++++++-------- .../dubbo/common/bytecode/Wrapper.java | 761 +++++++++--------- .../META-INF/spring/dubbo-demo-provider.xml | 8 +- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 58 +- .../javassist/JavassistProxyFactory.java | 46 +- .../wrapper/StubProxyFactoryWrapper.java | 2 +- .../rpc/protocol/dubbo/DubboProtocol.java | 2 +- .../dubbo/rpc/protocol/http/HttpProtocol.java | 7 +- .../protocol/memcached/MemcachedProtocol.java | 4 +- .../rpc/protocol/redis/RedisProtocol.java | 54 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 10 +- .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 17 +- .../rpc/protocol/thrift/ThriftInvoker.java | 51 +- .../tracker/ClientResponseInterceptor.java | 10 - ...ava => ConsumerInvocationInterceptor.java} | 2 +- .../tracker/ConsumerResultInterceptor.java | 10 + .../dubbo/tracker/HttpTrackerComponent.java | 8 + .../dubbo/tracker/InvocationInterceptor.java | 11 + .../tracker/InvocationSpanNameProvider.java | 13 - ...ava => ProviderInvocationInterceptor.java} | 2 +- ...or.java => ProviderResultInterceptor.java} | 2 +- .../alibaba/dubbo/tracker/RpcAttachment.java | 1 - .../com/alibaba/dubbo/tracker/RpcRequest.java | 20 + .../tracker/RpcRequestSpanNameProvider.java | 13 + .../alibaba/dubbo/tracker/RpcResponse.java | 20 + .../com/alibaba/dubbo/tracker/RpcTracker.java | 8 +- .../alibaba/dubbo/tracker/TrackerManager.java | 4 +- .../zipkin/BraveClientRequestAdapter.java | 20 +- .../zipkin/BraveClientRequestInterceptor.java | 27 - .../zipkin/BraveClientResponseAdapter.java | 11 +- .../BraveClientResponseInterceptor.java | 27 - .../BraveConsumerInvocationInterceptor.java | 30 + .../BraveConsumerResultInterceptor.java | 26 + .../BraveProviderInvocationInterceptor.java | 26 + ...va => BraveProviderResultInterceptor.java} | 9 +- .../tracker/zipkin/BraveRpcInvocation.java | 35 - .../dubbo/tracker/zipkin/BraveRpcResult.java | 27 - .../dubbo/tracker/zipkin/BraveRpcTracker.java | 25 +- .../zipkin/BraveServerRequestAdapter.java | 18 +- .../zipkin/BraveServerRequestInterceptor.java | 24 - .../zipkin/BraveServerResponseAdapter.java | 6 +- .../filter/BraveClientRpcTrackerFilter.java | 5 +- .../filter/BraveServerRpcTrackerFilter.java | 5 +- 44 files changed, 1303 insertions(+), 1402 deletions(-) delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ClientRequestInterceptor.java => ConsumerInvocationInterceptor.java} (66%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ServerRequestInterceptor.java => ProviderInvocationInterceptor.java} (60%) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ServerResponseInterceptor.java => ProviderResultInterceptor.java} (63%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{BraveServerResponseInterceptor.java => BraveProviderResultInterceptor.java} (62%) delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java index 6a275e314c8..b2a531d22c5 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java @@ -15,29 +15,22 @@ */ package com.alibaba.dubbo.common; +import com.alibaba.dubbo.common.utils.CollectionUtils; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.StringUtils; + import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URLDecoder; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import com.alibaba.dubbo.common.utils.CollectionUtils; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.StringUtils; - /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) - *

+ *

* url example: *

    *
  • http://www.facebook.com/friends?param1=value1&param2=value2 @@ -45,7 +38,7 @@ *
  • ftp://username:password@192.168.1.7:21/1/read.txt *
  • registry://192.168.1.7:9090/com.alibaba.service1?param1=value1&param2=value2 *
- *

+ *

* Some strange example below: *

    *
  • 192.168.1.3:20880
    @@ -57,13 +50,13 @@ *
  • file:///D:/1/router.js?type=script
    * for this case, url protocol = file, url host = null, url path = D:/1/router.js *
  • file:/D:/1/router.js?type=script
    - * same as above file:///D:/1/router.js?type=script + * same as above file:///D:/1/router.js?type=script *
  • /home/user1/router.js?type=script
    * for this case, url protocol = null, url host = null, url path = home/user1/router.js *
  • home/user1/router.js?type=script
    * for this case, url protocol = null, url host = home, url path = user1/router.js *
- * + * * @author william.liangf * @author ding.lid * @see java.net.URL @@ -75,20 +68,20 @@ public final class URL implements Serializable { private final String protocol; - private final String username; + private final String username; - private final String password; + private final String password; - private final String host; + private final String host; - private final int port; + private final int port; - private final String path; + private final String path; private final Map parameters; - + // ==== cache ==== - + private volatile transient Map numbers; private volatile transient Map urls; @@ -98,11 +91,11 @@ public final class URL implements Serializable { private volatile transient String full; private volatile transient String identity; - + private volatile transient String parameter; private volatile transient String string; - + protected URL() { this.protocol = null; this.username = null; @@ -112,65 +105,65 @@ protected URL() { this.path = null; this.parameters = null; } - - public URL(String protocol, String host, int port) { - this(protocol, null, null, host, port, null, (Map) null); - } - - public URL(String protocol, String host, int port, String[] pairs) { // 变长参数...与下面的path参数冲突,改为数组 + + public URL(String protocol, String host, int port) { + this(protocol, null, null, host, port, null, (Map) null); + } + + public URL(String protocol, String host, int port, String[] pairs) { // 变长参数...与下面的path参数冲突,改为数组 this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } - - public URL(String protocol, String host, int port, Map parameters) { + + public URL(String protocol, String host, int port, Map parameters) { this(protocol, null, null, host, port, null, parameters); } - - public URL(String protocol, String host, int port, String path) { - this(protocol, null, null, host, port, path, (Map) null); - } - public URL(String protocol, String host, int port, String path, String... pairs) { + public URL(String protocol, String host, int port, String path) { + this(protocol, null, null, host, port, path, (Map) null); + } + + public URL(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } - - public URL(String protocol, String host, int port, String path, Map parameters) { - this(protocol, null, null, host, port, path, parameters); - } - - public URL(String protocol, String username, String password, String host, int port, String path) { + + public URL(String protocol, String host, int port, String path, Map parameters) { + this(protocol, null, null, host, port, path, parameters); + } + + public URL(String protocol, String username, String password, String host, int port, String path) { this(protocol, username, password, host, port, path, (Map) null); } - - public URL(String protocol, String username, String password, String host, int port, String path, String... pairs) { - this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); - } - - public URL(String protocol, String username, String password, String host, int port, String path, Map parameters) { - if ((username == null || username.length() == 0) - && password != null && password.length() > 0) { - throw new IllegalArgumentException("Invalid url, password without username!"); - } - this.protocol = protocol; - this.username = username; - this.password = password; - this.host = host; - this.port = (port < 0 ? 0 : port); - this.path = path; - // trim the beginning "/" - while(path != null && path.startsWith("/")) { - path = path.substring(1); - } - if (parameters == null) { - parameters = new HashMap(); - } else { - parameters = new HashMap(parameters); - } - this.parameters = Collections.unmodifiableMap(parameters); - } + + public URL(String protocol, String username, String password, String host, int port, String path, String... pairs) { + this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); + } + + public URL(String protocol, String username, String password, String host, int port, String path, Map parameters) { + if ((username == null || username.length() == 0) + && password != null && password.length() > 0) { + throw new IllegalArgumentException("Invalid url, password without username!"); + } + this.protocol = protocol; + this.username = username; + this.password = password; + this.host = host; + this.port = (port < 0 ? 0 : port); + this.path = path; + // trim the beginning "/" + while (path != null && path.startsWith("/")) { + path = path.substring(1); + } + if (parameters == null) { + parameters = new HashMap(); + } else { + parameters = new HashMap(parameters); + } + this.parameters = Collections.unmodifiableMap(parameters); + } /** * Parse url string - * + * * @param url URL string * @return URL instance * @see URL @@ -205,20 +198,19 @@ public static URL valueOf(String url) { } i = url.indexOf("://"); if (i >= 0) { - if(i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); + if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); - } - else { + } else { // case: file:/path/to/file.txt i = url.indexOf(":/"); - if(i>=0) { - if(i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); + if (i >= 0) { + if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } - + i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); @@ -239,71 +231,71 @@ public static URL valueOf(String url) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } - if(url.length() > 0) host = url; + if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } - public String getProtocol() { - return protocol; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getAuthority() { - if ((username == null || username.length() == 0) - && (password == null || password.length() == 0)) { - return null; - } - return (username == null ? "" : username) - + ":" + (password == null ? "" : password); - } - - public String getHost() { - return host; - } - - /** - * 获取IP地址. - * - * 请注意: - * 如果和Socket的地址对比, - * 或用地址作为Map的Key查找, - * 请使用IP而不是Host, - * 否则配置域名会有问题 - * - * @return ip - */ - public String getIp() { - if (ip == null) { - ip = NetUtils.getIpByHost(host); - } - return ip; - } - - public int getPort() { - return port; - } + public String getProtocol() { + return protocol; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getAuthority() { + if ((username == null || username.length() == 0) + && (password == null || password.length() == 0)) { + return null; + } + return (username == null ? "" : username) + + ":" + (password == null ? "" : password); + } + + public String getHost() { + return host; + } + + /** + * 获取IP地址. + *

+ * 请注意: + * 如果和Socket的地址对比, + * 或用地址作为Map的Key查找, + * 请使用IP而不是Host, + * 否则配置域名会有问题 + * + * @return ip + */ + public String getIp() { + if (ip == null) { + ip = NetUtils.getIpByHost(host); + } + return ip; + } + + public int getPort() { + return port; + } public int getPort(int defaultPort) { return port <= 0 ? defaultPort : port; } - public String getAddress() { - return port <= 0 ? host : host + ":" + port; - } - - public String getBackupAddress() { - return getBackupAddress(0); - } - - public String getBackupAddress(int defaultPort) { - StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort)); + public String getAddress() { + return port <= 0 ? host : host + ":" + port; + } + + public String getBackupAddress() { + return getBackupAddress(0); + } + + public String getBackupAddress(int defaultPort) { + StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort)); String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { for (String backup : backups) { @@ -312,11 +304,11 @@ public String getBackupAddress(int defaultPort) { } } return address.toString(); - } - - public List getBackupUrls() { - List urls = new ArrayList(); - urls.add(this); + } + + public List getBackupUrls() { + List urls = new ArrayList(); + urls.add(this); String[] backups = getParameter(Constants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { for (String backup : backups) { @@ -324,11 +316,11 @@ public List getBackupUrls() { } } return urls; - } + } private String appendDefaultPort(String address, int defaultPort) { if (address != null && address.length() > 0 - && defaultPort > 0) { + && defaultPort > 0) { int i = address.indexOf(':'); if (i < 0) { return address + ":" + defaultPort; @@ -339,20 +331,20 @@ private String appendDefaultPort(String address, int defaultPort) { return address; } - public String getPath() { - return path; - } - - public String getAbsolutePath() { + public String getPath() { + return path; + } + + public String getAbsolutePath() { if (path != null && !path.startsWith("/")) { return "/" + path; } return path; - } - - public URL setProtocol(String protocol) { - return new URL(protocol, username, password, host, port, path, getParameters()); - } + } + + public URL setProtocol(String protocol) { + return new URL(protocol, username, password, host, port, path, getParameters()); + } public URL setUsername(String username) { return new URL(protocol, username, password, host, port, path, getParameters()); @@ -361,7 +353,7 @@ public URL setUsername(String username) { public URL setPassword(String password) { return new URL(protocol, username, password, host, port, path, getParameters()); } - + public URL setAddress(String address) { int i = address.lastIndexOf(':'); String host; @@ -394,7 +386,7 @@ public Map getParameters() { public String getParameterAndDecoded(String key) { return getParameterAndDecoded(key, null); } - + public String getParameterAndDecoded(String key, String defaultValue) { return decode(getParameter(key, defaultValue)); } @@ -422,7 +414,7 @@ public String[] getParameter(String key, String[] defaultValue) { } return Constants.COMMA_SPLIT_PATTERN.split(value); } - + private Map getNumbers() { if (numbers == null) { // 允许并发重复创建 numbers = new ConcurrentHashMap(); @@ -464,7 +456,7 @@ public double getParameter(String key, double defaultValue) { getNumbers().put(key, d); return d; } - + public float getParameter(String key, float defaultValue) { Number n = getNumbers().get(key); if (n != null) { @@ -768,7 +760,7 @@ public long getMethodPositiveParameter(String method, String key, long defaultVa } return value; } - + public int getMethodPositiveParameter(String method, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); @@ -840,22 +832,22 @@ public boolean hasMethodParameter(String method, String key) { String value = getMethodParameter(method, key); return value != null && value.length() > 0; } - + public boolean isLocalHost() { return NetUtils.isLocalHost(host) || getParameter(Constants.LOCALHOST_KEY, false); } - + public boolean isAnyHost() { return Constants.ANYHOST_VALUE.equals(host) || getParameter(Constants.ANYHOST_KEY, false); } - + public URL addParameterAndEncoded(String key, String value) { - if(value == null || value.length() == 0) { + if (value == null || value.length() == 0) { return this; } return addParameter(key, encode(value)); } - + public URL addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } @@ -867,15 +859,15 @@ public URL addParameter(String key, char value) { public URL addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } @@ -883,33 +875,33 @@ public URL addParameter(String key, long value) { public URL addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, Enum value) { - if(value == null) return this; + if (value == null) return this; return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, Number value) { - if(value == null) return this; + if (value == null) return this; return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, CharSequence value) { - if(value == null || value.length() == 0) return this; + if (value == null || value.length() == 0) return this; return addParameter(key, String.valueOf(value)); } - + public URL addParameter(String key, String value) { if (key == null || key.length() == 0 || value == null || value.length() == 0) { return this; } // 如果没有修改,直接返回。 - if(value.equals(getParameters().get(key))) { // value != null + if (value.equals(getParameters().get(key))) { // value != null return this; } @@ -917,7 +909,7 @@ public URL addParameter(String key, String value) { map.put(key, value); return new URL(protocol, username, password, host, port, path, map); } - + public URL addParameterIfAbsent(String key, String value) { if (key == null || key.length() == 0 || value == null || value.length() == 0) { @@ -930,42 +922,42 @@ public URL addParameterIfAbsent(String key, String value) { map.put(key, value); return new URL(protocol, username, password, host, port, path, map); } - - /** - * Add parameters to a new url. - * - * @param parameters - * @return A new URL - */ + + /** + * Add parameters to a new url. + * + * @param parameters + * @return A new URL + */ public URL addParameters(Map parameters) { if (parameters == null || parameters.size() == 0) { return this; } boolean hasAndEqual = true; - for(Map.Entry entry : parameters.entrySet()) { + for (Map.Entry entry : parameters.entrySet()) { String value = getParameters().get(entry.getKey()); - if(value == null && entry.getValue() != null || !value.equals(entry.getValue())) { + if (!entry.getValue().equals(value)) { hasAndEqual = false; break; } } // 如果没有修改,直接返回。 - if(hasAndEqual) return this; + if (hasAndEqual) return this; Map map = new HashMap(getParameters()); map.putAll(parameters); return new URL(protocol, username, password, host, port, path, map); } - - public URL addParametersIfAbsent(Map parameters) { - if (parameters == null || parameters.size() == 0) { - return this; - } - Map map = new HashMap(parameters); - map.putAll(getParameters()); - return new URL(protocol, username, password, host, port, path, map); - } + + public URL addParametersIfAbsent(Map parameters) { + if (parameters == null || parameters.size() == 0) { + return this; + } + Map map = new HashMap(parameters); + map.putAll(getParameters()); + return new URL(protocol, username, password, host, port, path, map); + } public URL addParameters(String... pairs) { if (pairs == null || pairs.length == 0) { @@ -976,35 +968,35 @@ public URL addParameters(String... pairs) { } Map map = new HashMap(); int len = pairs.length / 2; - for (int i = 0; i < len; i ++) { + for (int i = 0; i < len; i++) { map.put(pairs[2 * i], pairs[2 * i + 1]); } return addParameters(map); } - + public URL addParameterString(String query) { if (query == null || query.length() == 0) { return this; } return addParameters(StringUtils.parseQueryString(query)); } - + public URL removeParameter(String key) { if (key == null || key.length() == 0) { return this; } return removeParameters(key); } - + public URL removeParameters(Collection keys) { if (keys == null || keys.size() == 0) { return this; } - return removeParameters(keys.toArray(new String[0])); + return removeParameters(keys.toArray(new String[keys.size()])); } - public URL removeParameters(String... keys) { - if (keys == null || keys.length == 0) { + public URL removeParameters(String... keys) { + if (keys == null || keys.length == 0) { return this; } Map map = new HashMap(getParameters()); @@ -1015,27 +1007,27 @@ public URL removeParameters(String... keys) { return this; } return new URL(protocol, username, password, host, port, path, map); - } - - public URL clearParameters() { + } + + public URL clearParameters() { return new URL(protocol, username, password, host, port, path, new HashMap()); } - - public String getRawParameter(String key) { - if ("protocol".equals(key)) + + public String getRawParameter(String key) { + if ("protocol".equals(key)) return protocol; - if ("username".equals(key)) + if ("username".equals(key)) return username; - if ("password".equals(key)) + if ("password".equals(key)) return password; - if ("host".equals(key)) + if ("host".equals(key)) return host; - if ("port".equals(key)) + if ("port".equals(key)) return String.valueOf(port); - if ("path".equals(key)) + if ("path".equals(key)) return path; return getParameter(key); - } + } public Map toMap() { Map map = new HashMap(parameters); @@ -1054,8 +1046,8 @@ public Map toMap() { return map; } - public String toString() { - if (string != null) { + public String toString() { + if (string != null) { return string; } return string = buildString(false, true); // no show username and password @@ -1064,44 +1056,44 @@ public String toString() { public String toString(String... parameters) { return buildString(false, true, parameters); // no show username and password } - + public String toIdentityString() { if (identity != null) { return identity; } return identity = buildString(true, false); // only return identity message, see the method "equals" and "hashCode" - } + } public String toIdentityString(String... parameters) { return buildString(true, false, parameters); // only return identity message, see the method "equals" and "hashCode" } - - public String toFullString() { - if (full != null) { - return full; - } - return full = buildString(true, true); - } + + public String toFullString() { + if (full != null) { + return full; + } + return full = buildString(true, true); + } public String toFullString(String... parameters) { return buildString(true, true, parameters); } - + public String toParameterString() { if (parameter != null) { return parameter; } return parameter = toParameterString(new String[0]); } - - public String toParameterString(String... parameters) { - StringBuilder buf = new StringBuilder(); - buildParameters(buf, false, parameters); - return buf.toString(); - } - - private void buildParameters(StringBuilder buf, boolean concat, String[] parameters) { - if (getParameters() !=null && getParameters().size() > 0) { + + public String toParameterString(String... parameters) { + StringBuilder buf = new StringBuilder(); + buildParameters(buf, false, parameters); + return buf.toString(); + } + + private void buildParameters(StringBuilder buf, boolean concat, String[] parameters) { + if (getParameters() != null && getParameters().size() > 0) { List includes = (parameters == null || parameters.length == 0 ? null : Arrays.asList(parameters)); boolean first = true; for (Map.Entry entry : new TreeMap(getParameters()).entrySet()) { @@ -1121,54 +1113,54 @@ private void buildParameters(StringBuilder buf, boolean concat, String[] paramet } } } - } - - private String buildString(boolean appendUser, boolean appendParameter, String... parameters) { - return buildString(appendUser, appendParameter, false, false, parameters); - } - - private String buildString(boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) { - StringBuilder buf = new StringBuilder(); - if (protocol != null && protocol.length() > 0) { - buf.append(protocol); - buf.append("://"); - } - if (appendUser && username != null && username.length() > 0) { - buf.append(username); - if (password != null && password.length() > 0) { - buf.append(":"); - buf.append(password); - } - buf.append("@"); - } - String host; - if (useIP) { - host = getIp(); - } else { - host = getHost(); - } - if(host != null && host.length() > 0) { - buf.append(host); - if (port > 0) { - buf.append(":"); - buf.append(port); - } - } - String path; - if (useService) { - path = getServiceKey(); - } else { - path = getPath(); - } - if (path != null && path.length() > 0) { - buf.append("/"); - buf.append(path); - } - if (appendParameter) { - buildParameters(buf, true, parameters); - } - return buf.toString(); - } + } + + private String buildString(boolean appendUser, boolean appendParameter, String... parameters) { + return buildString(appendUser, appendParameter, false, false, parameters); + } + + private String buildString(boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) { + StringBuilder buf = new StringBuilder(); + if (protocol != null && protocol.length() > 0) { + buf.append(protocol); + buf.append("://"); + } + if (appendUser && username != null && username.length() > 0) { + buf.append(username); + if (password != null && password.length() > 0) { + buf.append(":"); + buf.append(password); + } + buf.append("@"); + } + String host; + if (useIP) { + host = getIp(); + } else { + host = getHost(); + } + if (host != null && host.length() > 0) { + buf.append(host); + if (port > 0) { + buf.append(":"); + buf.append(port); + } + } + String path; + if (useService) { + path = getServiceKey(); + } else { + path = getPath(); + } + if (path != null && path.length() > 0) { + buf.append("/"); + buf.append(path); + } + if (appendParameter) { + buildParameters(buf, true, parameters); + } + return buf.toString(); + } public java.net.URL toJavaURL() { try { @@ -1199,7 +1191,7 @@ public String getServiceKey() { } public String toServiceString() { - return buildString(true, false, true, true); + return buildString(true, false, true, true); } @Deprecated @@ -1216,8 +1208,8 @@ public URL setServiceInterface(String service) { } /** - * @deprecated Replace to getParameter(String, int) * @see #getParameter(String, int) + * @deprecated Replace to getParameter(String, int) */ @Deprecated public int getIntParameter(String key) { @@ -1225,8 +1217,8 @@ public int getIntParameter(String key) { } /** - * @deprecated Replace to getParameter(String, int) * @see #getParameter(String, int) + * @deprecated Replace to getParameter(String, int) */ @Deprecated public int getIntParameter(String key, int defaultValue) { @@ -1234,8 +1226,8 @@ public int getIntParameter(String key, int defaultValue) { } /** - * @deprecated Replace to getPositiveParameter(String, int) * @see #getPositiveParameter(String, int) + * @deprecated Replace to getPositiveParameter(String, int) */ @Deprecated public int getPositiveIntParameter(String key, int defaultValue) { @@ -1243,8 +1235,8 @@ public int getPositiveIntParameter(String key, int defaultValue) { } /** - * @deprecated Replace to getParameter(String, boolean) * @see #getParameter(String, boolean) + * @deprecated Replace to getParameter(String, boolean) */ @Deprecated public boolean getBooleanParameter(String key) { @@ -1252,17 +1244,17 @@ public boolean getBooleanParameter(String key) { } /** - * @deprecated Replace to getParameter(String, boolean) * @see #getParameter(String, boolean) + * @deprecated Replace to getParameter(String, boolean) */ - @Deprecated - public boolean getBooleanParameter(String key, boolean defaultValue) { - return getParameter(key, defaultValue); - } + @Deprecated + public boolean getBooleanParameter(String key, boolean defaultValue) { + return getParameter(key, defaultValue); + } - /** - * @deprecated Replace to getMethodParameter(String, String, int) + /** * @see #getMethodParameter(String, String, int) + * @deprecated Replace to getMethodParameter(String, String, int) */ @Deprecated public int getMethodIntParameter(String method, String key) { @@ -1270,8 +1262,8 @@ public int getMethodIntParameter(String method, String key) { } /** - * @deprecated Replace to getMethodParameter(String, String, int) * @see #getMethodParameter(String, String, int) + * @deprecated Replace to getMethodParameter(String, String, int) */ @Deprecated public int getMethodIntParameter(String method, String key, int defaultValue) { @@ -1279,8 +1271,8 @@ public int getMethodIntParameter(String method, String key, int defaultValue) { } /** - * @deprecated Replace to getMethodPositiveParameter(String, String, int) * @see #getMethodPositiveParameter(String, String, int) + * @deprecated Replace to getMethodPositiveParameter(String, String, int) */ @Deprecated public int getMethodPositiveIntParameter(String method, String key, int defaultValue) { @@ -1288,8 +1280,8 @@ public int getMethodPositiveIntParameter(String method, String key, int defaultV } /** - * @deprecated Replace to getMethodParameter(String, String, boolean) * @see #getMethodParameter(String, String, boolean) + * @deprecated Replace to getMethodParameter(String, String, boolean) */ @Deprecated public boolean getMethodBooleanParameter(String method, String key) { @@ -1297,8 +1289,8 @@ public boolean getMethodBooleanParameter(String method, String key) { } /** - * @deprecated Replace to getMethodParameter(String, String, boolean) * @see #getMethodParameter(String, String, boolean) + * @deprecated Replace to getMethodParameter(String, String, boolean) */ @Deprecated public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) { @@ -1306,7 +1298,7 @@ public boolean getMethodBooleanParameter(String method, String key, boolean defa } public static String encode(String value) { - if (value == null || value.length() == 0) { + if (value == null || value.length() == 0) { return ""; } try { @@ -1315,9 +1307,9 @@ public static String encode(String value) { throw new RuntimeException(e.getMessage(), e); } } - + public static String decode(String value) { - if (value == null || value.length() == 0) { + if (value == null || value.length() == 0) { return ""; } try { diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java index 84b78e50d01..860fd0b98a9 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java @@ -15,377 +15,311 @@ */ package com.alibaba.dubbo.common.bytecode; +import com.alibaba.dubbo.common.utils.ReflectUtils; +import javassist.*; + import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtField; -import javassist.CtMethod; -import javassist.CtNewConstructor; -import javassist.CtNewMethod; -import javassist.LoaderClassPath; -import javassist.NotFoundException; - -import com.alibaba.dubbo.common.utils.ReflectUtils; - /** * ClassGenerator - * + * * @author qian.lei */ -public final class ClassGenerator -{ - public static interface DC{} // dynamic class tag interface. +public final class ClassGenerator { + public static interface DC { + } // dynamic class tag interface. + + private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); + + private static final String SIMPLE_NAME_TAG = ""; + + private static final Map POOL_MAP = new ConcurrentHashMap(); //ClassLoader - ClassPool + + public static ClassGenerator newInstance() { + return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader())); + } - private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); + public static ClassGenerator newInstance(ClassLoader loader) { + return new ClassGenerator(getClassPool(loader)); + } - private static final String SIMPLE_NAME_TAG = ""; + public static boolean isDynamicClass(Class cl) { + return ClassGenerator.DC.class.isAssignableFrom(cl); + } - private static final Map POOL_MAP = new ConcurrentHashMap(); //ClassLoader - ClassPool + public static ClassPool getClassPool(ClassLoader loader) { + if (loader == null) + return ClassPool.getDefault(); - public static ClassGenerator newInstance() - { - return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader())); - } - - public static ClassGenerator newInstance(ClassLoader loader) - { - return new ClassGenerator(getClassPool(loader)); - } - - public static boolean isDynamicClass(Class cl) - { - return ClassGenerator.DC.class.isAssignableFrom(cl); - } - - public static ClassPool getClassPool(ClassLoader loader) - { - if( loader == null ) - return ClassPool.getDefault(); - - ClassPool pool = POOL_MAP.get(loader); - if( pool == null ) - { - pool = new ClassPool(true); - pool.appendClassPath(new LoaderClassPath(loader)); - POOL_MAP.put(loader, pool); - } - return pool; - } - - private ClassPool mPool; - - private CtClass mCtc; - - private String mClassName, mSuperClass; - - private Set mInterfaces; - - private List mFields, mConstructors, mMethods; - - private Map mCopyMethods; // - - private Map> mCopyConstructors; // - - private boolean mDefaultConstructor = false; - - private ClassGenerator(){} - - private ClassGenerator(ClassPool pool) - { - mPool = pool; - } - - public String getClassName() - { - return mClassName; - } - - public ClassGenerator setClassName(String name) - { - mClassName = name; - return this; - } - - public ClassGenerator addInterface(String cn) - { - if( mInterfaces == null ) - mInterfaces = new HashSet(); - mInterfaces.add(cn); - return this; - } - - public ClassGenerator addInterface(Class cl) - { - return addInterface(cl.getName()); - } - - public ClassGenerator setSuperClass(String cn) - { - mSuperClass = cn; - return this; - } - - public ClassGenerator setSuperClass(Class cl) - { - mSuperClass = cl.getName(); - return this; - } - - public ClassGenerator addField(String code) - { - if( mFields == null ) - mFields = new ArrayList(); - mFields.add(code); - return this; - } - - public ClassGenerator addField(String name, int mod, Class type) - { - return addField(name, mod, type, null); - } - - public ClassGenerator addField(String name, int mod, Class type, String def) - { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); - sb.append(name); - if( def != null && def.length() > 0 ) - { - sb.append('='); - sb.append(def); - } - sb.append(';'); - return addField(sb.toString()); - } - - public ClassGenerator addMethod(String code) - { - if( mMethods == null ) - mMethods = new ArrayList(); - mMethods.add(code); - return this; - } - - public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, String body) - { - return addMethod(name, mod, rt, pts, null, body); - } - - public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, String body) - { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name); - sb.append('('); - for(int i=0;i 0 ) - sb.append(','); - sb.append(ReflectUtils.getName(pts[i])); - sb.append(" arg").append(i); - } - sb.append(')'); - if( ets != null && ets.length > 0 ) - { - sb.append(" throws "); - for(int i=0;i 0 ) - sb.append(','); - sb.append(ReflectUtils.getName(ets[i])); - } - } - sb.append('{').append(body).append('}'); - return addMethod(sb.toString()); - } - - public ClassGenerator addMethod(Method m) - { - addMethod(m.getName(), m); - return this; - } - - public ClassGenerator addMethod(String name, Method m) - { - String desc = name + ReflectUtils.getDescWithoutMethodName(m); - addMethod(':' + desc); - if( mCopyMethods == null ) - mCopyMethods = new ConcurrentHashMap(8); - mCopyMethods.put(desc, m); - return this; - } - - public ClassGenerator addConstructor(String code) - { - if( mConstructors == null ) - mConstructors = new LinkedList(); - mConstructors.add(code); - return this; - } - - public ClassGenerator addConstructor(int mod, Class[] pts, String body) - { - return addConstructor(mod, pts, null, body); - } - - public ClassGenerator addConstructor(int mod, Class[] pts, Class[] ets, String body) - { - StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); - sb.append('('); - for(int i=0;i 0 ) - sb.append(','); - sb.append(ReflectUtils.getName(pts[i])); - sb.append(" arg").append(i); - } - sb.append(')'); - if( ets != null && ets.length > 0 ) - { - sb.append(" throws "); - for(int i=0;i 0 ) - sb.append(','); - sb.append(ReflectUtils.getName(ets[i])); - } - } - sb.append('{').append(body).append('}'); - return addConstructor(sb.toString()); - } - - public ClassGenerator addConstructor(Constructor c) - { - String desc = ReflectUtils.getDesc(c); - addConstructor(":"+desc); - if( mCopyConstructors == null ) - mCopyConstructors = new ConcurrentHashMap>(4); - mCopyConstructors.put(desc, c); - return this; - } - - public ClassGenerator addDefaultConstructor() - { - mDefaultConstructor = true; - return this; - } - - public ClassPool getClassPool() { - return mPool; - } - - public Class toClass(){ - return toClass(getClass().getClassLoader(), getClass().getProtectionDomain()); - } - - public Class toClass(ClassLoader loader, ProtectionDomain pd) - { - if( mCtc != null ) - mCtc.detach(); - long id = CLASS_NAME_COUNTER.getAndIncrement(); - try - { - CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); - if( mClassName == null ) - mClassName = ( mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) - ? ClassGenerator.class.getName() : mSuperClass + "$sc" ) + id; - mCtc = mPool.makeClass(mClassName); - if( mSuperClass != null ) - mCtc.setSuperclass(ctcs); - mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. - if( mInterfaces != null ) - for( String cl : mInterfaces ) mCtc.addInterface(mPool.get(cl)); - if( mFields != null ) - for( String code : mFields ) mCtc.addField(CtField.make(code, mCtc)); - if( mMethods != null ) - { - for( String code : mMethods ) - { - if( code.charAt(0) == ':' ) - mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null)); - else - mCtc.addMethod(CtNewMethod.make(code, mCtc)); - } - } - if( mDefaultConstructor ) - mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); - if( mConstructors != null ) - { - for( String code : mConstructors ) - { - if( code.charAt(0) == ':' ) - { - mCtc.addConstructor(CtNewConstructor.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); - } - else - { - String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. - mCtc.addConstructor(CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length-1]), mCtc)); - } - } - } - return mCtc.toClass(loader, pd); - } - catch(RuntimeException e) - { - throw e; - } - catch(NotFoundException e) - { - throw new RuntimeException(e.getMessage(), e); - } - catch(CannotCompileException e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - public void release() - { - if( mCtc != null ) mCtc.detach(); - if( mInterfaces != null ) mInterfaces.clear(); - if( mFields != null ) mFields.clear(); - if( mMethods != null ) mMethods.clear(); - if( mConstructors != null ) mConstructors.clear(); - if( mCopyMethods != null ) mCopyMethods.clear(); - if( mCopyConstructors != null ) mCopyConstructors.clear(); - } - - private CtClass getCtClass(Class c) throws NotFoundException - { - return mPool.get(c.getName()); - } - - private CtMethod getCtMethod(Method m) throws NotFoundException - { - return getCtClass(m.getDeclaringClass()).getMethod(m.getName(),ReflectUtils.getDescWithoutMethodName(m)); - } - - private CtConstructor getCtConstructor(Constructor c) throws NotFoundException - { - return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); - } - - private static String modifier(int mod) - { - if( Modifier.isPublic(mod) ) return "public"; - if( Modifier.isProtected(mod) ) return "protected"; - if( Modifier.isPrivate(mod) ) return "private"; - return ""; - } + ClassPool pool = POOL_MAP.get(loader); + if (pool == null) { + pool = new ClassPool(true); + pool.appendClassPath(new LoaderClassPath(loader)); + POOL_MAP.put(loader, pool); + } + return pool; + } + + private ClassPool mPool; + + private CtClass mCtc; + + private String mClassName, mSuperClass; + + private Set mInterfaces; + + private List mFields, mConstructors, mMethods; + + private Map mCopyMethods; // + + private Map> mCopyConstructors; // + + private boolean mDefaultConstructor = false; + + private ClassGenerator() { + } + + private ClassGenerator(ClassPool pool) { + mPool = pool; + } + + public String getClassName() { + return mClassName; + } + + public ClassGenerator setClassName(String name) { + mClassName = name; + return this; + } + + public ClassGenerator addInterface(String cn) { + if (mInterfaces == null) + mInterfaces = new HashSet(); + mInterfaces.add(cn); + return this; + } + + public ClassGenerator addInterface(Class cl) { + return addInterface(cl.getName()); + } + + public ClassGenerator setSuperClass(String cn) { + mSuperClass = cn; + return this; + } + + public ClassGenerator setSuperClass(Class cl) { + mSuperClass = cl.getName(); + return this; + } + + public ClassGenerator addField(String code) { + if (mFields == null) + mFields = new ArrayList(); + mFields.add(code); + return this; + } + + public ClassGenerator addField(String name, int mod, Class type) { + return addField(name, mod, type, null); + } + + public ClassGenerator addField(String name, int mod, Class type, String def) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); + sb.append(name); + if (def != null && def.length() > 0) { + sb.append('='); + sb.append(def); + } + sb.append(';'); + return addField(sb.toString()); + } + + public ClassGenerator addMethod(String code) { + if (mMethods == null) + mMethods = new ArrayList(); + mMethods.add(code); + return this; + } + + public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, String body) { + return addMethod(name, mod, rt, pts, null, body); + } + + public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, String body) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name); + sb.append('('); + for (int i = 0; i < pts.length; i++) { + if (i > 0) + sb.append(','); + sb.append(ReflectUtils.getName(pts[i])); + sb.append(" arg").append(i); + } + sb.append(')'); + if (ets != null && ets.length > 0) { + sb.append(" throws "); + for (int i = 0; i < ets.length; i++) { + if (i > 0) + sb.append(','); + sb.append(ReflectUtils.getName(ets[i])); + } + } + sb.append('{').append(body).append('}'); + return addMethod(sb.toString()); + } + + public ClassGenerator addMethod(Method m) { + addMethod(m.getName(), m); + return this; + } + + public ClassGenerator addMethod(String name, Method m) { + String desc = name + ReflectUtils.getDescWithoutMethodName(m); + addMethod(':' + desc); + if (mCopyMethods == null) + mCopyMethods = new ConcurrentHashMap(8); + mCopyMethods.put(desc, m); + return this; + } + + public ClassGenerator addConstructor(String code) { + if (mConstructors == null) + mConstructors = new LinkedList(); + mConstructors.add(code); + return this; + } + + public ClassGenerator addConstructor(int mod, Class[] pts, String body) { + return addConstructor(mod, pts, null, body); + } + + public ClassGenerator addConstructor(int mod, Class[] pts, Class[] ets, String body) { + StringBuilder sb = new StringBuilder(); + sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); + sb.append('('); + for (int i = 0; i < pts.length; i++) { + if (i > 0) + sb.append(','); + sb.append(ReflectUtils.getName(pts[i])); + sb.append(" arg").append(i); + } + sb.append(')'); + if (ets != null && ets.length > 0) { + sb.append(" throws "); + for (int i = 0; i < ets.length; i++) { + if (i > 0) + sb.append(','); + sb.append(ReflectUtils.getName(ets[i])); + } + } + sb.append('{').append(body).append('}'); + return addConstructor(sb.toString()); + } + + public ClassGenerator addConstructor(Constructor c) { + String desc = ReflectUtils.getDesc(c); + addConstructor(":" + desc); + if (mCopyConstructors == null) + mCopyConstructors = new ConcurrentHashMap>(4); + mCopyConstructors.put(desc, c); + return this; + } + + public ClassGenerator addDefaultConstructor() { + mDefaultConstructor = true; + return this; + } + + public ClassPool getClassPool() { + return mPool; + } + + public Class toClass() { + return toClass(getClass().getClassLoader(), getClass().getProtectionDomain()); + } + + public Class toClass(ClassLoader loader, ProtectionDomain pd) { + if (mCtc != null) + mCtc.detach(); + long id = CLASS_NAME_COUNTER.getAndIncrement(); + try { + CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); + if (mClassName == null) + mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) + ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; + mCtc = mPool.makeClass(mClassName); + if (mSuperClass != null) + mCtc.setSuperclass(ctcs); + mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. + if (mInterfaces != null) + for (String cl : mInterfaces) mCtc.addInterface(mPool.get(cl)); + if (mFields != null) + for (String code : mFields) mCtc.addField(CtField.make(code, mCtc)); + if (mMethods != null) { + for (String code : mMethods) { + if (code.charAt(0) == ':') + mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null)); + else + mCtc.addMethod(CtNewMethod.make(code, mCtc)); + } + } + if (mDefaultConstructor) + mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); + if (mConstructors != null) { + for (String code : mConstructors) { + if (code.charAt(0) == ':') { + mCtc.addConstructor(CtNewConstructor.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); + } else { + String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. + mCtc.addConstructor(CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc)); + } + } + } + return mCtc.toClass(loader, pd); + } catch (RuntimeException e) { + throw e; + } catch (NotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (CannotCompileException e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + public void release() { + if (mCtc != null) mCtc.detach(); + if (mInterfaces != null) mInterfaces.clear(); + if (mFields != null) mFields.clear(); + if (mMethods != null) mMethods.clear(); + if (mConstructors != null) mConstructors.clear(); + if (mCopyMethods != null) mCopyMethods.clear(); + if (mCopyConstructors != null) mCopyConstructors.clear(); + } + + private CtClass getCtClass(Class c) throws NotFoundException { + return mPool.get(c.getName()); + } + + private CtMethod getCtMethod(Method m) throws NotFoundException { + return getCtClass(m.getDeclaringClass()).getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); + } + + private CtConstructor getCtConstructor(Constructor c) throws NotFoundException { + return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); + } + + private static String modifier(int mod) { + if (Modifier.isPublic(mod)) return "public"; + if (Modifier.isProtected(mod)) return "protected"; + if (Modifier.isPrivate(mod)) return "private"; + return ""; + } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java index 653e30e6425..9e0be398458 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java @@ -15,415 +15,404 @@ */ package com.alibaba.dubbo.common.bytecode; +import com.alibaba.dubbo.common.utils.ClassHelper; +import com.alibaba.dubbo.common.utils.ReflectUtils; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; -import com.alibaba.dubbo.common.utils.ClassHelper; -import com.alibaba.dubbo.common.utils.ReflectUtils; - /** * Wrapper. - * + * * @author qian.lei */ -public abstract class Wrapper -{ - private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0); - - private static final Map, Wrapper> WRAPPER_MAP = new ConcurrentHashMap, Wrapper>(); //class wrapper map - - private static final String[] EMPTY_STRING_ARRAY = new String[0]; - - private static final String[] OBJECT_METHODS = new String[]{"getClass", "hashCode", "toString", "equals"}; - - private static final Wrapper OBJECT_WRAPPER = new Wrapper(){ - public String[] getMethodNames(){ return OBJECT_METHODS; } - public String[] getDeclaredMethodNames(){ return OBJECT_METHODS; } - public String[] getPropertyNames(){ return EMPTY_STRING_ARRAY; } - public Class getPropertyType(String pn){ return null; } - public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException{ throw new NoSuchPropertyException("Property [" + pn + "] not found."); } - public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException{ throw new NoSuchPropertyException("Property [" + pn + "] not found."); } - public boolean hasProperty(String name){ return false; } - public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException - { - if( "getClass".equals(mn) ) return instance.getClass(); - if( "hashCode".equals(mn) ) return instance.hashCode(); - if( "toString".equals(mn) ) return instance.toString(); - if( "equals".equals(mn) ) - { - if( args.length == 1 ) return instance.equals(args[0]); - throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); - } - throw new NoSuchMethodException("Method [" + mn + "] not found."); - } - }; - - /** - * get wrapper. - * - * @param c Class instance. - * @return Wrapper instance(not null). - */ - public static Wrapper getWrapper(Class c) - { - while( ClassGenerator.isDynamicClass(c) ) // can not wrapper on dynamic class. +public abstract class Wrapper { + private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0); + + private static final Map, Wrapper> WRAPPER_MAP = new ConcurrentHashMap, Wrapper>(); //class wrapper map + + private static final String[] EMPTY_STRING_ARRAY = new String[0]; + + private static final String[] OBJECT_METHODS = new String[]{"getClass", "hashCode", "toString", "equals"}; + + private static final Wrapper OBJECT_WRAPPER = new Wrapper() { + public String[] getMethodNames() { + return OBJECT_METHODS; + } + + public String[] getDeclaredMethodNames() { + return OBJECT_METHODS; + } + + public String[] getPropertyNames() { + return EMPTY_STRING_ARRAY; + } + + public Class getPropertyType(String pn) { + return null; + } + + public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException { + throw new NoSuchPropertyException("Property [" + pn + "] not found."); + } + + public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException { + throw new NoSuchPropertyException("Property [" + pn + "] not found."); + } + + public boolean hasProperty(String name) { + return false; + } + + public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException { + if ("getClass".equals(mn)) return instance.getClass(); + if ("hashCode".equals(mn)) return instance.hashCode(); + if ("toString".equals(mn)) return instance.toString(); + if ("equals".equals(mn)) { + if (args.length == 1) return instance.equals(args[0]); + throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); + } + throw new NoSuchMethodException("Method [" + mn + "] not found."); + } + }; + + /** + * get wrapper. + * + * @param c Class instance. + * @return Wrapper instance(not null). + */ + public static Wrapper getWrapper(Class c) { + while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class. c = c.getSuperclass(); - if( c == Object.class ) + if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); - if( ret == null ) - { + if (ret == null) { ret = makeWrapper(c); - WRAPPER_MAP.put(c,ret); + WRAPPER_MAP.put(c, ret); } return ret; } - /** - * get property name array. - * - * @return property name array. - */ - abstract public String[] getPropertyNames(); - - /** - * get property type. - * - * @param pn property name. - * @return Property type or nul. - */ - abstract public Class getPropertyType(String pn); - - /** - * has property. - * - * @param name property name. - * @return has or has not. - */ - abstract public boolean hasProperty(String name); - - /** - * get property value. - * - * @param instance instance. - * @param pn property name. - * @return value. - */ - abstract public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException, IllegalArgumentException; - - /** - * set property value. - * - * @param instance instance. - * @param pn property name. - * @param pv property value. - */ - abstract public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException, IllegalArgumentException; - - /** - * get property value. - * - * @param instance instance. - * @param pns property name array. - * @return value array. - */ - public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException - { - Object[] ret = new Object[pns.length]; - for(int i=0;i[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; - - private static Wrapper makeWrapper(Class c) - { - if( c.isPrimitive() ) - throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); - - String name = c.getName(); - ClassLoader cl = ClassHelper.getClassLoader(c); - - StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); - StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); - StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); - - c1.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); - c2.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); - c3.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); - - Map> pts = new HashMap>(); // - Map ms = new LinkedHashMap(); // - List mns = new ArrayList(); // method names. - List dmns = new ArrayList(); // declaring method names. - - // get all public field. - for( Field f : c.getFields() ) - { - String fn = f.getName(); - Class ft = f.getType(); - if( Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers()) ) - continue; - - c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")).append("; return; }"); - c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }"); - pts.put(fn, ft); - } - - Method[] methods = c.getMethods(); - // get all public method. - boolean hasMethod = hasMethods(methods); - if( hasMethod ){ - c3.append(" try{"); - } - for( Method m : methods ) - { - if( m.getDeclaringClass() == Object.class ) //ignore Object's method. - continue; - - String mn = m.getName(); - c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); + + /** + * get property name array. + * + * @return property name array. + */ + abstract public String[] getPropertyNames(); + + /** + * get property type. + * + * @param pn property name. + * @return Property type or nul. + */ + abstract public Class getPropertyType(String pn); + + /** + * has property. + * + * @param name property name. + * @return has or has not. + */ + abstract public boolean hasProperty(String name); + + /** + * get property value. + * + * @param instance instance. + * @param pn property name. + * @return value. + */ + abstract public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException, IllegalArgumentException; + + /** + * set property value. + * + * @param instance instance. + * @param pn property name. + * @param pv property value. + */ + abstract public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException, IllegalArgumentException; + + /** + * get property value. + * + * @param instance instance. + * @param pns property name array. + * @return value array. + */ + public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException { + Object[] ret = new Object[pns.length]; + for (int i = 0; i < ret.length; i++) + ret[i] = getPropertyValue(instance, pns[i]); + return ret; + } + + /** + * set property value. + * + * @param instance instance. + * @param pns property name array. + * @param pvs property value array. + */ + public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException { + if (pns.length != pvs.length) + throw new IllegalArgumentException("pns.length != pvs.length"); + + for (int i = 0; i < pns.length; i++) + setPropertyValue(instance, pns[i], pvs[i]); + } + + /** + * get method name array. + * + * @return method name array. + */ + abstract public String[] getMethodNames(); + + /** + * get method name array. + * + * @return method name array. + */ + abstract public String[] getDeclaredMethodNames(); + + /** + * has method. + * + * @param name method name. + * @return has or has not. + */ + public boolean hasMethod(String name) { + for (String mn : getMethodNames()) + if (mn.equals(name)) return true; + return false; + } + + /** + * invoke method. + * + * @param instance instance. + * @param mn method name. + * @param types + * @param args argument array. + * @return return value. + */ + abstract public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; + + private static Wrapper makeWrapper(Class c) { + if (c.isPrimitive()) + throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); + + String name = c.getName(); + ClassLoader cl = ClassHelper.getClassLoader(c); + + StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); + StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); + StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); + + c1.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + c2.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + c3.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + + Map> pts = new HashMap>(); // + Map ms = new LinkedHashMap(); // + List mns = new ArrayList(); // method names. + List dmns = new ArrayList(); // declaring method names. + + // get all public field. + for (Field f : c.getFields()) { + String fn = f.getName(); + Class ft = f.getType(); + if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) + continue; + + c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")).append("; return; }"); + c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }"); + pts.put(fn, ft); + } + + Method[] methods = c.getMethods(); + // get all public method. + boolean hasMethod = hasMethods(methods); + if (hasMethod) { + c3.append(" try{"); + } + for (Method m : methods) { + if (m.getDeclaringClass() == Object.class) //ignore Object's method. + continue; + + String mn = m.getName(); + c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); int len = m.getParameterTypes().length; c3.append(" && ").append(" $3.length == ").append(len); - - boolean override = false; - for( Method m2 : methods ) { - if (m != m2 && m.getName().equals(m2.getName())) { - override = true; - break; - } - } - if (override) { - if (len > 0) { - for (int l = 0; l < len; l ++) { - c3.append(" && ").append(" $3[").append(l).append("].getName().equals(\"") - .append(m.getParameterTypes()[l].getName()).append("\")"); - } - } - } - - c3.append(" ) { "); - - if( m.getReturnType() == Void.TYPE ) - c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;"); - else - c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");"); - - c3.append(" }"); - - mns.add(mn); - if( m.getDeclaringClass() == c ) - dmns.add(mn); - ms.put(ReflectUtils.getDesc(m), m); - } - if( hasMethod ){ - c3.append(" } catch(Throwable e) { " ); - c3.append(" throw new java.lang.reflect.InvocationTargetException(e); " ); - c3.append(" }"); + + boolean override = false; + for (Method m2 : methods) { + if (m != m2 && m.getName().equals(m2.getName())) { + override = true; + break; + } + } + if (override) { + if (len > 0) { + for (int l = 0; l < len; l++) { + c3.append(" && ").append(" $3[").append(l).append("].getName().equals(\"") + .append(m.getParameterTypes()[l].getName()).append("\")"); + } + } + } + + c3.append(" ) { "); + + if (m.getReturnType() == Void.TYPE) + c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;"); + else + c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");"); + + c3.append(" }"); + + mns.add(mn); + if (m.getDeclaringClass() == c) + dmns.add(mn); + ms.put(ReflectUtils.getDesc(m), m); + } + if (hasMethod) { + c3.append(" } catch(Throwable e) { "); + c3.append(" throw new java.lang.reflect.InvocationTargetException(e); "); + c3.append(" }"); + } + + c3.append(" throw new " + NoSuchMethodException.class.getName() + "(\"Not found method \\\"\"+$2+\"\\\" in class " + c.getName() + ".\"); }"); + + // deal with get/set method. + Matcher matcher; + for (Map.Entry entry : ms.entrySet()) { + String md = entry.getKey(); + Method method = (Method) entry.getValue(); + if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { + String pn = propertyName(matcher.group(1)); + c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); + pts.put(pn, method.getReturnType()); + } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) { + String pn = propertyName(matcher.group(1)); + c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); + pts.put(pn, method.getReturnType()); + } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { + Class pt = method.getParameterTypes()[0]; + String pn = propertyName(matcher.group(1)); + c1.append(" if( $2.equals(\"").append(pn).append("\") ){ w.").append(method.getName()).append("(").append(arg(pt, "$3")).append("); return; }"); + pts.put(pn, pt); + } + } + c1.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); + c2.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); + + // make class + long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); + ClassGenerator cc = ClassGenerator.newInstance(cl); + cc.setClassName((Modifier.isPublic(c.getModifiers()) ? Wrapper.class.getName() : c.getName() + "$sw") + id); + cc.setSuperClass(Wrapper.class); + + cc.addDefaultConstructor(); + cc.addField("public static String[] pns;"); // property name array. + cc.addField("public static " + Map.class.getName() + " pts;"); // property type map. + cc.addField("public static String[] mns;"); // all method name array. + cc.addField("public static String[] dmns;"); // declared method name array. + for (int i = 0, len = ms.size(); i < len; i++) + cc.addField("public static Class[] mts" + i + ";"); + + cc.addMethod("public String[] getPropertyNames(){ return pns; }"); + cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }"); + cc.addMethod("public Class getPropertyType(String n){ return (Class)pts.get($1); }"); + cc.addMethod("public String[] getMethodNames(){ return mns; }"); + cc.addMethod("public String[] getDeclaredMethodNames(){ return dmns; }"); + cc.addMethod(c1.toString()); + cc.addMethod(c2.toString()); + cc.addMethod(c3.toString()); + + try { + Class wc = cc.toClass(); + // setup static field. + wc.getField("pts").set(null, pts); + wc.getField("pns").set(null, pts.keySet().toArray(new String[0])); + wc.getField("mns").set(null, mns.toArray(new String[0])); + wc.getField("dmns").set(null, dmns.toArray(new String[0])); + int ix = 0; + for (Method m : ms.values()) + wc.getField("mts" + ix++).set(null, m.getParameterTypes()); + return (Wrapper) wc.newInstance(); + } catch (RuntimeException e) { + throw e; + } catch (Throwable e) { + throw new RuntimeException(e.getMessage(), e); + } finally { + cc.release(); + ms.clear(); + mns.clear(); + dmns.clear(); } - - c3.append(" throw new " + NoSuchMethodException.class.getName() + "(\"Not found method \\\"\"+$2+\"\\\" in class " + c.getName() + ".\"); }"); - - // deal with get/set method. - Matcher matcher; - for( Map.Entry entry : ms.entrySet() ) - { - String md = entry.getKey(); - Method method = (Method)entry.getValue(); - if( ( matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md) ).matches() ) - { - String pn = propertyName(matcher.group(1)); - c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); - pts.put(pn, method.getReturnType()); - } - else if( ( matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md) ).matches() ) - { - String pn = propertyName(matcher.group(1)); - c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); - pts.put(pn, method.getReturnType()); - } - else if( ( matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md) ).matches() ) - { - Class pt = method.getParameterTypes()[0]; - String pn = propertyName(matcher.group(1)); - c1.append(" if( $2.equals(\"").append(pn).append("\") ){ w.").append(method.getName()).append("(").append(arg(pt,"$3")).append("); return; }"); - pts.put(pn, pt); - } - } - c1.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); - c2.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); - - // make class - long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); - ClassGenerator cc = ClassGenerator.newInstance(cl); - cc.setClassName( ( Modifier.isPublic(c.getModifiers()) ? Wrapper.class.getName() : c.getName() + "$sw" ) + id ); - cc.setSuperClass(Wrapper.class); - - cc.addDefaultConstructor(); - cc.addField("public static String[] pns;"); // property name array. - cc.addField("public static " + Map.class.getName() + " pts;"); // property type map. - cc.addField("public static String[] mns;"); // all method name array. - cc.addField("public static String[] dmns;"); // declared method name array. - for(int i=0,len=ms.size();i wc = cc.toClass(); - // setup static field. - wc.getField("pts").set(null, pts); - wc.getField("pns").set(null, pts.keySet().toArray(new String[0])); - wc.getField("mns").set(null, mns.toArray(new String[0])); - wc.getField("dmns").set(null, dmns.toArray(new String[0])); - int ix = 0; - for( Method m : ms.values() ) - wc.getField("mts" + ix++).set(null, m.getParameterTypes()); - return (Wrapper)wc.newInstance(); - } - catch(RuntimeException e) - { - throw e; - } - catch(Throwable e) - { - throw new RuntimeException(e.getMessage(), e); - } - finally - { - cc.release(); - ms.clear(); - mns.clear(); - dmns.clear(); - } - } - - private static String arg(Class cl, String name) - { - if( cl.isPrimitive() ) - { - if( cl == Boolean.TYPE ) - return "((Boolean)" + name + ").booleanValue()"; - if( cl == Byte.TYPE ) - return "((Byte)" + name + ").byteValue()"; - if( cl == Character.TYPE ) - return "((Character)" + name + ").charValue()"; - if( cl == Double.TYPE ) - return "((Number)" + name + ").doubleValue()"; - if( cl == Float.TYPE ) - return "((Number)" + name + ").floatValue()"; - if( cl == Integer.TYPE ) - return "((Number)" + name + ").intValue()"; - if( cl == Long.TYPE ) - return "((Number)" + name + ").longValue()"; - if( cl == Short.TYPE ) - return "((Number)" + name + ").shortValue()"; - throw new RuntimeException("Unknown primitive type: " + cl.getName()); - } - return "(" + ReflectUtils.getName(cl) + ")" + name; - } - - private static String args(Class[] cs,String name) - { - int len = cs.length; - if( len == 0 ) return ""; - StringBuilder sb = new StringBuilder(); - for(int i=0;i 0 ) - sb.append(','); - sb.append(arg(cs[i],name+"["+i+"]")); - } - return sb.toString(); - } - - private static String propertyName(String pn) - { - return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; - } - - private static boolean hasMethods(Method[] methods){ - if(methods == null || methods.length == 0){ - return false; - } - for(Method m : methods){ - if(m.getDeclaringClass() != Object.class){ - return true; - } - } - return false; - } + } + + private static String arg(Class cl, String name) { + if (cl.isPrimitive()) { + if (cl == Boolean.TYPE) + return "((Boolean)" + name + ").booleanValue()"; + if (cl == Byte.TYPE) + return "((Byte)" + name + ").byteValue()"; + if (cl == Character.TYPE) + return "((Character)" + name + ").charValue()"; + if (cl == Double.TYPE) + return "((Number)" + name + ").doubleValue()"; + if (cl == Float.TYPE) + return "((Number)" + name + ").floatValue()"; + if (cl == Integer.TYPE) + return "((Number)" + name + ").intValue()"; + if (cl == Long.TYPE) + return "((Number)" + name + ").longValue()"; + if (cl == Short.TYPE) + return "((Number)" + name + ").shortValue()"; + throw new RuntimeException("Unknown primitive type: " + cl.getName()); + } + return "(" + ReflectUtils.getName(cl) + ")" + name; + } + + private static String args(Class[] cs, String name) { + int len = cs.length; + if (len == 0) return ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < len; i++) { + if (i > 0) + sb.append(','); + sb.append(arg(cs[i], name + "[" + i + "]")); + } + return sb.toString(); + } + + private static String propertyName(String pn) { + return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; + } + + private static boolean hasMethods(Method[] methods) { + if (methods == null || methods.length == 0) { + return false; + } + for (Method m : methods) { + if (m.getDeclaringClass() != Object.class) { + return true; + } + } + return false; + } } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index b35732046b4..f4d474662e1 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -47,7 +47,7 @@ - + @@ -58,11 +58,11 @@ - - + + - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java index d0f25307b4c..73cfadaa654 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -1,50 +1,46 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.proxy; -import java.lang.reflect.InvocationTargetException; - import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; + +import java.lang.reflect.InvocationTargetException; /** * InvokerWrapper - * + * * @author william.liangf */ public abstract class AbstractProxyInvoker implements Invoker { - + private final T proxy; - + private final Class type; - + private final URL url; - public AbstractProxyInvoker(T proxy, Class type, URL url){ + public AbstractProxyInvoker(T proxy, Class type, URL url) { if (proxy == null) { throw new IllegalArgumentException("proxy == null"); } if (type == null) { throw new IllegalArgumentException("interface == null"); } - if (! type.isInstance(proxy)) { + if (!type.isInstance(proxy)) { throw new IllegalArgumentException(proxy.getClass().getName() + " not implement interface " + type); } this.proxy = proxy; @@ -76,13 +72,13 @@ public Result invoke(Invocation invocation) throws RpcException { throw new RpcException("Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + ", cause: " + e.getMessage(), e); } } - + protected abstract Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable; @Override public String toString() { - return getInterface() + " -> " + getUrl()==null?" ":getUrl().toString(); + return getUrl().toString(); } - + } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java index 7e776af539e..ac1941dface 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.proxy.javassist; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.bytecode.Proxy; -import com.alibaba.dubbo.common.bytecode.Wrapper; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; -import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.bytecode.Proxy; +import com.alibaba.dubbo.common.bytecode.Wrapper; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; +import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler; /** - * JavaassistRpcProxyFactory + * JavassistRpcProxyFactory * @author william.liangf */ diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java index 23b43789d2e..4bd004f6f9d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java @@ -76,7 +76,7 @@ public T getProxy(Invoker invoker) throws RpcException { } try { Constructor constructor = ReflectUtils.findConstructor(stubClass, serviceType); - proxy = (T) constructor.newInstance(new Object[] {proxy}); + proxy = (T) constructor.newInstance(proxy); //export stub service URL url = invoker.getUrl(); if (url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT)){ diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 229de6d75e8..c36b5ce7d0a 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -98,7 +98,7 @@ public Object reply(ExchangeChannel channel, Object message) throws RemotingExce 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()); + throw new RemotingException(channel, (message.getClass().getName() + ": " + message) + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); } @Override diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java index 93b89e571e5..d08109b7a63 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java @@ -17,6 +17,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.http.HttpBinder; import com.alibaba.dubbo.remoting.http.HttpHandler; import com.alibaba.dubbo.remoting.http.HttpServer; @@ -115,7 +116,9 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc httpProxyFactoryBean.setServiceUrl(url.toIdentityString()); httpProxyFactoryBean.setServiceInterface(serviceType); String client = url.getParameter(Constants.CLIENT_KEY); - if (client == null || client.length() == 0 || "simple".equals(client)) { + if (StringUtils.isEmpty(client) || "okHttpClient".equals(client)) { + httpProxyFactoryBean.setHttpInvokerRequestExecutor(new OkHttpInvokerRequestExecutor(url)); + } else if ("simple".equals(client)) { SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { @@ -129,8 +132,6 @@ protected void prepareConnection(HttpURLConnection con, CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); - } else if ("okHttpClient".equals(client)) { - httpProxyFactoryBean.setHttpInvokerRequestExecutor(new OkHttpInvokerRequestExecutor(url)); } else if (client.length() > 0) { throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); } diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/com/alibaba/dubbo/rpc/protocol/memcached/MemcachedProtocol.java b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/com/alibaba/dubbo/rpc/protocol/memcached/MemcachedProtocol.java index 9439129dafc..d996d0892d0 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/com/alibaba/dubbo/rpc/protocol/memcached/MemcachedProtocol.java +++ b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/com/alibaba/dubbo/rpc/protocol/memcached/MemcachedProtocol.java @@ -92,9 +92,9 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } } catch (Throwable t) { RpcException re = new RpcException("Failed to invoke memecached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); - if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { + if (t instanceof TimeoutException) { re.setCode(RpcException.TIMEOUT_EXCEPTION); - } else if (t instanceof MemcachedException || t instanceof IOException) { + } else if (t instanceof MemcachedException) { re.setCode(RpcException.NETWORK_EXCEPTION); } throw re; diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java index bcb9e2f25a0..924af3189c5 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -15,39 +15,32 @@ */ package com.alibaba.dubbo.rpc.protocol.redis; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -import org.apache.commons.pool.impl.GenericObjectPool; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.serialize.ObjectInput; import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; import com.alibaba.dubbo.rpc.protocol.AbstractProtocol; +import org.apache.commons.pool.impl.GenericObjectPool; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisDataException; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.Map; +import java.util.concurrent.TimeoutException; /** * RedisProtocol - * + * * @author william.liangf */ public class RedisProtocol extends AbstractProtocol { @@ -61,7 +54,7 @@ public int getDefaultPort() { public Exporter export(final Invoker invoker) throws RpcException { throw new UnsupportedOperationException("Unsupported export redis service. url: " + invoker.getUrl()); } - + private Serialization getSerialization(URL url) { return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java")); } @@ -86,8 +79,8 @@ public Invoker refer(final Class type, final URL url) throws RpcExcept config.timeBetweenEvictionRunsMillis = url.getParameter("time.between.eviction.runs.millis", 0); if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) config.minEvictableIdleTimeMillis = url.getParameter("min.evictable.idle.time.millis", 0); - final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), - url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), + url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); final int expiry = url.getParameter("expiry", 0); final String get = url.getParameter("get", "get"); final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set"); @@ -130,10 +123,9 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } else { throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service."); } - } - catch (Throwable t) { + } catch (Throwable t) { RpcException re = new RpcException("Failed to invoke memecached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); - if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { + if (t instanceof SocketTimeoutException) { re.setCode(RpcException.TIMEOUT_EXCEPTION); } else if (t instanceof JedisConnectionException || t instanceof IOException) { re.setCode(RpcException.NETWORK_EXCEPTION); @@ -141,13 +133,11 @@ protected Result doInvoke(Invocation invocation) throws Throwable { re.setCode(RpcException.SERIALIZATION_EXCEPTION); } throw re; - } - finally { - if(resource != null) { + } finally { + if (resource != null) { try { jedisPool.returnResource(resource); - } - catch (Throwable t) { + } catch (Throwable t) { logger.warn("returnResource error: " + t.getMessage(), t); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java index 918f28f91a1..df0d3ed25d1 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,8 +22,8 @@ import com.alibaba.dubbo.remoting.http.servlet.BootstrapListener; import com.alibaba.dubbo.remoting.http.servlet.ServletManager; import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; import com.alibaba.dubbo.rpc.ServiceClassHolder; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HttpResponse; diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java index 79c8a834172..ef4aa893aa8 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -15,26 +15,25 @@ */ package com.alibaba.dubbo.rpc.protocol.rmi; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.rmi.RemoteException; - +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.rmi.RmiProxyFactoryBean; import org.springframework.remoting.rmi.RmiServiceExporter; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.rmi.RemoteException; /** * RmiProtocol. - * + * * @author qian.lei */ public class RmiProtocol extends AbstractProxyProtocol { - public static final int DEFAULT_PORT = 1099; + public static final int DEFAULT_PORT = 1099; public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java index d893fcdb106..6f108d78744 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -1,10 +1,10 @@ /** * File Created at 2011-12-06 * $Id$ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -19,12 +19,7 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; import java.util.Set; @@ -41,23 +36,23 @@ public class ThriftInvoker extends AbstractInvoker { private final AtomicPositiveInteger index = new AtomicPositiveInteger(); private final ReentrantLock destroyLock = new ReentrantLock(); - + private final Set> invokers; - public ThriftInvoker( Class service, URL url, ExchangeClient[] clients ) { + public ThriftInvoker(Class service, URL url, ExchangeClient[] clients) { this(service, url, clients, null); } public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Set> invokers) { super(type, url, - new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, - Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); + new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, + Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); this.clients = clients; this.invokers = invokers; } - + @Override - protected Result doInvoke( Invocation invocation ) throws Throwable { + protected Result doInvoke(Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; @@ -65,11 +60,11 @@ protected Result doInvoke( Invocation invocation ) throws Throwable { methodName = invocation.getMethodName(); - inv.setAttachment( Constants.PATH_KEY, getUrl().getPath() ); + inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); // for thrift codec - inv.setAttachment( ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, getUrl().getParameter( - ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, DubboClassNameGenerator.NAME ) ); + inv.setAttachment(ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, getUrl().getParameter( + ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, DubboClassNameGenerator.NAME)); ExchangeClient currentClient; @@ -81,7 +76,7 @@ protected Result doInvoke( Invocation invocation ) throws Throwable { try { int timeout = getUrl().getMethodParameter( - methodName, Constants.TIMEOUT_KEY,Constants.DEFAULT_TIMEOUT); + methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); RpcContext.getContext().setFuture(null); @@ -102,11 +97,11 @@ public boolean isAvailable() { return false; } - for (ExchangeClient client : clients){ + for (ExchangeClient client : clients) { if (client.isConnected() - && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)){ + && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { //cannot write == not Available ? - return true ; + return true; } } return false; @@ -114,21 +109,21 @@ public boolean isAvailable() { public void destroy() { //防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭 - if (super.isDestroyed()){ - return ; + if (super.isDestroyed()) { + return; } else { //dubbo check ,避免多次关闭 destroyLock.lock(); - try{ + try { - if (super.isDestroyed()){ - return ; + if (super.isDestroyed()) { + return; } super.destroy(); - if(invokers != null) { + if (invokers != null) { invokers.remove(this); } @@ -142,7 +137,7 @@ public void destroy() { } - }finally { + } finally { destroyLock.unlock(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java deleted file mode 100644 index e9b98a28d2b..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public interface ClientResponseInterceptor { - - void handle(Object response); - -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java similarity index 66% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java index f5cf6b3adb3..21018bfd880 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java @@ -3,7 +3,7 @@ /** * @author Xs */ -public interface ClientRequestInterceptor { +public interface ConsumerInvocationInterceptor { void handle(RpcRequest request); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java new file mode 100644 index 00000000000..ed5f2aaf775 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface ConsumerResultInterceptor { + + void handle(RpcResponse response); + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java new file mode 100644 index 00000000000..62aba5573f4 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java @@ -0,0 +1,8 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public class HttpTrackerComponent { + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java new file mode 100644 index 00000000000..a5072247984 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java @@ -0,0 +1,11 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public class InvocationInterceptor { + + private ConsumerInvocationInterceptor consumerInvocationInterceptor; + + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java deleted file mode 100644 index 5cb41096ba4..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationSpanNameProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.alibaba.dubbo.tracker; - -import com.alibaba.dubbo.rpc.Invocation; - -/** - * @author Xs - */ -public class InvocationSpanNameProvider { - - public String spanName(Invocation invocation) { - return invocation.getMethodName(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java similarity index 60% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java index 9f80836d20f..dc5575d6fd4 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker; -public interface ServerRequestInterceptor { +public interface ProviderInvocationInterceptor { void handle(RpcRequest request); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java similarity index 63% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java index dc847536278..df7562d5d8e 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker; -public interface ServerResponseInterceptor { +public interface ProviderResultInterceptor { void handle(RpcResponse response); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java index 1183c5f647b..c7001121673 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java @@ -2,7 +2,6 @@ /** * @author Xs - * @seeBraveHttpHeaders */ public enum RpcAttachment { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java index 6c38a6b326a..e065a22fa49 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java @@ -2,6 +2,7 @@ import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcInvocation; public class RpcRequest { @@ -22,4 +23,23 @@ public Invocation getInvocation() { return invocation; } + public boolean isTraceableRequest() { + return invocation instanceof RpcInvocation; + } + + public String getMethodName() { + return invocation.getMethodName(); + } + + public void addAttachment(String key, String value) { + ((RpcInvocation) invocation).setAttachment(key, value); + } + + public String getAttachment(String key) { + return invocation.getAttachment(key); + } + + public String providerAddress() { + return invoker.getUrl().getAddress(); + } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java new file mode 100644 index 00000000000..63150f2378b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.Invocation; + +/** + * @author Xs + */ +public class RpcRequestSpanNameProvider { + + public String spanName(RpcRequest rpcRequest) { + return rpcRequest.getMethodName(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java index c963bfac501..8c76f59a5d0 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java @@ -2,6 +2,7 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcResult; public class RpcResponse { @@ -21,4 +22,23 @@ public Invoker getInvoker() { public Result getResult() { return result; } + + public boolean isTraceableResponse() { + return result instanceof RpcResult; + } + + public boolean returnSuccessfully() { + return !result.hasException(); + } + + public String exceptionMessage(){ + if (returnSuccessfully()) { + return "result OK"; + } + Throwable throwable = result.getException(); + if (throwable instanceof NullPointerException) { + return "NullPointerException"; + } + return throwable.getMessage(); + } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index a05b29bb8e3..a3aa2cff007 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -7,13 +7,13 @@ */ public interface RpcTracker { - ClientRequestInterceptor clientRequestInterceptor(); + ConsumerInvocationInterceptor clientRequestInterceptor(); - ClientResponseInterceptor clientResponseInterceptor(); + ConsumerResultInterceptor clientResponseInterceptor(); - ServerRequestInterceptor serverRequestInterceptor(); + ProviderInvocationInterceptor serverRequestInterceptor(); - ServerResponseInterceptor serverResponseInterceptor(); + ProviderResultInterceptor serverResponseInterceptor(); ServletFilter servletFilter(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java index 12359e3d632..4d29eac9bbf 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java @@ -34,8 +34,8 @@ public static RpcTracker getRpcTracker() { return rpcTracker; } - public static RpcTracker mockRpcTracker(String application) { - String urlStr = "zipkin://localhost:9411?application=" + application + "&collector=http"; + public static RpcTracker mockRpcTracker(String address, String application) { + String urlStr = "zipkin://" + address + "?application=" + application + "&collector=http"; URL url = URL.valueOf(urlStr); return create(url); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java index 2986aaf9dc2..b42b65064e4 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java @@ -1,8 +1,8 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientRequestAdapter; import com.github.kristofa.brave.IdConversion; @@ -18,37 +18,37 @@ */ public class BraveClientRequestAdapter implements ClientRequestAdapter { - private final InvocationSpanNameProvider spanNameProvider; + private final RpcRequestSpanNameProvider spanNameProvider; private final RpcRequest rpcRequest; - public BraveClientRequestAdapter(RpcRequest rpcRequest, InvocationSpanNameProvider spanNameProvider) { + public BraveClientRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { this.rpcRequest = rpcRequest; this.spanNameProvider = spanNameProvider; } @Override public String getSpanName() { - return spanNameProvider.spanName(invocation.getRpcInvocation()); + return spanNameProvider.spanName(rpcRequest); } @Override public void addSpanIdToRequest(SpanId spanId) { if (spanId == null) { - invocation.addAttachment(RpcAttachment.Sampled.getName(), "0"); + rpcRequest.addAttachment(RpcAttachment.Sampled.getName(), "0"); } else { - invocation.addAttachment(RpcAttachment.Sampled.getName(), "1"); - invocation.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); - invocation.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); + rpcRequest.addAttachment(RpcAttachment.Sampled.getName(), "1"); + rpcRequest.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); + rpcRequest.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); if (spanId.nullableParentId() != null) { - invocation.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); + rpcRequest.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); } } } @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, invocation.providerAddress()); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); return Collections.singletonList(annotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java deleted file mode 100644 index 9b347feb124..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestInterceptor.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcRequest; - -/** - * @author Xs - */ -public class BraveClientRequestInterceptor implements ClientRequestInterceptor { - - private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; - - private final InvocationSpanNameProvider spanNameProvider; - - public BraveClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor, - InvocationSpanNameProvider spanNameProvider) { - this.clientRequestInterceptor = clientRequestInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public void handle(RpcRequest request) { - clientRequestInterceptor.handle(new BraveClientRequestAdapter(request, spanNameProvider)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java index 6afceaee7fa..3a94de5fd3a 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; +import com.alibaba.dubbo.tracker.RpcResponse; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientResponseAdapter; import com.github.kristofa.brave.KeyValueAnnotation; @@ -12,16 +13,16 @@ */ public class BraveClientResponseAdapter implements ClientResponseAdapter { - private final BraveRpcResult rpcResult; + private final RpcResponse rpcResponse; - public BraveClientResponseAdapter(BraveRpcResult rpcResult) { - this.rpcResult = rpcResult; + public BraveClientResponseAdapter(RpcResponse rpcResponse) { + this.rpcResponse = rpcResponse; } @Override public Collection responseAnnotations() { - if (rpcResult.hasException()) { - KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResult.exception()); + if (!rpcResponse.returnSuccessfully()) { + KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); return Collections.singletonList(statusAnnotation); } return Collections.emptyList(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java deleted file mode 100644 index 0e01e96adb7..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseInterceptor.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.protocol.dubbo.DecodeableRpcResult; -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; - -/** - * @author Xs - */ -public class BraveClientResponseInterceptor implements ClientResponseInterceptor { - - private final com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor; - - - public BraveClientResponseInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { - this.clientResponseInterceptor = clientResponseInterceptor; - } - - @Override - public void handle(Object response) { - if (!(response instanceof RpcResult)) { - return; - } - RpcResult result = (RpcResult) response; - clientResponseInterceptor.handle(new BraveClientResponseAdapter(new BraveRpcResult(result))); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java new file mode 100644 index 00000000000..05a24494f8e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ConsumerInvocationInterceptor; +import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; +import com.github.kristofa.brave.ClientRequestInterceptor; + +/** + * @author Xs + */ +public class BraveConsumerInvocationInterceptor implements ConsumerInvocationInterceptor { + + private final ClientRequestInterceptor clientRequestInterceptor; + + private final RpcRequestSpanNameProvider spanNameProvider; + + public BraveConsumerInvocationInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor, + RpcRequestSpanNameProvider spanNameProvider) { + this.clientRequestInterceptor = clientRequestInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public void handle(RpcRequest request) { + if (!request.isTraceableRequest()) { + return; + } + clientRequestInterceptor.handle(new BraveClientRequestAdapter(request, spanNameProvider)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java new file mode 100644 index 00000000000..736b7ff5feb --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ConsumerResultInterceptor; +import com.alibaba.dubbo.tracker.RpcResponse; +import com.github.kristofa.brave.ClientResponseInterceptor; + +/** + * @author Xs + */ +public class BraveConsumerResultInterceptor implements ConsumerResultInterceptor { + + private final ClientResponseInterceptor clientResponseInterceptor; + + + public BraveConsumerResultInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { + this.clientResponseInterceptor = clientResponseInterceptor; + } + + @Override + public void handle(RpcResponse response) { + if (!response.isTraceableResponse()) { + return; + } + clientResponseInterceptor.handle(new BraveClientResponseAdapter(response)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java new file mode 100644 index 00000000000..d5870dcfa1a --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.ProviderInvocationInterceptor; + +public class BraveProviderInvocationInterceptor implements ProviderInvocationInterceptor { + + private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; + + private final RpcRequestSpanNameProvider spanNameProvider; + + public BraveProviderInvocationInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor, + RpcRequestSpanNameProvider spanNameProvider) { + this.serverRequestInterceptor = serverRequestInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public void handle(RpcRequest request) { + if (!request.isTraceableRequest()) { + return; + } + serverRequestInterceptor.handle(new BraveServerRequestAdapter(request, spanNameProvider)); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java similarity index 62% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java index 0f024ca33df..a7b7ea3ddaf 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java @@ -2,18 +2,21 @@ import com.alibaba.dubbo.tracker.RpcResponse; -import com.alibaba.dubbo.tracker.ServerResponseInterceptor; +import com.alibaba.dubbo.tracker.ProviderResultInterceptor; -public class BraveServerResponseInterceptor implements ServerResponseInterceptor { +public class BraveProviderResultInterceptor implements ProviderResultInterceptor { private final com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor; - public BraveServerResponseInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { + public BraveProviderResultInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { this.serverResponseInterceptor = serverResponseInterceptor; } @Override public void handle(RpcResponse response) { + if (!response.isTraceableResponse()) { + return; + } serverResponseInterceptor.handle(new BraveServerResponseAdapter(response)); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java deleted file mode 100644 index 31727848102..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcInvocation.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcInvocation; - -public class BraveRpcInvocation { - - private final RpcInvocation rpcInvocation; - - public BraveRpcInvocation(RpcInvocation rpcInvocation) { - this.rpcInvocation = rpcInvocation; - } - - public void addAttachment(String key, String value) { - rpcInvocation.setAttachment(key, value); - } - - - public String getAttachment(String key) { - return rpcInvocation.getAttachment(key); - } - - public String providerAddress() { - String address; - Invoker invoker = rpcInvocation.getInvoker(); - if (invoker == null){ - - } - return rpcInvocation.getInvoker().getUrl().getAddress(); - } - - public RpcInvocation getRpcInvocation() { - return rpcInvocation; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java deleted file mode 100644 index 2d2904b23ac..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcResult.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.rpc.RpcResult; - -public class BraveRpcResult { - - private final RpcResult rpcResult; - - public BraveRpcResult(RpcResult rpcResult) { - this.rpcResult = rpcResult; - } - - public boolean hasException() { - return rpcResult.hasException(); - } - - public String exception() { - if (!hasException()) { - return "result OK"; - } - Throwable throwable = rpcResult.getException(); - if (throwable instanceof NullPointerException) { - return "NullPointerException"; - } - return throwable.getMessage(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java index d74e8e4094e..4a6beb08fb2 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java @@ -12,14 +12,13 @@ */ public class BraveRpcTracker implements RpcTracker { - private final BraveClientRequestInterceptor clientRequestInterceptor; + private final BraveConsumerInvocationInterceptor clientRequestInterceptor; - private final BraveClientResponseInterceptor clientResponseInterceptor; + private final BraveConsumerResultInterceptor clientResponseInterceptor; - private final BraveServerRequestInterceptor serverRequestInterceptor; - - private final BraveServerResponseInterceptor serverResponseInterceptor; + private final BraveProviderInvocationInterceptor serverRequestInterceptor; + private final BraveProviderResultInterceptor serverResponseInterceptor; private final BraveServletFilter braveServletFilter; @@ -32,31 +31,31 @@ private BraveRpcTracker(URL url) { builder.spanCollector(SpanCollectorFactory.create(url)); builder.traceSampler(SamplerFactory.create(url)); Brave brave = builder.build(); - clientRequestInterceptor = new BraveClientRequestInterceptor(brave.clientRequestInterceptor(), new InvocationSpanNameProvider()); - clientResponseInterceptor = new BraveClientResponseInterceptor(brave.clientResponseInterceptor()); - serverRequestInterceptor = new BraveServerRequestInterceptor(brave.serverRequestInterceptor(), new InvocationSpanNameProvider()); - serverResponseInterceptor = new BraveServerResponseInterceptor(brave.serverResponseInterceptor()); + clientRequestInterceptor = new BraveConsumerInvocationInterceptor(brave.clientRequestInterceptor(), new RpcRequestSpanNameProvider()); + clientResponseInterceptor = new BraveConsumerResultInterceptor(brave.clientResponseInterceptor()); + serverRequestInterceptor = new BraveProviderInvocationInterceptor(brave.serverRequestInterceptor(), new RpcRequestSpanNameProvider()); + serverResponseInterceptor = new BraveProviderResultInterceptor(brave.serverResponseInterceptor()); braveServletFilter = new BraveServletFilter(new com.github.kristofa.brave.servlet.BraveServletFilter( brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider())); } @Override - public ClientRequestInterceptor clientRequestInterceptor() { + public ConsumerInvocationInterceptor clientRequestInterceptor() { return clientRequestInterceptor; } @Override - public ClientResponseInterceptor clientResponseInterceptor() { + public ConsumerResultInterceptor clientResponseInterceptor() { return clientResponseInterceptor; } @Override - public ServerRequestInterceptor serverRequestInterceptor() { + public ProviderInvocationInterceptor serverRequestInterceptor() { return serverRequestInterceptor; } @Override - public ServerResponseInterceptor serverResponseInterceptor() { + public ProviderResultInterceptor serverResponseInterceptor() { return serverResponseInterceptor; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java index 875aca9c9f3..5c89f690685 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java @@ -1,8 +1,8 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.KeyValueAnnotation; import com.github.kristofa.brave.ServerRequestAdapter; @@ -16,25 +16,25 @@ public class BraveServerRequestAdapter implements ServerRequestAdapter { - private final InvocationSpanNameProvider spanNameProvider; + private final RpcRequestSpanNameProvider spanNameProvider; private final RpcRequest rpcRequest; - public BraveServerRequestAdapter(RpcRequest rpcRequest, InvocationSpanNameProvider spanNameProvider) { + public BraveServerRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { this.spanNameProvider = spanNameProvider; this.rpcRequest = rpcRequest; } @Override public TraceData getTraceData() { - final String sampled = invocation.getAttachment(RpcAttachment.Sampled.getName()); + final String sampled = rpcRequest.getAttachment(RpcAttachment.Sampled.getName()); if (sampled != null) { if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { return TraceData.builder().sample(false).build(); } else { - final String parentSpanId = invocation.getAttachment(RpcAttachment.ParentSpanId.getName()); - final String traceId = invocation.getAttachment(RpcAttachment.TraceId.getName()); - final String spanId = invocation.getAttachment(RpcAttachment.SpanId.getName()); + final String parentSpanId = rpcRequest.getAttachment(RpcAttachment.ParentSpanId.getName()); + final String traceId = rpcRequest.getAttachment(RpcAttachment.TraceId.getName()); + final String spanId = rpcRequest.getAttachment(RpcAttachment.SpanId.getName()); if (traceId != null && spanId != null) { SpanId span = getSpanId(traceId, spanId, parentSpanId); @@ -47,12 +47,12 @@ public TraceData getTraceData() { @Override public String getSpanName() { - return spanNameProvider.spanName(invocation.getRpcInvocation()); + return spanNameProvider.spanName(rpcRequest); } @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, invocation.providerAddress()); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); return Collections.singletonList(annotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java deleted file mode 100644 index 070f26141e0..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestInterceptor.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.tracker.InvocationSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.ServerRequestInterceptor; - -public class BraveServerRequestInterceptor implements ServerRequestInterceptor { - - private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; - - private final InvocationSpanNameProvider spanNameProvider; - - public BraveServerRequestInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor, - InvocationSpanNameProvider spanNameProvider) { - this.serverRequestInterceptor = serverRequestInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public void handle(RpcRequest request) { - serverRequestInterceptor.handle(new BraveServerRequestAdapter(request,spanNameProvider)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java index 950d224becf..c969eeefe29 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java @@ -19,10 +19,10 @@ public BraveServerResponseAdapter(RpcResponse rpcResponse) { @Override public Collection responseAnnotations() { KeyValueAnnotation statusAnnotation; - if (rpcResult.hasException()) { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResult.exception()); - } else { + if (rpcResponse.returnSuccessfully()) { statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); + } else { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); } return Collections.singletonList(statusAnnotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java index 1c3386bdf85..7b9e34f4bbc 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java @@ -7,6 +7,7 @@ import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcResponse; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.TrackerManager; import com.alibaba.dubbo.tracker.filter.ClientRpcTrackerFilter; @@ -19,10 +20,10 @@ public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - RpcTracker rpcTracker = TrackerManager.mockRpcTracker("consumer"); + RpcTracker rpcTracker = TrackerManager.mockRpcTracker("192.168.150.132:9411", "consumer"); rpcTracker.clientRequestInterceptor().handle(new RpcRequest(invoker, invocation)); Result result = invoker.invoke(invocation); - rpcTracker.clientResponseInterceptor().handle(result); + rpcTracker.clientResponseInterceptor().handle(new RpcResponse(invoker, result)); return result; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java index a41e47fdde7..bf82efd1cbc 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java @@ -7,6 +7,7 @@ import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.tracker.RpcRequest; +import com.alibaba.dubbo.tracker.RpcResponse; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.TrackerManager; import com.alibaba.dubbo.tracker.filter.ServerRpcTrackerFilter; @@ -19,10 +20,10 @@ public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - RpcTracker rpcTracker = TrackerManager.mockRpcTracker("provider"); + RpcTracker rpcTracker = TrackerManager.mockRpcTracker("192.168.150.132:9411", "provider"); rpcTracker.serverRequestInterceptor().handle(new RpcRequest(invoker, invocation)); Result result = invoker.invoke(invocation); - rpcTracker.serverResponseInterceptor().handle(result); + rpcTracker.serverResponseInterceptor().handle(new RpcResponse(invoker, result)); return result; } } From fe8ac45861a2115efd55ac3d80a150870576d422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Tue, 17 Jan 2017 21:25:16 +0800 Subject: [PATCH 10/69] add request builder,response builder, PendingReply --- .../dubbo/registry/dubbo/MockedClient.java | 5 - .../remoting/exchange/ExchangeChannelV2.java | 40 ++ .../remoting/exchange/ExchangeClient.java | 2 - .../remoting/exchange/ExchangeClientV2.java | 9 + .../dubbo/remoting/exchange/Interceptor.java | 6 +- .../dubbo/remoting/exchange/Request.java | 114 +++-- .../dubbo/remoting/exchange/Response.java | 124 +++--- .../exchange/codec/ExchangeCodec.java | 94 ++-- .../exchange/support/DefaultFuture.java | 18 +- .../support/header/HeaderExchangeChannel.java | 15 +- .../header/HeaderExchangeChannelV2.java | 223 ++++++++++ .../support/header/HeaderExchangeClient.java | 43 +- .../header/HeaderExchangeClientV2.java | 178 ++++++++ .../support/header/HeaderExchangeHandler.java | 27 +- .../support/header/HeaderExchangeServer.java | 7 +- .../support/header/HeartBeatTask.java | 11 +- .../support/header/HeartbeatHandler.java | 6 +- .../exchange/support/header/PendingReply.java | 32 ++ .../remoting/codec/ExchangeCodecTest.java | 307 +++++++------ .../handler/ConnectChannelHandlerTest.java | 92 ++-- .../handler/HeaderExchangeHandlerTest.java | 125 +++--- .../codec/DeprecatedExchangeCodec.java | 86 ++-- .../com/alibaba/dubbo/rpc/RpcContext.java | 415 +++++++++--------- .../rpc/filter/ConsumerContextFilter.java | 16 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 1 - .../dubbo/DecodeableRpcInvocation.java | 4 +- .../protocol/dubbo/DecodeableRpcResult.java | 3 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 55 ++- .../rpc/protocol/dubbo/DubboInvoker.java | 44 +- .../dubbo/LazyConnectExchangeClient.java | 4 - .../dubbo/ReferenceCountExchangeClient.java | 49 +-- .../rpc/protocol/hessian/HessianProtocol.java | 2 +- .../hessian/HttpClientConnection.java | 1 - .../hessian/OkHttpConnectionFactory.java | 4 +- .../rpc/protocol/thrift/ThriftCodec.java | 62 +-- .../rpc/protocol/thrift/ThriftCodecTest.java | 369 ++++++++-------- .../heartbeat/HeartBeatExchangeHandler.java | 35 +- .../alibaba/dubbo/tracker/RpcAttachment.java | 4 +- .../dubbo/tracker/RpcTrackerEngine.java | 4 + .../filter/BraveClientRpcTrackerFilter.java | 2 +- .../filter/BraveServerRpcTrackerFilter.java | 2 +- 41 files changed, 1511 insertions(+), 1129 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java index 562348179f0..3f24b30c458 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java @@ -257,9 +257,4 @@ public void reset(URL url) { @Deprecated public void reset(com.alibaba.dubbo.common.Parameters parameters) { } - - @Override - public void addInterceptor(Interceptor interceptor) { - - } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java new file mode 100644 index 00000000000..0cdd8140275 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java @@ -0,0 +1,40 @@ +package com.alibaba.dubbo.remoting.exchange; + +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.RemotingException; + +public interface ExchangeChannelV2 extends Channel { + /** + * send request. + * + * @param request + * @return response + * @throws RemotingException + */ + Response request(Request request) throws RemotingException; + + /** + * send request. + * + * @param request + * @param timeout + * @return response future + * @throws RemotingException + */ + Response request(Request request, int timeout) throws RemotingException; + + /** + * get message handler. + * + * @return message handler + */ + ExchangeHandler getExchangeHandler(); + + /** + * graceful close. + * + * @param timeout + */ + void close(int timeout); + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java index ffb0decc242..73f80e8507f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java @@ -24,6 +24,4 @@ */ public interface ExchangeClient extends Client, ExchangeChannel { - void addInterceptor(Interceptor interceptor); - } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java new file mode 100644 index 00000000000..3722c7b9a9f --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java @@ -0,0 +1,9 @@ +package com.alibaba.dubbo.remoting.exchange; + +import com.alibaba.dubbo.remoting.Client; + +public interface ExchangeClientV2 extends Client, ExchangeChannelV2 { + + void addInterceptor(Interceptor interceptor); + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java index 6704c5c44ca..28d2b6bce24 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java @@ -7,13 +7,13 @@ */ public interface Interceptor { - ResponseFuture intercept(Chain chain); + Response intercept(Chain chain); interface Chain { - Object request(); + Request request(); - ResponseFuture proceed(Object request, int timeout) throws RemotingException; + Response proceed(Request request, int timeout) throws RemotingException; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java index 7b7a005f689..29bd640b4f9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java @@ -35,22 +35,92 @@ public class Request { private final long mId; - private String mVersion; + private final String mVersion; - private boolean mTwoWay = true; + private final boolean mTwoWay; - private boolean mEvent = false; + private final boolean mEvent; - private boolean mBroken = false; + private final boolean mBroken; - private Object mData; + private final Object mData; - public Request() { - mId = newId(); + public Request(Builder builder) { + this.mId = builder.mId; + this.mVersion = builder.mVersion; + this.mTwoWay = builder.mTwoWay; + this.mEvent = builder.mEvent; + this.mBroken = builder.mBroken; + this.mData = builder.mData; } - public Request(long id) { - mId = id; + public Builder newBuilder() { + return new Builder(this); + } + + public static class Builder { + private long mId; + private String mVersion; + private boolean mTwoWay = true; + private boolean mEvent = false; + private boolean mBroken = false; + private Object mData; + + public Builder() { + } + + public Builder(long mId) { + this.mId = mId; + } + + public Builder(Request request) { + this.mId = request.mId; + this.mVersion = request.mVersion; + this.mTwoWay = request.mTwoWay; + this.mEvent = request.mEvent; + this.mBroken = request.mBroken; + this.mData = request.mData; + + } + + public Builder id(long mId) { + this.mId = mId; + return this; + } + + public Builder newId() { + this.mId = Request.newId(); + return this; + } + + public Builder version(String mVersion) { + this.mVersion = mVersion; + return this; + } + + public Builder twoWay(boolean mTwoWay) { + this.mTwoWay = mTwoWay; + return this; + } + + public Builder isEvent(boolean mEvent) { + this.mEvent = mEvent; + return this; + } + + public Builder broken(boolean mBroken) { + this.mBroken = mBroken; + return this; + } + + public Builder data(Object mData) { + this.mData = mData; + return this; + } + + public Request build() { + return new Request(this); + } } public long getId() { @@ -61,53 +131,27 @@ public String getVersion() { return mVersion; } - public void setVersion(String version) { - mVersion = version; - } - public boolean isTwoWay() { return mTwoWay; } - public void setTwoWay(boolean twoWay) { - mTwoWay = twoWay; - } - public boolean isEvent() { return mEvent; } - public void setEvent(String event) { - mEvent = true; - mData = event; - } - public boolean isBroken() { return mBroken; } - public void setBroken(boolean mBroken) { - this.mBroken = mBroken; - } public Object getData() { return mData; } - public void setData(Object msg) { - mData = msg; - } - public boolean isHeartbeat() { return mEvent && HEARTBEAT_EVENT == mData; } - public void setHeartbeat(boolean isHeartbeat) { - if (isHeartbeat) { - setEvent(HEARTBEAT_EVENT); - } - } - private static long newId() { // getAndIncrement()增长到MAX_VALUE时,再增长会变为MIN_VALUE,负数也可以做为ID return INVOKE_ID.getAndIncrement(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java index 4d09c46ea56..3c6f838e7d2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java @@ -24,137 +24,151 @@ public class Response { public static final String HEARTBEAT_EVENT = null; - public static final String READONLY_EVENT = "R"; - /** * ok. */ public static final byte OK = 20; - /** * client side timeout. */ public static final byte CLIENT_TIMEOUT = 30; - /** * server side timeout. */ public static final byte SERVER_TIMEOUT = 31; - /** * request format error. */ public static final byte BAD_REQUEST = 40; - /** * response format error. */ public static final byte BAD_RESPONSE = 50; - /** * service not found. */ public static final byte SERVICE_NOT_FOUND = 60; - /** * service error. */ public static final byte SERVICE_ERROR = 70; - /** * internal server error. */ public static final byte SERVER_ERROR = 80; - /** * internal server error. */ public static final byte CLIENT_ERROR = 90; - private long mId = 0; + private final long mId; + private final String mVersion; + private final byte mStatus; + private final boolean mEvent; + private final String mErrorMsg; + private final Object mResult; + + public Response(Builder builder) { + this.mId = builder.mId; + this.mVersion = builder.mVersion; + this.mStatus = builder.mStatus; + this.mEvent = builder.mEvent; + this.mErrorMsg = builder.mErrorMsg; + this.mResult = builder.mResult; + } - private String mVersion; + public Builder newBuilder() { + return new Builder(this); + } - private byte mStatus = OK; + public static class Builder { + private long mId = 0; + private String mVersion; + private byte mStatus = OK; + private boolean mEvent = false; + private String mErrorMsg; + private Object mResult; - private boolean mEvent = false; + public Builder() { + } - private String mErrorMsg; + public Builder(long mId) { + this.mId = mId; + } - private Object mResult; + public Builder(Response response) { + this.mId = response.mId; + this.mVersion = response.mVersion; + this.mStatus = response.mStatus; + this.mEvent = response.mEvent; + this.mErrorMsg = response.mErrorMsg; + this.mResult = response.mResult; + } - public Response() { - } + public Builder id(long mId) { + this.mId = mId; + return this; + } - public Response(long id) { - mId = id; - } + public Builder version(String mVersion) { + this.mVersion = mVersion; + return this; + } + + public Builder status(byte mStatus) { + this.mStatus = mStatus; + return this; + } - public Response(long id, String version) { - mId = id; - mVersion = version; + public Builder isEvent(boolean mEvent) { + this.mEvent = mEvent; + return this; + } + + public Builder errorMsg(String mErrorMsg) { + this.mErrorMsg = mErrorMsg; + return this; + } + + public Builder result(Object mResult) { + this.mResult = mResult; + return this; + } + + public Response build() { + return new Response(this); + } } public long getId() { return mId; } - public void setId(long id) { - mId = id; - } - public String getVersion() { return mVersion; } - public void setVersion(String version) { - mVersion = version; - } - public byte getStatus() { return mStatus; } - public void setStatus(byte status) { - mStatus = status; - } - public boolean isEvent() { return mEvent; } - public void setEvent(String event) { - mEvent = true; - mResult = event; - } - public boolean isHeartbeat() { return mEvent && HEARTBEAT_EVENT == mResult; } - @Deprecated - public void setHeartbeat(boolean isHeartbeat) { - if (isHeartbeat) { - setEvent(HEARTBEAT_EVENT); - } - } - public Object getResult() { return mResult; } - public void setResult(Object msg) { - mResult = msg; - } - public String getErrorMessage() { return mErrorMsg; } - public void setErrorMessage(String msg) { - mErrorMsg = msg; - } @Override public String toString() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index e95ecb84fde..dd3ab8c1454 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -15,6 +15,7 @@ */ package com.alibaba.dubbo.remoting.exchange.codec; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.io.Bytes; import com.alibaba.dubbo.common.io.StreamUtils; import com.alibaba.dubbo.common.logger.Logger; @@ -47,17 +48,14 @@ public class ExchangeCodec extends TelnetCodec { private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class); - // header length. protected static final int HEADER_LENGTH = 16; - // magic header. protected static final short MAGIC = (short) 0xdabb; protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; - // message flag. protected static final byte FLAG_REQUEST = (byte) 0x80; @@ -151,56 +149,54 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. - Response res = new Response(id); - if ((flag & FLAG_EVENT) != 0) { - res.setEvent(Response.HEARTBEAT_EVENT); + Response.Builder builder = new Response.Builder(id); + boolean isEvent = (flag & FLAG_EVENT) != 0; + builder.isEvent(isEvent); + if (isEvent) { + builder.result(Response.HEARTBEAT_EVENT); } // get status. byte status = header[3]; - res.setStatus(status); + builder.status(status); if (status == Response.OK) { try { Object data; - if (res.isHeartbeat()) { - data = decodeHeartbeatData(channel, in); - } else if (res.isEvent()) { + if (isEvent) { data = decodeEventData(channel, in); } else { data = decodeResponseData(channel, in, getRequestData(id)); } - res.setResult(data); + builder.result(data); } catch (Throwable t) { - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + builder.status(Response.CLIENT_ERROR); + builder.errorMsg(StringUtils.toString(t)); } } else { - res.setErrorMessage(in.readUTF()); + builder.errorMsg(in.readUTF()); } - return res; + return builder.build(); } else { // decode request. - Request req = new Request(id); - req.setVersion("2.0.0"); - req.setTwoWay((flag & FLAG_TWOWAY) != 0); - if ((flag & FLAG_EVENT) != 0) { - req.setEvent(Request.HEARTBEAT_EVENT); + Request.Builder builder = new Request.Builder(id); + builder.version(Version.getVersion()).twoWay((flag & FLAG_TWOWAY) != 0); + boolean isEvent = (flag & FLAG_EVENT) != 0; + if (isEvent) { + builder.isEvent(true).data(Request.HEARTBEAT_EVENT); } try { Object data; - if (req.isHeartbeat()) { - data = decodeHeartbeatData(channel, in); - } else if (req.isEvent()) { + if (isEvent) { data = decodeEventData(channel, in); } else { data = decodeRequestData(channel, in); } - req.setData(data); + builder.data(data); } catch (Throwable t) { // bad request - req.setBroken(true); - req.setData(t); + builder.broken(true); + builder.data(t); } - return req; + return builder.build(); } } @@ -220,16 +216,12 @@ protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) byte[] header = new byte[HEADER_LENGTH]; // set magic number. Bytes.short2bytes(MAGIC, header); - // set request and serialization flag. header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); - if (req.isTwoWay()) header[2] |= FLAG_TWOWAY; if (req.isEvent()) header[2] |= FLAG_EVENT; - // set request id. Bytes.long2bytes(req.getId(), header, 4); - // encode request data. int savedWriteIndex = buffer.writerIndex(); buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); @@ -285,7 +277,7 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re // encode response data or error message. if (status == Response.OK) { if (res.isHeartbeat()) { - encodeHeartbeatData(channel, out, res.getResult()); + encodeEventData(channel, out, res.getResult()); } else { encodeResponseData(channel, out, res.getResult()); } @@ -314,12 +306,10 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re try { // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理? logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); - - Response r = new Response(res.getId(), res.getVersion()); - r.setStatus(Response.BAD_RESPONSE); - r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); - channel.send(r); - + Response.Builder builder = new Response.Builder(res.getId()); + builder.version(res.getVersion()).status(Response.BAD_RESPONSE); + builder.errorMsg("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); + channel.send(builder.build()); return; } catch (RemotingException e) { logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); @@ -344,15 +334,6 @@ protected Object decodeData(ObjectInput in) throws IOException { return decodeRequestData(in); } - @Deprecated - protected Object decodeHeartbeatData(ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - protected Object decodeRequestData(ObjectInput in) throws IOException { try { return in.readObject(); @@ -378,11 +359,6 @@ private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } - @Deprecated - protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { - encodeEventData(out, data); - } - protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); } @@ -404,15 +380,6 @@ protected Object decodeEventData(Channel channel, ObjectInput in) throws IOExcep } } - @Deprecated - protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { return decodeRequestData(in); } @@ -434,11 +401,6 @@ private void encodeEventData(Channel channel, ObjectOutput out, Object data) thr encodeEventData(out, data); } - @Deprecated - protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeHeartbeatData(out, data); - } - protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java index 17f1987d4db..6b29e269b98 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java @@ -1,12 +1,12 @@ /* * Copyright 1999-2011 Alibaba Group. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -111,9 +111,7 @@ public Object get(int timeout) throws RemotingException { } public void cancel() { - Response errorResult = new Response(id); - errorResult.setErrorMessage("request future has been canceled."); - response = errorResult; + response = response.newBuilder().errorMsg("request future has been canceled.").build(); FUTURES.remove(id); CHANNELS.remove(id); } @@ -290,10 +288,10 @@ public void run() { } if (System.currentTimeMillis() - future.getStartTimestamp() > future.getTimeout()) { // create exception response. - Response timeoutResponse = new Response(future.getId()); - // set timeout status. - timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); - timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); + Response.Builder builder = new Response.Builder(future.getId()); + builder.status(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); + builder.errorMsg(future.getTimeoutMessage(true)); + Response timeoutResponse = builder.build(); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index b46ddc715fd..d8d5903dd29 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -17,6 +17,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.remoting.Channel; @@ -83,10 +84,9 @@ public void send(Object message, boolean sent) throws RemotingException { || message instanceof String) { channel.send(message, sent); } else { - Request request = new Request(); - request.setVersion("2.0.0"); - request.setTwoWay(false); - request.setData(message); + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).twoWay(false).data(message); + Request request = builder.build(); channel.send(request, sent); } } @@ -101,10 +101,9 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept ", cause: The channel " + this + " is closed!"); } // create request. - Request req = new Request(); - req.setVersion("2.0.0"); - req.setTwoWay(true); - req.setData(request); + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).twoWay(true).data(request); + Request req = builder.build(); DefaultFuture future = new DefaultFuture(channel, req, timeout); try { channel.send(req); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java new file mode 100644 index 00000000000..4652cc398e1 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java @@ -0,0 +1,223 @@ +package com.alibaba.dubbo.remoting.exchange.support.header; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.ExchangeChannelV2; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; + +import java.net.InetSocketAddress; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +public class HeaderExchangeChannelV2 implements ExchangeChannelV2 { + + private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeChannel.class); + + private static final String CHANNEL_KEY = HeaderExchangeChannelV2.class.getName() + ".CHANNEL"; + + private static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); + + private final Channel channel; + + private volatile boolean closed = false; + + + HeaderExchangeChannelV2(Channel channel) { + if (channel == null) { + throw new IllegalArgumentException("channel == null"); + } + this.channel = channel; + } + + static HeaderExchangeChannel getOrAddChannel(Channel ch) { + if (ch == null) { + return null; + } + HeaderExchangeChannel ret = (HeaderExchangeChannel) ch.getAttribute(CHANNEL_KEY); + if (ret == null) { + ret = new HeaderExchangeChannel(ch); + if (ch.isConnected()) { + ch.setAttribute(CHANNEL_KEY, ret); + } + } + return ret; + } + + static void removeChannelIfDisconnected(Channel ch) { + if (ch != null && !ch.isConnected()) { + ch.removeAttribute(CHANNEL_KEY); + } + } + + public void send(Object message) throws RemotingException { + send(message, getUrl().getParameter(Constants.SENT_KEY, false)); + } + + public void send(Object message, boolean sent) throws RemotingException { + if (closed) { + throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + + ", cause: The channel " + this + " is closed!"); + } + if (message instanceof Request + || message instanceof Response + || message instanceof String) { + channel.send(message, sent); + } else { + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).twoWay(false).data(message); + Request request = builder.build(); + channel.send(request, sent); + } + } + + public Response request(Request request) throws RemotingException { + return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + } + + public Response request(Request request, int timeout) throws RemotingException { + if (closed) { + throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + + ", cause: The channel " + this + " is closed!"); + } + Long requestId = request.getId(); + PendingReply pendingReply = new PendingReply(requestId); + addPendingReply(pendingReply); + try { + channel.send(request); + } catch (RemotingException e) { + removePendingReply(pendingReply); + throw e; + } + LinkedBlockingQueue reply = pendingReply.getQueue(); + Response response = null; + try { + response = (timeout < 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + throw new RemotingException(this, e); + } finally { + removePendingReply(pendingReply); + } + return response; + } + + private static void addPendingReply(PendingReply pendingReply) { + REPLY_HOLDER.putIfAbsent(pendingReply.getSavedReplyTo(), pendingReply); + } + + private static void removePendingReply(PendingReply pendingReply) { + REPLY_HOLDER.remove(pendingReply.getSavedReplyTo()); + } + + public static void handleResponse(Response response) { + PendingReply pendingReply = REPLY_HOLDER.get(response.getId()); + if (pendingReply == null) { + logger.warn("Response received after timeout for " + response); + return; + } + LinkedBlockingQueue replyHandoff = pendingReply.getQueue(); + replyHandoff.add(response); + } + + public boolean isClosed() { + return closed; + } + + public void close() { + try { + channel.close(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + } + + // graceful close + public void close(int timeout) { + if (closed) { + return; + } + closed = true; + if (timeout > 0) { + long start = System.currentTimeMillis(); +// while (DefaultFuture.hasFuture(HeaderExchangeChannelV2.this) +// && System.currentTimeMillis() - start < timeout) { +// try { +// Thread.sleep(10); +// } catch (InterruptedException e) { +// logger.warn(e.getMessage(), e); +// } +// } + } + close(); + } + + public InetSocketAddress getLocalAddress() { + return channel.getLocalAddress(); + } + + public InetSocketAddress getRemoteAddress() { + return channel.getRemoteAddress(); + } + + public URL getUrl() { + return channel.getUrl(); + } + + public boolean isConnected() { + return channel.isConnected(); + } + + public ChannelHandler getChannelHandler() { + return channel.getChannelHandler(); + } + + public ExchangeHandler getExchangeHandler() { + return (ExchangeHandler) channel.getChannelHandler(); + } + + public Object getAttribute(String key) { + return channel.getAttribute(key); + } + + public void setAttribute(String key, Object value) { + channel.setAttribute(key, value); + } + + public void removeAttribute(String key) { + channel.removeAttribute(key); + } + + public boolean hasAttribute(String key) { + return channel.hasAttribute(key); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (channel.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + HeaderExchangeChannelV2 other = (HeaderExchangeChannelV2) obj; + return channel.equals(other.channel); + } + + @Override + public String toString() { + return channel.toString(); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index cbb8a59e2a4..97f0f97e35a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -47,6 +47,7 @@ public class HeaderExchangeClient implements ExchangeClient { private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); + // 心跳定时器 private ScheduledFuture heartbeatTimer; @@ -183,47 +184,7 @@ public ResponseFuture request(Object request) throws RemotingException { } public ResponseFuture request(Object request, int timeout) throws RemotingException { - Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, request); - return chain.proceed(request, timeout); - } - - @Override - public void addInterceptor(Interceptor interceptor) { - interceptors.add(interceptor); - } - - /** - * @author Xs request interceptor - */ - class ExchangeClientInterceptorChain implements Interceptor.Chain { - - private final int index; - - private final Object request; - - ExchangeClientInterceptorChain(int index, Object request) { - this.index = index; - this.request = request; - } - - @Override - public Object request() { - return request; - } - - @Override - public ResponseFuture proceed(Object request, int timeout) throws RemotingException { - if (index < interceptors.size()) { - Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request); - Interceptor interceptor = interceptors.get(index); - ResponseFuture responseFuture = interceptor.intercept(chain); - if (responseFuture == null) { - throw new NullPointerException("interceptor " + interceptor - + " returned null"); - } - } - return channel.request(request, timeout); - } + return channel.request(request, timeout); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java new file mode 100644 index 00000000000..3cc7a19cab7 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java @@ -0,0 +1,178 @@ +package com.alibaba.dubbo.remoting.exchange.support.header; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Client; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.*; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; + +/** + * @author yanss + */ +public class HeaderExchangeClientV2 implements ExchangeClientV2 { + + private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeClient.class); + + private final Client client; + + private final HeaderExchangeChannelV2 channel; + + private final List interceptors = new ArrayList(); + + public HeaderExchangeClientV2(Client client) { + if (client == null) { + throw new IllegalArgumentException("client == null"); + } + this.client = client; + this.channel = new HeaderExchangeChannelV2(client); + String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); + } + + public URL getUrl() { + return channel.getUrl(); + } + + public InetSocketAddress getRemoteAddress() { + return channel.getRemoteAddress(); + } + + public ChannelHandler getChannelHandler() { + return channel.getChannelHandler(); + } + + public boolean isConnected() { + return channel.isConnected(); + } + + public InetSocketAddress getLocalAddress() { + return channel.getLocalAddress(); + } + + @Override + public Response request(Request request) throws RemotingException { + return null; + } + + @Override + public Response request(Request request, int timeout) throws RemotingException { + return null; + } + + public ExchangeHandler getExchangeHandler() { + return channel.getExchangeHandler(); + } + + public void send(Object message) throws RemotingException { + channel.send(message); + } + + public void send(Object message, boolean sent) throws RemotingException { + channel.send(message, sent); + } + + public boolean isClosed() { + return channel.isClosed(); + } + + public void close() { + channel.close(); + } + + public void close(int timeout) { + channel.close(timeout); + } + + public void reset(URL url) { + client.reset(url); + } + + @Deprecated + public void reset(com.alibaba.dubbo.common.Parameters parameters) { + reset(getUrl().addParameters(parameters.getParameters())); + } + + public void reconnect() throws RemotingException { + client.reconnect(); + } + + public Object getAttribute(String key) { + return channel.getAttribute(key); + } + + public void setAttribute(String key, Object value) { + channel.setAttribute(key, value); + } + + public void removeAttribute(String key) { + channel.removeAttribute(key); + } + + public boolean hasAttribute(String key) { + return channel.hasAttribute(key); + } + + + public Response request(Object request) throws RemotingException { + return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + } + + public Response request(Object request, int timeout) throws RemotingException { + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).twoWay(true).data(request); + Request req = builder.build(); + Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, req); + return chain.proceed(req, timeout); + } + + public void addInterceptor(Interceptor interceptor) { + interceptors.add(interceptor); + } + + /** + * @author Xs request interceptor + */ + class ExchangeClientInterceptorChain implements Interceptor.Chain { + + private final int index; + + private final Request request; + + ExchangeClientInterceptorChain(int index, Request request) { + this.index = index; + this.request = request; + } + + @Override + public Request request() { + return request; + } + + @Override + public Response proceed(Request request, int timeout) throws RemotingException { + if (index < interceptors.size()) { + Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request); + Interceptor interceptor = interceptors.get(index); + Response response = interceptor.intercept(chain); + if (response == null) { + throw new NullPointerException("interceptor " + interceptor + + " returned null"); + } + return response; + } + return channel.request(request, timeout); + } + } + + @Override + public String toString() { + return "HeaderExchangeClient [channel=" + channel + "]"; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 774d7abd9c3..7a2a05c5029 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -64,31 +64,28 @@ void handlerEvent(Channel channel, Request req) throws RemotingException { } Response handleRequest(ExchangeChannel channel, Request req) throws RemotingException { - Response res = new Response(req.getId(), req.getVersion()); + Response.Builder builder = new Response.Builder(req.getId()); + builder.version(req.getVersion()); if (req.isBroken()) { Object data = req.getData(); - String msg; if (data == null) msg = null; else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data); else msg = data.toString(); - res.setErrorMessage("Fail to decode request due to: " + msg); - res.setStatus(Response.BAD_REQUEST); - - return res; + builder.errorMsg("Fail to decode request due to: " + msg); + builder.status(Response.BAD_REQUEST); + return builder.build(); } // find handler by message class. Object msg = req.getData(); try { // handle data. Object result = handler.reply(channel, msg); - res.setStatus(Response.OK); - res.setResult(result); + builder.status(Response.OK).result(result); } catch (Throwable e) { - res.setStatus(Response.SERVICE_ERROR); - res.setErrorMessage(StringUtils.toString(e)); + builder.status(Response.SERVICE_ERROR).errorMsg(StringUtils.toString(e)); } - return res; + return builder.build(); } void handleResponse(Channel channel, Response response) throws RemotingException { @@ -161,7 +158,6 @@ public void received(Channel channel, Object message) throws RemotingException { ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); try { if (message instanceof Request) { - // handle request. Request request = (Request) message; if (request.isEvent()) { handlerEvent(channel, request); @@ -200,10 +196,9 @@ public void caught(Channel channel, Throwable exception) throws RemotingExceptio if (msg instanceof Request) { Request req = (Request) msg; if (req.isTwoWay() && !req.isHeartbeat()) { - Response res = new Response(req.getId(), req.getVersion()); - res.setStatus(Response.SERVER_ERROR); - res.setErrorMessage(StringUtils.toString(e)); - channel.send(res); + Response.Builder builder = new Response.Builder(req.getId()); + builder.version(req.getVersion()).status(Response.SERVER_ERROR).errorMsg(StringUtils.toString(e)); + channel.send(builder.build()); return; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 5144cc6807b..750bf2f9560 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -122,10 +122,9 @@ public void close(final int timeout) { } private void sendChannelReadOnlyEvent() { - Request request = new Request(); - request.setEvent(Request.READONLY_EVENT); - request.setTwoWay(false); - request.setVersion(Version.getVersion()); + Request.Builder builder = new Request.Builder(); + builder.newId().twoWay(false).version(Version.getVersion()).isEvent(true).data(Request.READONLY_EVENT); + Request request = builder.build(); Collection channels = getChannels(); for (Channel channel : channels) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java index 909d59fd5e5..a3197bed9d9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java @@ -16,6 +16,7 @@ package com.alibaba.dubbo.remoting.exchange.support.header; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.remoting.Channel; @@ -57,11 +58,11 @@ public void run() { HeaderExchangeHandler.KEY_WRITE_TIMESTAMP); if ((lastRead != null && now - lastRead > heartbeat) || (lastWrite != null && now - lastWrite > heartbeat)) { - Request req = new Request(); - req.setVersion("2.0.0"); - req.setTwoWay(true); - req.setEvent(Request.HEARTBEAT_EVENT); - channel.send(req); + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()). + twoWay(true).isEvent(true).data(Request.HEARTBEAT_EVENT); + Request request = builder.build(); + channel.send(request); if (logger.isDebugEnabled()) { logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java index c357470d728..44ec5f90282 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java @@ -63,8 +63,10 @@ public void received(Channel channel, Object message) throws RemotingException { if (isHeartbeatRequest(message)) { Request req = (Request) message; if (req.isTwoWay()) { - Response res = new Response(req.getId(), req.getVersion()); - res.setEvent(Response.HEARTBEAT_EVENT); + Response res = new Response.Builder(req.getId()). + version(req.getVersion()). + isEvent(true). + result(Response.HEARTBEAT_EVENT).build(); channel.send(res); if (logger.isInfoEnabled()) { int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java new file mode 100644 index 00000000000..bf13f75372c --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java @@ -0,0 +1,32 @@ +package com.alibaba.dubbo.remoting.exchange.support.header; + +import com.alibaba.dubbo.remoting.exchange.Response; + +import java.util.concurrent.LinkedBlockingQueue; + +/** + * ADD CALLBACK HERE ?? + */ +public class PendingReply { + + private volatile Long savedReplyTo; + + private final LinkedBlockingQueue queue; + + public PendingReply(Long savedReplyTo) { + this.savedReplyTo = savedReplyTo; + this.queue = new LinkedBlockingQueue(); + } + + public Long getSavedReplyTo() { + return savedReplyTo; + } + + public void setSavedReplyTo(Long savedReplyTo) { + this.savedReplyTo = savedReplyTo; + } + + public LinkedBlockingQueue getQueue() { + return queue; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index 14500fed791..b0a6da6cd0c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -16,15 +16,8 @@ package com.alibaba.dubbo.remoting.codec; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; - -import org.junit.Before; -import org.junit.Test; - import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.io.Bytes; import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; @@ -37,49 +30,54 @@ import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; - import junit.framework.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; + import static org.junit.Assert.fail; /** * @author chao.liuc - * byte 16 - * 0-1 magic code - * 2 flag - * 8 - 1-request/0-response - * 7 - two way - * 6 - heartbeat - * 1-5 serialization id - * 3 status - * 20 ok - * 90 error? - * 4-11 id (long) - * 12 -15 datalength - * + * byte 16 + * 0-1 magic code + * 2 flag + * 8 - 1-request/0-response + * 7 - two way + * 6 - heartbeat + * 1-5 serialization id + * 3 status + * 20 ok + * 90 error? + * 4-11 id (long) + * 12 -15 datalength */ -public class ExchangeCodecTest extends TelnetCodecTest{ +public class ExchangeCodecTest extends TelnetCodecTest { // magic header. - private static final short MAGIC = (short) 0xdabb; - private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; - private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; + private static final short MAGIC = (short) 0xdabb; + private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; + private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; Serialization serialization = getSerialization(Constants.DEFAULT_REMOTING_SERIALIZATION); - - - private Object decode(byte[] request) throws IOException{ + + private Object decode(byte[] request) throws IOException { ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); AbstractMockChannel channel = getServerSideChannel(url); //decode Object obj = codec.decode(channel, buffer); return obj; } - - private byte[] getRequestBytes(Object obj, byte[] header) throws IOException{ + + private byte[] getRequestBytes(Object obj, byte[] header) throws IOException { // encode request data. UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); ObjectOutput out = serialization.serialize(url, bos); out.writeObject(obj); - + out.flushBuffer(); bos.flush(); bos.close(); @@ -89,60 +87,62 @@ private byte[] getRequestBytes(Object obj, byte[] header) throws IOException{ byte[] request = join(header, data); return request; } - - private byte[] assemblyDataProtocol(byte[] header){ + + private byte[] assemblyDataProtocol(byte[] header) { Person request = new Person(); byte[] newbuf = join(header, objectToByte(request)); return newbuf; } - + private static Serialization getSerialization(String name) { Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); return serialization; } //=================================================================================== - + @Before public void setUp() throws Exception { codec = new ExchangeCodec(); } + @Test - public void test_Decode_Error_MagicNum() throws IOException{ - HashMap inputBytes = new HashMap(); - inputBytes.put( new byte[] { 0 }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); - inputBytes.put( new byte[] { MAGIC_HIGH, 0 }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); - inputBytes.put( new byte[] { 0 , MAGIC_LOW }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); - - for (byte[] input : inputBytes.keySet()){ - testDecode_assertEquals(assemblyDataProtocol(input) ,inputBytes.get(input)); + public void test_Decode_Error_MagicNum() throws IOException { + HashMap inputBytes = new HashMap(); + inputBytes.put(new byte[]{0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + inputBytes.put(new byte[]{MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + inputBytes.put(new byte[]{0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + + for (byte[] input : inputBytes.keySet()) { + testDecode_assertEquals(assemblyDataProtocol(input), inputBytes.get(input)); } } - + @Test - public void test_Decode_Error_Length() throws IOException{ - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + public void test_Decode_Error_Length() throws IOException { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - + Channel channel = getServerSideChannel(url); - byte[] baddata = new byte[]{1,2}; + byte[] baddata = new byte[]{1, 2}; ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata)); - Response obj = (Response)codec.decode(channel, buffer); + Response obj = (Response) codec.decode(channel, buffer); Assert.assertEquals(person, obj.getResult()); //only decode necessary bytes Assert.assertEquals(request.length, buffer.readerIndex()); } + @Test - public void test_Decode_Error_Response_Object() throws IOException{ + public void test_Decode_Error_Response_Object() throws IOException { //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); //bad object - byte[] badbytes = new byte[]{-1,-2,-3,-4,-3,-4,-3,-4,-3,-4,-3,-4}; + byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); - - Response obj = (Response)decode(request); + + Response obj = (Response) decode(request); Assert.assertEquals(90, obj.getStatus()); } @@ -157,22 +157,24 @@ public void test_Decode_Check_Payload() throws IOException { Assert.assertTrue(expected.getMessage().startsWith("Data length too large: " + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); } } + @Test - public void test_Decode_Header_Need_Readmore() throws IOException{ - byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; + public void test_Decode_Header_Need_Readmore() throws IOException { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } - + @Test - public void test_Decode_Body_Need_Readmore() throws IOException{ - byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0, 0, 0, 0 , 1 ,1, 'a', 'a' }; + public void test_Decode_Body_Need_Readmore() throws IOException { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } + @Test - public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException{ + public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException { // - byte[] header = new byte[] { 0, 0, MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; - + byte[] header = new byte[]{0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header); Object obj = codec.decode(channel, buffer); @@ -180,203 +182,200 @@ public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException{ //如果telnet数据与request数据在同一个数据包中,不能因为telnet没有结尾字符而影响其他数据的接收. Assert.assertEquals(2, buffer.readerIndex()); } - + @Test - public void test_Decode_Return_Response_Person() throws IOException{ + public void test_Decode_Return_Response_Person() throws IOException { //00000010-response/oneway/hearbeat=false/hessian |20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 2, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - - Response obj = (Response)decode(request); + + Response obj = (Response) decode(request); Assert.assertEquals(20, obj.getStatus()); Assert.assertEquals(person, obj.getResult()); System.out.println(obj); } - + @Test //status输入有问题,序列化时读取信息出错. - public void test_Decode_Return_Response_Error() throws IOException{ - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 2, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + public void test_Decode_Return_Response_Error() throws IOException { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 2, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String errorString = "encode request data error "; byte[] request = getRequestBytes(errorString, header); - Response obj = (Response)decode(request); + Response obj = (Response) decode(request); Assert.assertEquals(90, obj.getStatus()); Assert.assertEquals(errorString, obj.getErrorMessage()); } + @Test - public void test_Decode_Return_Request_Event_Object() throws IOException{ + public void test_Decode_Return_Request_Event_Object() throws IOException { //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - - Request obj = (Request)decode(request); + + Request obj = (Request) decode(request); Assert.assertEquals(person, obj.getData()); Assert.assertEquals(true, obj.isTwoWay()); Assert.assertEquals(true, obj.isEvent()); Assert.assertEquals("2.0.0", obj.getVersion()); System.out.println(obj); } - + @Test - public void test_Decode_Return_Request_Event_String() throws IOException{ + public void test_Decode_Return_Request_Event_String() throws IOException { //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String event = Request.READONLY_EVENT; byte[] request = getRequestBytes(event, header); - - Request obj = (Request)decode(request); + + Request obj = (Request) decode(request); Assert.assertEquals(event, obj.getData()); Assert.assertEquals(true, obj.isTwoWay()); Assert.assertEquals(true, obj.isEvent()); Assert.assertEquals("2.0.0", obj.getVersion()); System.out.println(obj); } - + @Test - public void test_Decode_Return_Request_Heartbeat_Object() throws IOException{ + public void test_Decode_Return_Request_Heartbeat_Object() throws IOException { //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xff, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; byte[] request = getRequestBytes(null, header); - Request obj = (Request)decode(request); + Request obj = (Request) decode(request); Assert.assertEquals(null, obj.getData()); Assert.assertEquals(true, obj.isTwoWay()); Assert.assertEquals(true, obj.isHeartbeat()); Assert.assertEquals("2.0.0", obj.getVersion()); System.out.println(obj); } - + @Test - public void test_Decode_Return_Request_Object() throws IOException{ + public void test_Decode_Return_Request_Object() throws IOException { //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte) 0xdf, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xdf, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - - Request obj = (Request)decode(request); + + Request obj = (Request) decode(request); Assert.assertEquals(person, obj.getData()); Assert.assertEquals(true, obj.isTwoWay()); Assert.assertEquals(false, obj.isHeartbeat()); Assert.assertEquals("2.0.0", obj.getVersion()); System.out.println(obj); } - - @Test - public void test_Decode_Error_Request_Object() throws IOException{ - //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, (byte)0xdf, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + @Test + public void test_Decode_Error_Request_Object() throws IOException { + //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) 0xdf, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); //bad object - byte[] badbytes = new byte[]{-1,-2,-3,-4,-3,-4,-3,-4,-3,-4,-3,-4}; + byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); - - Request obj = (Request)decode(request); + + Request obj = (Request) decode(request); Assert.assertEquals(true, obj.isBroken()); Assert.assertEquals(true, obj.getData() instanceof Throwable); } - + @Test - public void test_Header_Response_NoSerializationFlag() throws IOException{ - //00000010-response/oneway/hearbeat=false/noset |20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + public void test_Header_Response_NoSerializationFlag() throws IOException { + //00000010-response/oneway/hearbeat=false/noset |20-stats=ok|id=0|length=0 + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - - Response obj = (Response)decode(request); + + Response obj = (Response) decode(request); Assert.assertEquals(20, obj.getStatus()); Assert.assertEquals(person, obj.getResult()); System.out.println(obj); } - + @Test - public void test_Header_Response_Heartbeat() throws IOException{ - //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[] { MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + public void test_Header_Response_Heartbeat() throws IOException { + //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - - Response obj = (Response)decode(request); + + Response obj = (Response) decode(request); Assert.assertEquals(20, obj.getStatus()); Assert.assertEquals(person, obj.getResult()); System.out.println(obj); } - - @Test - public void test_Encode_Request() throws IOException{ + + @Test + public void test_Encode_Request() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014); Channel channel = getCliendSideChannel(url); - Request request = new Request(); + Person person = new Person(); - request.setData(person); - + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).data(person); + final Request request = builder.build(); codec.encode(channel, encodeBuffer, request); //encode resault check need decode byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); - Request obj = (Request)codec.decode(channel, decodeBuffer); + Request obj = (Request) codec.decode(channel, decodeBuffer); Assert.assertEquals(request.isBroken(), obj.isBroken()); Assert.assertEquals(request.isHeartbeat(), obj.isHeartbeat()); Assert.assertEquals(request.isTwoWay(), obj.isTwoWay()); Assert.assertEquals(person, obj.getData()); } - - @Test - public void test_Encode_Response() throws IOException{ + + @Test + public void test_Encode_Response() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); - Response response = new Response(); - response.setHeartbeat(true); - response.setId(1001l); - response.setStatus((byte)20 ); - response.setVersion("11"); Person person = new Person(); - response.setResult(person); - + Response response = new Response.Builder(1001l). + isEvent(true). + status((byte) 20). + version("11"). + result(person).build(); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); //encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); - Response obj = (Response)codec.decode(channel, decodeBuffer); - + Response obj = (Response) codec.decode(channel, decodeBuffer); + Assert.assertEquals(response.getId(), obj.getId()); Assert.assertEquals(response.getStatus(), obj.getStatus()); Assert.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assert.assertEquals(person, obj.getResult()); // encode response verson ?? // Assert.assertEquals(response.getVersion(), obj.getVersion()); - + } - - @Test - public void test_Encode_Error_Response() throws IOException{ + + @Test + public void test_Encode_Error_Response() throws IOException { ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); - Response response = new Response(); - response.setHeartbeat(true); - response.setId(1001l); - response.setStatus((byte)10 ); - response.setVersion("11"); - String badString = "bad" ; - response.setErrorMessage(badString); Person person = new Person(); - response.setResult(person); - + Response response = new Response.Builder(1001l). + isEvent(true). + status((byte) 10). + version("11"). + result(person). + errorMsg("bad").build(); codec.encode(channel, encodeBuffer, response); byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); //encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); - Response obj = (Response)codec.decode(channel, decodeBuffer); + Response obj = (Response) codec.decode(channel, decodeBuffer); Assert.assertEquals(response.getId(), obj.getId()); Assert.assertEquals(response.getStatus(), obj.getStatus()); Assert.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); - Assert.assertEquals(badString, obj.getErrorMessage()); + Assert.assertEquals("bad", obj.getErrorMessage()); Assert.assertEquals(null, obj.getResult()); // Assert.assertEquals(response.getVersion(), obj.getVersion()); } @@ -385,10 +384,10 @@ public void test_Encode_Error_Response() throws IOException{ @Test public void testMessageLengthGreaterThanMessageActualLength() throws Exception { Channel channel = getCliendSideChannel(url); - Request request = new Request(1L); - request.setVersion("2.0.0"); Date date = new Date(); - request.setData(date); + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).data(date); + final Request request = builder.build(); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); codec.encode(channel, encodeBuffer, request); byte[] bytes = new byte[encodeBuffer.writerIndex()]; @@ -403,23 +402,24 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { int padding = 512; out.write(Bytes.int2bytes(len + padding)); out.write(bytes, 16, bytes.length - 16); - for(int i = 0; i < padding; i++) { + for (int i = 0; i < padding; i++) { out.write(1); } out.write(bytes); /* request|1111...|request */ ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray()); - Request decodedRequest = (Request)codec.decode(channel, decodeBuffer); + Request decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assert.assertTrue(date.equals(decodedRequest.getData())); Assert.assertEquals(bytes.length + padding, decodeBuffer.readerIndex()); - decodedRequest = (Request)codec.decode(channel, decodeBuffer); + decodedRequest = (Request) codec.decode(channel, decodeBuffer); Assert.assertTrue(date.equals(decodedRequest.getData())); } @Test public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { - Request request = new Request(1L); - request.setData("hello"); + Request.Builder builder = new Request.Builder(); + builder.newId().version(Version.getVersion()).data("hello"); + final Request request = builder.build(); ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); try { @@ -429,8 +429,7 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6)); } - Response response = new Response(1L); - response.setResult("hello"); + Response response = new Response.Builder(1L).result("hello").build(); encodeBuffer = ChannelBuffers.dynamicBuffer(512); channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); codec.encode(channel, encodeBuffer, response); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java index 3155ecb50d9..83985305d0c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java @@ -15,121 +15,125 @@ */ package com.alibaba.dubbo.remoting.handler; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; +import junit.framework.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; -public class ConnectChannelHandlerTest extends WrappedChannelHandlerTest{ +public class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { @Before public void setUp() throws Exception { handler = new ConnectionOrderedChannelHandler(new BizChannelHander(true), url); } - + @Test - public void test_Connect_Blocked() throws RemotingException{ + public void test_Connect_Blocked() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHander(false), url); - ThreadPoolExecutor executor = (ThreadPoolExecutor)getField(handler, "connectionExecutor", 1); + ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); Assert.assertEquals(1, executor.getMaximumPoolSize()); - + int runs = 20; int taskCount = runs * 2; - for(int i=0; ikimi */ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec { private static final Logger logger = LoggerFactory.getLogger(DeprecatedExchangeCodec.class); - // header length. protected static final int HEADER_LENGTH = 16; - // magic header. protected static final short MAGIC = (short) 0xdabb; protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; - // message flag. protected static final byte FLAG_REQUEST = (byte) 0x80; @@ -73,7 +70,7 @@ public Object decode(Channel channel, InputStream is) throws IOException { protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { // check magic number. if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { + || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); @@ -93,20 +90,17 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he if (readable < HEADER_LENGTH) { return NEED_MORE_INPUT; } - // get data length. int len = Bytes.bytes2int(header, 12); checkPayload(channel, len); - int tt = len + HEADER_LENGTH; if (readable < tt) { return NEED_MORE_INPUT; } - // limit input stream. - if (readable != tt) + if (readable != tt) { is = StreamUtils.limitedInputStream(is, len); - + } try { return decodeBody(channel, is, header); } finally { @@ -131,56 +125,54 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. - Response res = new Response(id); - if ((flag & FLAG_EVENT) != 0) { - res.setEvent(Response.HEARTBEAT_EVENT); + Response.Builder builder = new Response.Builder(id); + boolean isEvent = (flag & FLAG_EVENT) != 0; + builder.isEvent(isEvent); + if (isEvent) { + builder.result(Response.HEARTBEAT_EVENT); } // get status. byte status = header[3]; - res.setStatus(status); + builder.status(status); + Response res = builder.build(); if (status == Response.OK) { try { Object data; - if (res.isHeartbeat()) { - data = decodeHeartbeatData(channel, in); - } else if (res.isEvent()) { + if (isEvent) { data = decodeEventData(channel, in); } else { data = decodeResponseData(channel, in, getRequestData(id)); } - res.setResult(data); + res = res.newBuilder().result(data).build(); } catch (Throwable t) { - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + res = res.newBuilder().status(Response.CLIENT_ERROR).errorMsg(StringUtils.toString(t)).build(); } } else { - res.setErrorMessage(in.readUTF()); + res = res.newBuilder().errorMsg(in.readUTF()).build(); } return res; } else { // decode request. - Request req = new Request(id); - req.setVersion("2.0.0"); - req.setTwoWay((flag & FLAG_TWOWAY) != 0); - if ((flag & FLAG_EVENT) != 0) { - req.setEvent(Request.HEARTBEAT_EVENT); + Request.Builder builder = new Request.Builder(id); + builder.version(Version.getVersion()); + builder.twoWay((flag & FLAG_TWOWAY) != 0); + boolean isEvent = (flag & FLAG_EVENT) != 0; + if (isEvent) { + builder.isEvent(true).data(Request.HEARTBEAT_EVENT); } try { Object data; - if (req.isHeartbeat()) { - data = decodeHeartbeatData(channel, in); - } else if (req.isEvent()) { + if (isEvent) { data = decodeEventData(channel, in); } else { data = decodeRequestData(channel, in); } - req.setData(data); + builder.data(data); } catch (Throwable t) { // bad request - req.setBroken(true); - req.setData(t); + builder.broken(true).data(t); } - return req; + return builder.build(); } } @@ -251,7 +243,7 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th // encode response data or error message. if (status == Response.OK) { if (res.isHeartbeat()) { - encodeHeartbeatData(channel, out, res.getResult()); + encodeEventData(channel, out, res.getResult()); } else { encodeResponseData(channel, out, res.getResult()); } @@ -272,12 +264,11 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th try { // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理? logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); - - Response r = new Response(res.getId(), res.getVersion()); - r.setStatus(Response.BAD_RESPONSE); - r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); + Response r = res.newBuilder(). + status(Response.BAD_RESPONSE). + errorMsg("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)). + build(); channel.send(r); - return; } catch (RemotingException e) { logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); @@ -289,10 +280,8 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th throw (IOException) t; } else if (t instanceof RuntimeException) { throw (RuntimeException) t; - } else if (t instanceof Error) { - throw (Error) t; } else { - throw new RuntimeException(t.getMessage(), t); + throw (Error) t; } } } @@ -388,11 +377,6 @@ private void encodeEventData(Channel channel, ObjectOutput out, Object data) thr encodeEventData(out, data); } - @Deprecated - protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeHeartbeatData(out, data); - } - protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(out, data); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index e0d6cd75236..f24d21c094a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -15,60 +15,51 @@ */ package com.alibaba.dubbo.rpc; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; +import java.net.InetSocketAddress; +import java.util.*; +import java.util.concurrent.*; + /** * Thread local context. (API, ThreadLocal, ThreadSafe) - * + *

* 注意:RpcContext是一个临时状态记录器,当接收到RPC请求,或发起RPC请求时,RpcContext的状态都会变化。 * 比如:A调B,B再调C,则B机器上,在B调C之前,RpcContext记录的是A调B的信息,在B调C之后,RpcContext记录的是B调C的信息。 - * - * @see com.alibaba.dubbo.rpc.filter.ContextFilter + * * @author qian.lei * @author william.liangf * @export + * @see com.alibaba.dubbo.rpc.filter.ContextFilter */ public class RpcContext { - - private static final ThreadLocal LOCAL = new ThreadLocal() { - @Override - protected RpcContext initialValue() { - return new RpcContext(); - } - }; - - /** - * get context. - * - * @return context - */ - public static RpcContext getContext() { - return LOCAL.get(); - } - - /** - * remove context. - * - * @see com.alibaba.dubbo.rpc.filter.ContextFilter - */ - public static void removeContext() { - LOCAL.remove(); - } + + private static final ThreadLocal LOCAL = new ThreadLocal() { + @Override + protected RpcContext initialValue() { + return new RpcContext(); + } + }; + + /** + * get context. + * + * @return context + */ + public static RpcContext getContext() { + return LOCAL.get(); + } + + /** + * remove context. + * + * @see com.alibaba.dubbo.rpc.filter.ContextFilter + */ + public static void removeContext() { + LOCAL.remove(); + } private Future future; @@ -82,9 +73,9 @@ public static void removeContext() { private Object[] arguments; - private InetSocketAddress localAddress; + private InetSocketAddress localAddress; - private InetSocketAddress remoteAddress; + private InetSocketAddress remoteAddress; private final Map attachments = new HashMap(); @@ -95,17 +86,17 @@ public static void removeContext() { private Object request; private Object response; - @Deprecated + @Deprecated private List> invokers; - - @Deprecated + + @Deprecated private Invoker invoker; - @Deprecated + @Deprecated private Invocation invocation; - - protected RpcContext() { - } + + protected RpcContext() { + } /** * Get the request object of the underlying RPC protocol, e.g. HttpServletRequest @@ -156,7 +147,7 @@ public void setResponse(Object response) { /** * is provider side. - * + * * @return provider side. */ public boolean isProviderSide() { @@ -174,13 +165,13 @@ public boolean isProviderSide() { } else { host = address.getAddress().getHostAddress(); } - return url.getPort() != address.getPort() || - ! NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host)); + return url.getPort() != address.getPort() || + !NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host)); } /** * is consumer side. - * + * * @return consumer side. */ public boolean isConsumerSide() { @@ -198,13 +189,13 @@ public boolean isConsumerSide() { } else { host = address.getAddress().getHostAddress(); } - return url.getPort() == address.getPort() && + return url.getPort() == address.getPort() && NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host)); } /** * get future. - * + * * @param * @return future */ @@ -215,7 +206,7 @@ public Future getFuture() { /** * set future. - * + * * @param future */ public void setFuture(Future future) { @@ -223,7 +214,7 @@ public void setFuture(Future future) { } public List getUrls() { - return urls == null && url != null ? (List) Arrays.asList(url) : urls; + return urls == null && url != null ? (List) Collections.singletonList(url) : urls; } public void setUrls(List urls) { @@ -240,7 +231,7 @@ public void setUrl(URL url) { /** * get method name. - * + * * @return method name. */ public String getMethodName() { @@ -253,7 +244,7 @@ public void setMethodName(String methodName) { /** * get parameter types. - * + * * @serial */ public Class[] getParameterTypes() { @@ -266,7 +257,7 @@ public void setParameterTypes(Class[] parameterTypes) { /** * get arguments. - * + * * @return arguments. */ public Object[] getArguments() { @@ -279,22 +270,22 @@ public void setArguments(Object[] arguments) { /** * set local address. - * + * * @param address * @return context */ - public RpcContext setLocalAddress(InetSocketAddress address) { - this.localAddress = address; - return this; - } - - /** - * set local address. - * - * @param host - * @param port - * @return context - */ + public RpcContext setLocalAddress(InetSocketAddress address) { + this.localAddress = address; + return this; + } + + /** + * set local address. + * + * @param host + * @param port + * @return context + */ public RpcContext setLocalAddress(String host, int port) { if (port < 0) { port = 0; @@ -303,35 +294,35 @@ public RpcContext setLocalAddress(String host, int port) { return this; } - /** - * get local address. - * - * @return local address - */ - public InetSocketAddress getLocalAddress() { - return localAddress; - } + /** + * get local address. + * + * @return local address + */ + public InetSocketAddress getLocalAddress() { + return localAddress; + } - public String getLocalAddressString() { + public String getLocalAddressString() { return getLocalHost() + ":" + getLocalPort(); } - - /** - * get local host name. - * - * @return local host name - */ - public String getLocalHostName() { - String host = localAddress == null ? null : localAddress.getHostName(); - if (host == null || host.length() == 0) { - return getLocalHost(); - } - return host; - } + + /** + * get local host name. + * + * @return local host name + */ + public String getLocalHostName() { + String host = localAddress == null ? null : localAddress.getHostName(); + if (host == null || host.length() == 0) { + return getLocalHost(); + } + return host; + } /** * set remote address. - * + * * @param address * @return context */ @@ -339,10 +330,10 @@ public RpcContext setRemoteAddress(InetSocketAddress address) { this.remoteAddress = address; return this; } - + /** * set remote address. - * + * * @param host * @param port * @return context @@ -355,42 +346,42 @@ public RpcContext setRemoteAddress(String host, int port) { return this; } - /** - * get remote address. - * - * @return remote address - */ - public InetSocketAddress getRemoteAddress() { - return remoteAddress; - } - - /** - * get remote address string. - * - * @return remote address string. - */ - public String getRemoteAddressString() { - return getRemoteHost() + ":" + getRemotePort(); - } - - /** - * get remote host name. - * - * @return remote host name - */ - public String getRemoteHostName() { - return remoteAddress == null ? null : remoteAddress.getHostName(); - } + /** + * get remote address. + * + * @return remote address + */ + public InetSocketAddress getRemoteAddress() { + return remoteAddress; + } + + /** + * get remote address string. + * + * @return remote address string. + */ + public String getRemoteAddressString() { + return getRemoteHost() + ":" + getRemotePort(); + } + + /** + * get remote host name. + * + * @return remote host name + */ + public String getRemoteHostName() { + return remoteAddress == null ? null : remoteAddress.getHostName(); + } /** * get local host. - * + * * @return local host */ public String getLocalHost() { - String host = localAddress == null ? null : - localAddress.getAddress() == null ? localAddress.getHostName() - : NetUtils.filterLocalHost(localAddress.getAddress().getHostAddress()); + String host = localAddress == null ? null : + localAddress.getAddress() == null ? localAddress.getHostName() + : NetUtils.filterLocalHost(localAddress.getAddress().getHostAddress()); if (host == null || host.length() == 0) { return NetUtils.getLocalHost(); } @@ -399,7 +390,7 @@ public String getLocalHost() { /** * get local port. - * + * * @return port */ public int getLocalPort() { @@ -408,18 +399,18 @@ public int getLocalPort() { /** * get remote host. - * + * * @return remote host */ public String getRemoteHost() { - return remoteAddress == null ? null : - remoteAddress.getAddress() == null ? remoteAddress.getHostName() - : NetUtils.filterLocalHost(remoteAddress.getAddress().getHostAddress()); + return remoteAddress == null ? null : + remoteAddress.getAddress() == null ? remoteAddress.getHostName() + : NetUtils.filterLocalHost(remoteAddress.getAddress().getHostAddress()); } /** * get remote port. - * + * * @return remote port */ public int getRemotePort() { @@ -428,7 +419,7 @@ public int getRemotePort() { /** * get attachment. - * + * * @param key * @return attachment */ @@ -438,7 +429,7 @@ public String getAttachment(String key) { /** * set attachment. - * + * * @param key * @param value * @return context @@ -454,7 +445,7 @@ public RpcContext setAttachment(String key, String value) { /** * remove attachment. - * + * * @param key * @return context */ @@ -465,7 +456,7 @@ public RpcContext removeAttachment(String key) { /** * get attachments. - * + * * @return attachments */ public Map getAttachments() { @@ -474,7 +465,7 @@ public Map getAttachments() { /** * set attachments - * + * * @param attachment * @return context */ @@ -485,14 +476,14 @@ public RpcContext setAttachments(Map attachment) { } return this; } - + public void clearAttachments() { this.attachments.clear(); } /** * get values. - * + * * @return values */ public Map get() { @@ -501,7 +492,7 @@ public Map get() { /** * set value. - * + * * @param key * @param value * @return context @@ -517,7 +508,7 @@ public RpcContext set(String key, Object value) { /** * remove value. - * + * * @param key * @return value */ @@ -528,7 +519,7 @@ public RpcContext remove(String key) { /** * get value. - * + * * @param key * @return value */ @@ -573,7 +564,7 @@ public RpcContext setInvocation(Invocation invocation) { public boolean isServerSide() { return isProviderSide(); } - + /** * @deprecated Replace to isConsumerSide() */ @@ -581,14 +572,14 @@ public boolean isServerSide() { public boolean isClientSide() { return isConsumerSide(); } - + /** * @deprecated Replace to getUrls() */ @Deprecated - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public List> getInvokers() { - return invokers == null && invoker != null ? (List)Arrays.asList(invoker) : invokers; + return invokers == null && invoker != null ? (List) Collections.singletonList(invoker) : invokers; } /** @@ -606,72 +597,76 @@ public Invoker getInvoker() { public Invocation getInvocation() { return invocation; } - + /** * 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题. + * * @param callable * @return 通过future.get()获取返回结果. */ @SuppressWarnings("unchecked") - public Future asyncCall(Callable callable) { - try { - try { - setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); - final T o = callable.call(); - //local调用会直接返回结果. - if (o != null) { - FutureTask f = new FutureTask(new Callable() { - public T call() throws Exception { - return o; - } - }); - f.run(); - return f; - } else { - - } - } catch (Exception e) { - throw new RpcException(e); - } finally { - removeAttachment(Constants.ASYNC_KEY); - } - } catch (final RpcException e) { - return new Future() { - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - public boolean isCancelled() { - return false; - } - public boolean isDone() { - return true; - } - public T get() throws InterruptedException, ExecutionException { - throw new ExecutionException(e.getCause()); - } - public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, - TimeoutException { - return get(); - } - }; - } - return ((Future)getContext().getFuture()); - } - - /** - * oneway调用,只发送请求,不接收返回结果. - * @param callable - */ - public void asyncCall(Runnable runable) { - try { - setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString()); - runable.run(); - } catch (Throwable e) { - //FIXME 异常是否应该放在future中? - throw new RpcException("oneway call error ." + e.getMessage(), e); - } finally { - removeAttachment(Constants.RETURN_KEY); - } + public Future asyncCall(Callable callable) { + try { + try { + setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); + final T o = callable.call(); + //local调用会直接返回结果. + if (o != null) { + FutureTask f = new FutureTask(new Callable() { + public T call() throws Exception { + return o; + } + }); + f.run(); + return f; + } + } catch (Exception e) { + throw new RpcException(e); + } finally { + removeAttachment(Constants.ASYNC_KEY); + } + } catch (final RpcException e) { + return new Future() { + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + public boolean isCancelled() { + return false; + } + + public boolean isDone() { + return true; + } + + public T get() throws InterruptedException, ExecutionException { + throw new ExecutionException(e.getCause()); + } + + public T get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, + TimeoutException { + return get(); + } + }; + } + return ((Future) getContext().getFuture()); + } + + /** + * oneway调用,只发送请求,不接收返回结果. + * + * @param runnable + */ + public void asyncCall(Runnable runnable) { + try { + setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString()); + runnable.run(); + } catch (Throwable e) { + //FIXME 异常是否应该放在future中? + throw new RpcException("oneway call error ." + e.getMessage(), e); + } finally { + removeAttachment(Constants.RETURN_KEY); + } } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilter.java index 710786528da..1f62d5a65f1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilter.java @@ -18,17 +18,11 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.*; /** * ConsumerContextInvokerFilter - * + * * @author william.liangf */ @Activate(group = Constants.CONSUMER, order = -10000) @@ -39,10 +33,10 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept .setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(NetUtils.getLocalHost(), 0) - .setRemoteAddress(invoker.getUrl().getHost(), - invoker.getUrl().getPort()); + .setRemoteAddress(invoker.getUrl().getHost(), + invoker.getUrl().getPort()); if (invocation instanceof RpcInvocation) { - ((RpcInvocation)invocation).setInvoker(invoker); + ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java index 1b75315f878..fd864534934 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/AbstractInvoker.java @@ -133,7 +133,6 @@ public Result invoke(Invocation inv) throws RpcException { } RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); - try { return doInvoke(invocation); } catch (InvocationTargetException e) { // biz exception diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 21c7316775c..fb1aca464aa 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -74,8 +74,7 @@ public void decode() throws Exception { if (log.isWarnEnabled()) { log.warn("Decode rpc invocation failed: " + e.getMessage(), e); } - request.setBroken(true); - request.setData(e); + request = request.newBuilder().broken(true).data(e).build(); } finally { hasDecoded = true; } @@ -140,7 +139,6 @@ public Object decode(Channel channel, InputStream input) throws IOException { } } setParameterTypes(pts); - Map map = (Map) in.readObject(Map.class); if (map != null && map.size() > 0) { Map attachment = getAttachments(); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index 514f8151e58..c6aa975bc2f 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -119,8 +119,7 @@ public void decode() throws Exception { if (log.isWarnEnabled()) { log.warn("Decode rpc result failed: " + e.getMessage(), e); } - response.setStatus(Response.CLIENT_ERROR); - response.setErrorMessage(StringUtils.toString(e)); + response = response.newBuilder().status(Response.CLIENT_ERROR).errorMsg(StringUtils.toString(e)).build(); } finally { hasDecoded = true; } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index 3e5fd8944f1..066736b334e 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.io.IOException; -import java.io.InputStream; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -41,6 +38,9 @@ import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcInvocation; +import java.io.IOException; +import java.io.InputStream; + import static com.alibaba.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument; /** @@ -74,19 +74,20 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. - Response res = new Response(id); - if ((flag & FLAG_EVENT) != 0) { - res.setEvent(Response.HEARTBEAT_EVENT); + Response.Builder builder = new Response.Builder(id); + boolean isEvent = (flag & FLAG_EVENT) != 0; + builder.isEvent(isEvent); + if (isEvent) { + builder.result(Response.HEARTBEAT_EVENT); } // get status. byte status = header[3]; - res.setStatus(status); + builder.status(status); + Response res = builder.build(); if (status == Response.OK) { try { Object data; - if (res.isHeartbeat()) { - data = decodeHeartbeatData(channel, deserialize(s, channel.getUrl(), is)); - } else if (res.isEvent()) { + if (isEvent) { data = decodeEventData(channel, deserialize(s, channel.getUrl(), is)); } else { DecodeableRpcResult result; @@ -94,7 +95,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro Constants.DECODE_IN_IO_THREAD_KEY, Constants.DEFAULT_DECODE_IN_IO_THREAD)) { result = new DecodeableRpcResult(channel, res, is, - (Invocation)getRequestData(id), proto); + (Invocation) getRequestData(id), proto); result.decode(); } else { result = new DecodeableRpcResult(channel, res, @@ -103,37 +104,37 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } data = result; } - res.setResult(data); + res = res.newBuilder().result(data).build(); } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn("Decode response failed: " + t.getMessage(), t); } - res.setStatus(Response.CLIENT_ERROR); - res.setErrorMessage(StringUtils.toString(t)); + res = res.newBuilder().status(Response.CLIENT_ERROR).errorMsg(StringUtils.toString(t)).build(); } } else { - res.setErrorMessage(deserialize(s, channel.getUrl(), is).readUTF()); + res = res.newBuilder().errorMsg(deserialize(s, channel.getUrl(), is).readUTF()).build(); } return res; } else { // decode request. - Request req = new Request(id); - req.setVersion("2.0.0"); - req.setTwoWay((flag & FLAG_TWOWAY) != 0); - if ((flag & FLAG_EVENT) != 0) { - req.setEvent(Request.HEARTBEAT_EVENT); + Request.Builder builder = new Request.Builder(id); + builder.version(Version.getVersion()).twoWay((flag & FLAG_TWOWAY) != 0); + boolean isEvent = (flag & FLAG_EVENT) != 0; + builder.isEvent(isEvent); + if (isEvent) { + builder.data(Request.HEARTBEAT_EVENT); } + Request req = builder.build(); try { Object data; - if (req.isHeartbeat()) { - data = decodeHeartbeatData(channel, deserialize(s, channel.getUrl(), is)); - } else if (req.isEvent()) { + if (isEvent) { data = decodeEventData(channel, deserialize(s, channel.getUrl(), is)); } else { DecodeableRpcInvocation inv; if (channel.getUrl().getParameter( Constants.DECODE_IN_IO_THREAD_KEY, Constants.DEFAULT_DECODE_IN_IO_THREAD)) { + inv = new DecodeableRpcInvocation(channel, req, is, proto); inv.decode(); } else { @@ -142,14 +143,12 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } data = inv; } - req.setData(data); + req = req.newBuilder().data(data).build(); } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn("Decode request failed: " + t.getMessage(), t); } - // bad request - req.setBroken(true); - req.setData(t); + req = req.newBuilder().broken(true).data(t).build(); } return req; } @@ -190,7 +189,7 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) Object[] args = inv.getArguments(); if (args != null) - for (int i = 0; i < args.length; i++){ + for (int i = 0; i < args.length; i++) { out.writeObject(encodeInvocationArgument(channel, inv, i)); } out.writeObject(inv.getAttachments()); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index f9fc7821224..558cdf49e66 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -87,7 +87,8 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { return new RpcResult(); } else { RpcContext.getContext().setFuture(null); - return (Result) currentClient.request(inv, timeout).get(); + Result result = (Result) currentClient.request(inv, timeout).get(); + return result; } } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); @@ -111,30 +112,29 @@ public boolean isAvailable() { public void destroy() { //防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭 - if (super.isDestroyed()) { + if (isDestroyed()) { return; - } else { - //dubbo check ,避免多次关闭 - destroyLock.lock(); - try { - if (super.isDestroyed()) { - return; - } - super.destroy(); - if (invokers != null) { - invokers.remove(this); - } - for (ExchangeClient client : clients) { - try { - client.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } + } + //dubbo check ,避免多次关闭 + destroyLock.lock(); + try { + if (super.isDestroyed()) { + return; + } + super.destroy(); + if (invokers != null) { + invokers.remove(this); + } + for (ExchangeClient client : clients) { + try { + client.close(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); } - - } finally { - destroyLock.unlock(); } + + } finally { + destroyLock.unlock(); } } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 642c9a4bee0..496c17eed24 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -217,8 +217,4 @@ private void checkClient() { } } - @Override - public void addInterceptor(Interceptor interceptor) { - client.addInterceptor(interceptor); - } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index d1b744c22b3..d81695390d7 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -15,10 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.net.InetSocketAddress; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.Parameters; import com.alibaba.dubbo.common.URL; @@ -26,33 +22,36 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Interceptor; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import java.net.InetSocketAddress; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + /** * dubbo protocol support class. - * + * * @author chao.liuc */ @SuppressWarnings("deprecation") final class ReferenceCountExchangeClient implements ExchangeClient { private ExchangeClient client; - + private final URL url; - + // private final ExchangeHandler handler; - + private final AtomicInteger refenceCount = new AtomicInteger(0); - + private final ConcurrentMap ghostClientMap; - - + + public ReferenceCountExchangeClient(ExchangeClient client, ConcurrentMap ghostClientMap) { this.client = client; refenceCount.incrementAndGet(); this.url = client.getUrl(); - if (ghostClientMap == null){ + if (ghostClientMap == null) { throw new IllegalStateException("ghostClientMap can not be null, url: " + url); } this.ghostClientMap = ghostClientMap; @@ -125,7 +124,8 @@ public void setAttribute(String key, Object value) { public void removeAttribute(String key) { client.removeAttribute(key); } - /* + + /* * close方法将不再幂等,调用需要注意. */ public void close() { @@ -133,8 +133,8 @@ public void close() { } public void close(int timeout) { - if (refenceCount.decrementAndGet() <= 0){ - if (timeout == 0){ + if (refenceCount.decrementAndGet() <= 0) { + if (timeout == 0) { client.close(); } else { client.close(timeout); @@ -142,9 +142,9 @@ public void close(int timeout) { client = replaceWithLazyClient(); } } - + //幽灵client, - private LazyConnectExchangeClient replaceWithLazyClient(){ + private LazyConnectExchangeClient replaceWithLazyClient() { //这个操作只为了防止程序bug错误关闭client做的防御措施,初始client必须为false状态 URL lazyUrl = url.addParameter(Constants.LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.FALSE) .addParameter(Constants.RECONNECT_KEY, Boolean.FALSE) @@ -152,11 +152,11 @@ private LazyConnectExchangeClient replaceWithLazyClient(){ .addParameter("warning", Boolean.TRUE.toString()) .addParameter(LazyConnectExchangeClient.REQUEST_WITH_WARNING_KEY, true) .addParameter("_client_memo", "referencecounthandler.replacewithlazyclient"); - + String key = url.getAddress(); //最差情况下只有一个幽灵连接 LazyConnectExchangeClient gclient = ghostClientMap.get(key); - if (gclient == null || gclient.isClosed()){ + if (gclient == null || gclient.isClosed()) { gclient = new LazyConnectExchangeClient(lazyUrl, client.getExchangeHandler()); ghostClientMap.put(key, gclient); } @@ -166,13 +166,8 @@ private LazyConnectExchangeClient replaceWithLazyClient(){ public boolean isClosed() { return client.isClosed(); } - - public void incrementAndGetCount(){ - refenceCount.incrementAndGet(); - } - @Override - public void addInterceptor(Interceptor interceptor) { - client.addInterceptor(interceptor); + public void incrementAndGetCount() { + refenceCount.incrementAndGet(); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java index 2c482e185cd..f6acd0d0a7b 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -106,7 +106,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { if ("httpclient".equalsIgnoreCase(client)) { hessianProxyFactory.setConnectionFactory(new HttpClientConnectionFactory()); } else if ("okHttpClient".equalsIgnoreCase(client)) { - hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory()); + hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory(url)); } else if (client != null && client.length() > 0 && !Constants.DEFAULT_HTTP_CLIENT.equals(client)) { throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java index 6b2c612a008..9bb315aa6d6 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HttpClientConnection.java @@ -35,7 +35,6 @@ public class HttpClientConnection extends AbstractHessianConnection { private final HttpClient httpClient; - private final HttpPost request; private volatile HttpResponse response; diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index 3aa491fe4c9..f40ee063327 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -21,8 +21,10 @@ public class OkHttpConnectionFactory implements HessianConnectionFactory { private final OkHttpClient client; - public OkHttpConnectionFactory() { + public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); client = builder.build(); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java index 12509b2798b..5f7d902f489 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -51,7 +51,7 @@ /** * Thrift framed protocol codec. - * + *

*

  * |<-                                  message header                                  ->|<- message body ->|
  * +----------------+----------------------+------------------+---------------------------+------------------+
@@ -59,12 +59,12 @@
  * +----------------+----------------------+------------------+---------------------------+------------------+
  * |<-                                               message size                                          ->|
  * 
- * + *

*

* header fields in version 1 *

    - *
  1. string - service name
  2. - *
  3. long - dubbo request id
  4. + *
  5. string - service name
  6. + *
  7. long - dubbo request id
  8. *
*

* @@ -263,10 +263,9 @@ private Object decode(TProtocol protocol) result.setArguments(parameters.toArray()); result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); - - Request request = new Request(id); - request.setData(result); - + Request.Builder builder = new Request.Builder(id); + builder.data(result); + Request request = builder.build(); cachedRequest.putIfAbsent(id, RequestData.create(message.seqid, serviceName, message.name)); @@ -282,24 +281,14 @@ private Object decode(TProtocol protocol) } catch (TException e) { throw new IOException(e.getMessage(), e); } - RpcResult result = new RpcResult(); - result.setException(new RpcException(exception.getMessage())); - - Response response = new Response(); - - response.setResult(result); - - response.setId(id); - - return response; - + Response.Builder builder = new Response.Builder(id); + builder.result(result); + return builder.build(); } else if (message.type == TMessageType.REPLY) { - String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name); - if (StringUtils.isEmpty(resultClassName)) { throw new IllegalArgumentException( new StringBuilder(32) @@ -308,21 +297,14 @@ private Object decode(TProtocol protocol) .append(", the service name you specified may not generated by thrift idl compiler") .toString()); } - Class clazz = cachedClass.get(resultClassName); - if (clazz == null) { - try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent(resultClassName, clazz); - } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - } TBase result; @@ -333,7 +315,6 @@ private Object decode(TProtocol protocol) } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - try { result.read(protocol); protocol.readMessageEnd(); @@ -342,54 +323,37 @@ private Object decode(TProtocol protocol) } Object realResult = null; - int index = 0; - while (true) { - TFieldIdEnum fieldIdEnum = result.fieldForId(index++); - if (fieldIdEnum == null) { break; } - Field field; - try { field = clazz.getDeclaredField(fieldIdEnum.getFieldName()); field.setAccessible(true); } catch (NoSuchFieldException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - try { realResult = field.get(result); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } - if (realResult != null) { break; } - } - - Response response = new Response(); - - response.setId(id); - + Response.Builder builder = new Response.Builder(id); RpcResult rpcResult = new RpcResult(); - if (realResult instanceof Throwable) { rpcResult.setException((Throwable) realResult); } else { rpcResult.setValue(realResult); } - - response.setResult(rpcResult); - - return response; - + builder.result(rpcResult); + return builder.build(); } else { // Impossible throw new IOException(); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index 4b0ecdaa0d1..f1e2c792955 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -1,10 +1,10 @@ /** * File Created at 2011-12-05 * $Id$ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -13,18 +13,6 @@ */ package com.alibaba.dubbo.rpc.protocol.thrift; -import java.io.ByteArrayInputStream; - -import org.apache.thrift.TApplicationException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; -import org.apache.thrift.transport.TTransport; -import org.junit.Assert; -import org.junit.Test; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; @@ -38,6 +26,17 @@ import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.gen.thrift.Demo; import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; +import org.apache.thrift.TApplicationException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TIOStreamTransport; +import org.apache.thrift.transport.TTransport; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; /** * @author gang.lvg @@ -54,319 +53,315 @@ public void testEncodeRequest() throws Exception { ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024); - codec.encode( channel, output, request ); + codec.encode(channel, output, request); byte[] bytes = new byte[output.readableBytes()]; output.readBytes(bytes); - ByteArrayInputStream bis = new ByteArrayInputStream( bytes ); + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - TTransport transport = new TIOStreamTransport( bis ); + TTransport transport = new TIOStreamTransport(bis); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); // frame byte[] length = new byte[4]; - transport.read( length, 0, 4 ); + transport.read(length, 0, 4); - if ( bis.markSupported() ) { - bis.mark( 0 ); + if (bis.markSupported()) { + bis.mark(0); } // magic - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); + Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); // message length int messageLength = protocol.readI32(); - Assert.assertEquals( messageLength + 4, bytes.length ); + Assert.assertEquals(messageLength + 4, bytes.length); // header length short headerLength = protocol.readI16(); // version - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); + Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); // service name - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); + Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); // dubbo request id - Assert.assertEquals( request.getId(), protocol.readI64() ); + Assert.assertEquals(request.getId(), protocol.readI64()); // test message header length - if ( bis.markSupported() ) { + if (bis.markSupported()) { bis.reset(); - bis.skip( headerLength ); + bis.skip(headerLength); } TMessage message = protocol.readMessageBegin(); Demo.echoString_args args = new Demo.echoString_args(); - args.read( protocol ); + args.read(protocol); protocol.readMessageEnd(); - Assert.assertEquals( "echoString", message.name ); + Assert.assertEquals("echoString", message.name); - Assert.assertEquals( TMessageType.CALL, message.type ); + Assert.assertEquals(TMessageType.CALL, message.type); - Assert.assertEquals( "Hello, World!", args.getArg() ); + Assert.assertEquals("Hello, World!", args.getArg()); } @Test public void testDecodeReplyResponse() throws Exception { - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); + URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - Channel channel = new MockedChannel( url ); + Channel channel = new MockedChannel(url); - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 ); + RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); Request request = createRequest(); - DefaultFuture future = new DefaultFuture( channel, request, 10 ); + DefaultFuture future = new DefaultFuture(channel, request, 10); - TMessage message = new TMessage( "echoString", TMessageType.REPLY, ThriftCodec.getSeqId() ); + TMessage message = new TMessage("echoString", TMessageType.REPLY, ThriftCodec.getSeqId()); Demo.echoString_result methodResult = new Demo.echoString_result(); methodResult.success = "Hello, World!"; - TTransport transport = new TIOStreamTransport( bos ); + TTransport transport = new TIOStreamTransport(bos); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); int messageLength, headerLength; // prepare - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); - protocol.writeString( Demo.Iface.class.getName() ); - protocol.writeI64( request.getId() ); + protocol.writeI16(ThriftCodec.MAGIC); + protocol.writeI32(Integer.MAX_VALUE); + protocol.writeI16(Short.MAX_VALUE); + protocol.writeByte(ThriftCodec.VERSION); + protocol.writeString(Demo.Iface.class.getName()); + protocol.writeI64(request.getId()); protocol.getTransport().flush(); headerLength = bos.size(); - protocol.writeMessageBegin( message ); - methodResult.write( protocol ); + protocol.writeMessageBegin(message); + methodResult.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); try { - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); + bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); + protocol.writeI32(messageLength); + bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); + protocol.writeI16((short) (0xffff & headerLength)); } finally { - bos.setWriteIndex( oldIndex ); + bos.setWriteIndex(oldIndex); } // prepare - byte[] buf = new byte[ 4 + bos.size()]; - System.arraycopy( bos.toByteArray(), 0, buf, 4, bos.size() ); + byte[] buf = new byte[4 + bos.size()]; + System.arraycopy(bos.toByteArray(), 0, buf, 4, bos.size()); ChannelBuffer bis = ChannelBuffers.wrappedBuffer(buf); - Object obj = codec.decode( ( Channel ) null, bis ); + Object obj = codec.decode((Channel) null, bis); - Assert.assertNotNull( obj ); + Assert.assertNotNull(obj); - Assert.assertEquals( true, obj instanceof Response ); + Assert.assertEquals(true, obj instanceof Response); - Response response = ( Response ) obj; + Response response = (Response) obj; - Assert.assertEquals( request.getId(), response.getId() ); + Assert.assertEquals(request.getId(), response.getId()); - Assert.assertTrue( response.getResult() instanceof RpcResult ); + Assert.assertTrue(response.getResult() instanceof RpcResult); - RpcResult result = ( RpcResult ) response.getResult(); + RpcResult result = (RpcResult) response.getResult(); - Assert.assertTrue( result.getResult() instanceof String ); + Assert.assertTrue(result.getResult() instanceof String); - Assert.assertEquals( methodResult.success, result.getResult() ); + Assert.assertEquals(methodResult.success, result.getResult()); } @Test public void testDecodeExceptionResponse() throws Exception { - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() ); + URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName()); - Channel channel = new MockedChannel( url ); + Channel channel = new MockedChannel(url); - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 ); + RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); Request request = createRequest(); - DefaultFuture future = new DefaultFuture( channel, request, 10 ); + DefaultFuture future = new DefaultFuture(channel, request, 10); - TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() ); + TMessage message = new TMessage("echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId()); - TTransport transport = new TIOStreamTransport( bos ); + TTransport transport = new TIOStreamTransport(bos); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); TApplicationException exception = new TApplicationException(); int messageLength, headerLength; // prepare - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); - protocol.writeString( Demo.class.getName() ); - protocol.writeI64( request.getId() ); + protocol.writeI16(ThriftCodec.MAGIC); + protocol.writeI32(Integer.MAX_VALUE); + protocol.writeI16(Short.MAX_VALUE); + protocol.writeByte(ThriftCodec.VERSION); + protocol.writeString(Demo.class.getName()); + protocol.writeI64(request.getId()); protocol.getTransport().flush(); headerLength = bos.size(); - protocol.writeMessageBegin( message ); - exception.write( protocol ); + protocol.writeMessageBegin(message); + exception.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); try { - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); + bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); + protocol.writeI32(messageLength); + bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); + protocol.writeI16((short) (0xffff & headerLength)); } finally { - bos.setWriteIndex( oldIndex ); + bos.setWriteIndex(oldIndex); } // prepare ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray())); - Object obj = codec.decode( ( Channel ) null, bis ); + Object obj = codec.decode((Channel) null, bis); - Assert.assertNotNull( obj ); + Assert.assertNotNull(obj); - Assert.assertTrue( obj instanceof Response ); + Assert.assertTrue(obj instanceof Response); - Response response = ( Response ) obj; + Response response = (Response) obj; - Assert.assertTrue( response.getResult() instanceof RpcResult ); + Assert.assertTrue(response.getResult() instanceof RpcResult); - RpcResult result = ( RpcResult ) response.getResult(); + RpcResult result = (RpcResult) response.getResult(); - Assert.assertTrue( result.hasException() ); + Assert.assertTrue(result.hasException()); - Assert.assertTrue( result.getException() instanceof RpcException ); + Assert.assertTrue(result.getException() instanceof RpcException); } @Test public void testEncodeReplyResponse() throws Exception { - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); + URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - Channel channel = new MockedChannel( url ); + Channel channel = new MockedChannel(url); Request request = createRequest(); RpcResult rpcResult = new RpcResult(); - rpcResult.setResult( "Hello, World!" ); + rpcResult.setResult("Hello, World!"); - Response response = new Response(); - response.setResult( rpcResult ); - response.setId( request.getId() ); + Response response = new Response.Builder(request.getId()).result(rpcResult).build(); ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" ); - ThriftCodec.cachedRequest.putIfAbsent( request.getId(), rd ); - codec.encode( channel, bos, response ); + ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); + ThriftCodec.cachedRequest.putIfAbsent(request.getId(), rd); + codec.encode(channel, bos, response); byte[] buf = new byte[bos.writerIndex() - 4]; - System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); + System.arraycopy(bos.array(), 4, buf, 0, bos.writerIndex() - 4); - ByteArrayInputStream bis = new ByteArrayInputStream( buf ); + ByteArrayInputStream bis = new ByteArrayInputStream(buf); - if ( bis.markSupported() ) { - bis.mark( 0 ); + if (bis.markSupported()) { + bis.mark(0); } - TIOStreamTransport transport = new TIOStreamTransport( bis ); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TIOStreamTransport transport = new TIOStreamTransport(bis); + TBinaryProtocol protocol = new TBinaryProtocol(transport); - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); + Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); + Assert.assertEquals(protocol.readI32() + 4, bos.writerIndex()); int headerLength = protocol.readI16(); - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); - Assert.assertEquals( request.getId(), protocol.readI64() ); + Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); + Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); + Assert.assertEquals(request.getId(), protocol.readI64()); - if ( bis.markSupported() ) { + if (bis.markSupported()) { bis.reset(); - bis.skip( headerLength ); + bis.skip(headerLength); } TMessage message = protocol.readMessageBegin(); - Assert.assertEquals( "echoString", message.name ); - Assert.assertEquals( TMessageType.REPLY, message.type ); - Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid ); + Assert.assertEquals("echoString", message.name); + Assert.assertEquals(TMessageType.REPLY, message.type); + Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid); Demo.echoString_result result = new Demo.echoString_result(); - result.read( protocol ); + result.read(protocol); protocol.readMessageEnd(); - Assert.assertEquals( rpcResult.getValue(), result.getSuccess() ); + Assert.assertEquals(rpcResult.getValue(), result.getSuccess()); } @Test public void testEncodeExceptionResponse() throws Exception { - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); + URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - Channel channel = new MockedChannel( url ); + Channel channel = new MockedChannel(url); Request request = createRequest(); RpcResult rpcResult = new RpcResult(); String exceptionMessage = "failed"; - rpcResult.setException( new RuntimeException( exceptionMessage ) ); + rpcResult.setException(new RuntimeException(exceptionMessage)); - Response response = new Response(); - response.setResult( rpcResult ); - response.setId( request.getId() ); + Response response = new Response.Builder(request.getId()).result(rpcResult).build(); ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" ); - ThriftCodec.cachedRequest.put( request.getId(), rd ); - codec.encode( channel, bos, response ); + ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); + ThriftCodec.cachedRequest.put(request.getId(), rd); + codec.encode(channel, bos, response); byte[] buf = new byte[bos.writerIndex() - 4]; - System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); - ByteArrayInputStream bis = new ByteArrayInputStream( buf); + System.arraycopy(bos.array(), 4, buf, 0, bos.writerIndex() - 4); + ByteArrayInputStream bis = new ByteArrayInputStream(buf); - if ( bis.markSupported() ) { - bis.mark( 0 ); + if (bis.markSupported()) { + bis.mark(0); } - TIOStreamTransport transport = new TIOStreamTransport( bis ); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TIOStreamTransport transport = new TIOStreamTransport(bis); + TBinaryProtocol protocol = new TBinaryProtocol(transport); - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); + Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); + Assert.assertEquals(protocol.readI32() + 4, bos.writerIndex()); int headerLength = protocol.readI16(); - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); - Assert.assertEquals( request.getId(), protocol.readI64() ); + Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); + Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); + Assert.assertEquals(request.getId(), protocol.readI64()); - if ( bis.markSupported() ) { + if (bis.markSupported()) { bis.reset(); - bis.skip( headerLength ); + bis.skip(headerLength); } TMessage message = protocol.readMessageBegin(); - Assert.assertEquals( "echoString", message.name ); - Assert.assertEquals( TMessageType.EXCEPTION, message.type ); - Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid ); - TApplicationException exception = TApplicationException.read( protocol ); + Assert.assertEquals("echoString", message.name); + Assert.assertEquals(TMessageType.EXCEPTION, message.type); + Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid); + TApplicationException exception = TApplicationException.read(protocol); protocol.readMessageEnd(); - Assert.assertEquals( exceptionMessage, exception.getMessage() ); + Assert.assertEquals(exceptionMessage, exception.getMessage()); } @@ -374,59 +369,59 @@ public void testEncodeExceptionResponse() throws Exception { public void testDecodeRequest() throws Exception { Request request = createRequest(); // encode - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); + RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - TIOStreamTransport transport = new TIOStreamTransport( bos ); + TIOStreamTransport transport = new TIOStreamTransport(bos); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); + TBinaryProtocol protocol = new TBinaryProtocol(transport); int messageLength, headerLength; - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); + protocol.writeI16(ThriftCodec.MAGIC); + protocol.writeI32(Integer.MAX_VALUE); + protocol.writeI16(Short.MAX_VALUE); + protocol.writeByte(ThriftCodec.VERSION); protocol.writeString( - ( ( RpcInvocation ) request.getData() ) - .getAttachment( Constants.INTERFACE_KEY) ); - protocol.writeI64( request.getId() ); + ((RpcInvocation) request.getData()) + .getAttachment(Constants.INTERFACE_KEY)); + protocol.writeI64(request.getId()); protocol.getTransport().flush(); headerLength = bos.size(); - Demo.echoString_args args = new Demo.echoString_args( ); - args.setArg( "Hell, World!" ); + Demo.echoString_args args = new Demo.echoString_args(); + args.setArg("Hell, World!"); - TMessage message = new TMessage( "echoString", TMessageType.CALL, ThriftCodec.getSeqId() ); + TMessage message = new TMessage("echoString", TMessageType.CALL, ThriftCodec.getSeqId()); - protocol.writeMessageBegin( message ); - args.write( protocol ); + protocol.writeMessageBegin(message); + args.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); - try{ - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); + try { + bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); + protocol.writeI16((short) (0xffff & headerLength)); + bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); + protocol.writeI32(messageLength); } finally { - bos.setWriteIndex( oldIndex ); + bos.setWriteIndex(oldIndex); } - Object obj = codec.decode( ( Channel ) null, ChannelBuffers.wrappedBuffer( - encodeFrame(bos.toByteArray())) ); + Object obj = codec.decode((Channel) null, ChannelBuffers.wrappedBuffer( + encodeFrame(bos.toByteArray()))); - Assert.assertTrue( obj instanceof Request ); + Assert.assertTrue(obj instanceof Request); - obj = ( ( Request ) obj ).getData(); + obj = ((Request) obj).getData(); - Assert.assertTrue( obj instanceof RpcInvocation ); + Assert.assertTrue(obj instanceof RpcInvocation); - RpcInvocation invocation = ( RpcInvocation ) obj; + RpcInvocation invocation = (RpcInvocation) obj; - Assert.assertEquals( "echoString", invocation.getMethodName() ); - Assert.assertArrayEquals( new Class[] {String .class}, invocation.getParameterTypes() ); - Assert.assertArrayEquals( new Object[] { args.getArg() }, invocation.getArguments() ); + Assert.assertEquals("echoString", invocation.getMethodName()); + Assert.assertArrayEquals(new Class[]{String.class}, invocation.getParameterTypes()); + Assert.assertArrayEquals(new Object[]{args.getArg()}, invocation.getArguments()); } @@ -434,26 +429,24 @@ private Request createRequest() { RpcInvocation invocation = new RpcInvocation(); - invocation.setMethodName( "echoString" ); - - invocation.setArguments( new Object[]{ "Hello, World!" } ); - - invocation.setParameterTypes( new Class[]{ String.class } ); + invocation.setMethodName("echoString"); - invocation.setAttachment( Constants.INTERFACE_KEY, Demo.Iface.class.getName() ); + invocation.setArguments(new Object[]{"Hello, World!"}); - Request request = new Request( 1L ); + invocation.setParameterTypes(new Class[]{String.class}); - request.setData( invocation ); + invocation.setAttachment(Constants.INTERFACE_KEY, Demo.Iface.class.getName()); - return request; + Request.Builder builder = new Request.Builder(1L); + builder.data(invocation); + return builder.build(); } - static byte[] encodeFrame( byte[] content ) { - byte[] result = new byte[4+content.length]; - TFramedTransport.encodeFrameSize( content.length, result ); - System.arraycopy( content, 0, result, 4, content.length ); + static byte[] encodeFrame(byte[] content) { + byte[] result = new byte[4 + content.length]; + TFramedTransport.encodeFrameSize(content.length, result); + System.arraycopy(content, 0, result, 4, content.length); return result; } diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java index 016fc87b29b..4f59404ac40 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java @@ -16,8 +16,6 @@ package com.alibaba.dubbo.examples.heartbeat; -import java.util.concurrent.atomic.AtomicInteger; - import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; @@ -25,35 +23,40 @@ import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; +import java.util.concurrent.atomic.AtomicInteger; + /** * @author kimi */ public class HeartBeatExchangeHandler extends HeaderExchangeHandler { - private AtomicInteger heartBeatCounter = new AtomicInteger( 0 ); - - public HeartBeatExchangeHandler( ExchangeHandler handler ) { - super( handler ); + private AtomicInteger heartBeatCounter = new AtomicInteger(0); + + public HeartBeatExchangeHandler(ExchangeHandler handler) { + super(handler); } @Override - public void received( Channel channel, Object message ) throws RemotingException { - if ( message instanceof Request ) { - Request req = ( Request ) message; - if ( req.isHeartbeat() ) { + public void received(Channel channel, Object message) throws RemotingException { + if (message instanceof Request) { + Request req = (Request) message; + if (req.isHeartbeat()) { heartBeatCounter.incrementAndGet(); channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - Response res = new Response( req.getId(), req.getVersion() ); - res.setEvent( req.getData() == null ? null : req.getData().toString() ); - channel.send( res ); + Response res = new Response.Builder(req.getId()). + version(req.getVersion()). + isEvent(true). + result(req.getData() == null ? null : req.getData().toString()). + build(); + channel.send(res); } } else { - super.received( channel, message ); + super.received(channel, message); } } - + public int getHeartBeatCount() { return heartBeatCounter.get(); } - + } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java index c7001121673..36e3bbc46ca 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java @@ -11,7 +11,9 @@ public enum RpcAttachment { ParentSpanId("X-B3-ParentSpanId"), - Sampled("X-B3-Sampled"); + Sampled("X-B3-Sampled"), + + Method("X-B3-Method"); private final String name; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java new file mode 100644 index 00000000000..d61587cb663 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java @@ -0,0 +1,4 @@ +package com.alibaba.dubbo.tracker; + +public interface RpcTrackerEngine { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java index 7b9e34f4bbc..b7e51e8eccd 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java @@ -15,7 +15,7 @@ /** * @author Xs */ -@Activate(group = Constants.CONSUMER, order = Integer.MAX_VALUE) +//@Activate(group = Constants.CONSUMER, order = Integer.MAX_VALUE) public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java index bf82efd1cbc..7a04e78a8e5 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java @@ -15,7 +15,7 @@ /** * @author Xs */ -@Activate(group = Constants.PROVIDER, order = Integer.MIN_VALUE) +//@Activate(group = Constants.PROVIDER, order = Integer.MIN_VALUE) public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { @Override From 3ab7c85b4314f4003204aaf2d229adf53013ec7d Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 17 Jan 2017 23:44:06 +0800 Subject: [PATCH 11/69] HeaderExchangeChannelV2 --- .../dubbo/remoting/TimeoutException.java | 30 +-- .../exchange/support/DefaultFuture.java | 6 +- .../header/HeaderExchangeChannelV2.java | 17 +- .../support/header/HeaderExchangeHandler.java | 9 +- .../header/HeaderExchangeHandlerV2.java | 202 ++++++++++++++++++ 5 files changed, 230 insertions(+), 34 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java index f2ae4ed037d..d60d294b84b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java @@ -19,43 +19,23 @@ /** * TimeoutException. (API, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get() - * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get(int) + * * @author qian.lei * @export + * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get() + * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get(int) */ public class TimeoutException extends RemotingException { private static final long serialVersionUID = 3122966731958222692L; - - public static final int CLIENT_SIDE = 0; - - public static final int SERVER_SIDE = 1; - - private final int phase; - public TimeoutException(boolean serverSide, Channel channel, String message){ + public TimeoutException(Channel channel, String message) { super(channel, message); - this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; } - public TimeoutException(boolean serverSide, InetSocketAddress localAddress, + public TimeoutException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(localAddress, remoteAddress, message); - this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; - } - - public int getPhase() { - return phase; - } - - public boolean isServerSide() { - return phase == 1; - } - - public boolean isClientSide() { - return phase == 0; } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java index 6b29e269b98..0bd4378d8a4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java @@ -104,7 +104,7 @@ public Object get(int timeout) throws RemotingException { lock.unlock(); } if (!isDone()) { - throw new TimeoutException(sent > 0, channel, getTimeoutMessage(false)); + throw new TimeoutException(channel, getTimeoutMessage(false)); } } return returnFromResponse(); @@ -160,7 +160,7 @@ private void invokeCallback(ResponseCallback c) { } } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { try { - TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); + TimeoutException te = new TimeoutException(channel, res.getErrorMessage()); callbackCopy.caught(te); } catch (Exception e) { logger.error("callback invoke error ,url:" + channel.getUrl(), e); @@ -184,7 +184,7 @@ private Object returnFromResponse() throws RemotingException { return res.getResult(); } if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - throw new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()); + throw new TimeoutException(channel, res.getErrorMessage()); } throw new RemotingException(channel, res.getErrorMessage()); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java index 4652cc398e1..5eb0605beb2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java @@ -8,6 +8,7 @@ import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannelV2; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.Request; @@ -88,9 +89,9 @@ public Response request(Request request, int timeout) throws RemotingException { throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } - Long requestId = request.getId(); - PendingReply pendingReply = new PendingReply(requestId); + PendingReply pendingReply = new PendingReply(request.getId()); addPendingReply(pendingReply); + long startTimeMs = System.currentTimeMillis(); try { channel.send(request); } catch (RemotingException e) { @@ -106,9 +107,20 @@ public Response request(Request request, int timeout) throws RemotingException { } finally { removePendingReply(pendingReply); } + // timeout + if (response == null) { + throw new TimeoutException(channel, getTimeoutMessage(request, timeout, startTimeMs)); + } return response; } + public String getTimeoutMessage(Request request, int timeout, long startTimeMs) { + long nowTimestamp = System.currentTimeMillis(); + return "elapsed: " + (nowTimestamp - startTimeMs) + " ms, timeout: " + + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress(); + } + private static void addPendingReply(PendingReply pendingReply) { REPLY_HOLDER.putIfAbsent(pendingReply.getSavedReplyTo(), pendingReply); } @@ -127,6 +139,7 @@ public static void handleResponse(Response response) { replyHandoff.add(response); } + public boolean isClosed() { return closed; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 7a2a05c5029..4e2802aff97 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -57,13 +57,13 @@ public HeaderExchangeHandler(ExchangeHandler handler) { this.handler = handler; } - void handlerEvent(Channel channel, Request req) throws RemotingException { + private void handlerEvent(Channel channel, Request req) throws RemotingException { if (req.getData() != null && req.getData().equals(Request.READONLY_EVENT)) { channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); } } - Response handleRequest(ExchangeChannel channel, Request req) throws RemotingException { + private Response handleRequest(ExchangeChannel channel, Request req) throws RemotingException { Response.Builder builder = new Response.Builder(req.getId()); builder.version(req.getVersion()); if (req.isBroken()) { @@ -88,7 +88,7 @@ Response handleRequest(ExchangeChannel channel, Request req) throws RemotingExce return builder.build(); } - void handleResponse(Channel channel, Response response) throws RemotingException { + private void handleResponse(Channel channel, Response response) throws RemotingException { if (response != null && !response.isHeartbeat()) { DefaultFuture.received(channel, response); } @@ -173,7 +173,8 @@ public void received(Channel channel, Object message) throws RemotingException { handleResponse(channel, (Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { - Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); + Exception e = new Exception("Dubbo client can not supported string message: " + + message + " in channel: " + channel + ", url: " + channel.getUrl()); logger.error(e.getMessage(), e); } else { String echo = handler.telnet(channel, (String) message); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java new file mode 100644 index 00000000000..67825e74926 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java @@ -0,0 +1,202 @@ +package com.alibaba.dubbo.remoting.exchange.support.header; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.ExecutionException; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; + +import java.net.InetSocketAddress; + +/** + * @author Xs + */ +public class HeaderExchangeHandlerV2 implements ChannelHandlerDelegate { + + protected static final Logger logger = LoggerFactory.getLogger(HeaderExchangeHandler.class); + + public static String KEY_READ_TIMESTAMP = HeartbeatHandler.KEY_READ_TIMESTAMP; + + public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; + + private final ExchangeHandler handler; + + public HeaderExchangeHandlerV2(ExchangeHandler handler) { + if (handler == null) { + throw new IllegalArgumentException("handler == null"); + } + this.handler = handler; + } + + private void handlerEvent(Channel channel, Request req) throws RemotingException { + if (req.getData() != null && req.getData().equals(Request.READONLY_EVENT)) { + channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); + } + } + + private Response handleRequest(ExchangeChannel channel, Request req) throws RemotingException { + Response.Builder builder = new Response.Builder(req.getId()); + builder.version(req.getVersion()); + if (req.isBroken()) { + Object data = req.getData(); + String msg; + if (data == null) msg = null; + else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data); + else msg = data.toString(); + builder.errorMsg("Fail to decode request due to: " + msg); + builder.status(Response.BAD_REQUEST); + return builder.build(); + } + Object msg = req.getData(); + try { + Object result = handler.reply(channel, msg); + builder.status(Response.OK).result(result); + } catch (Throwable e) { + builder.status(Response.SERVICE_ERROR).errorMsg(StringUtils.toString(e)); + } + return builder.build(); + } + + private void handleResponse(Response response) throws RemotingException { + if (response != null && !response.isHeartbeat()) { + HeaderExchangeChannelV2.handleResponse(response); + } + } + + public void connected(Channel channel) throws RemotingException { + channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); + channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); + ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + try { + handler.connected(exchangeChannel); + } finally { + HeaderExchangeChannel.removeChannelIfDisconnected(channel); + } + } + + public void disconnected(Channel channel) throws RemotingException { + channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); + channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); + ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + try { + handler.disconnected(exchangeChannel); + } finally { + HeaderExchangeChannel.removeChannelIfDisconnected(channel); + } + } + + public void sent(Channel channel, Object message) throws RemotingException { + Throwable exception = null; + try { + channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); + ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + try { + handler.sent(exchangeChannel, message); + } finally { + HeaderExchangeChannel.removeChannelIfDisconnected(channel); + } + } catch (Throwable t) { + exception = t; + } + if (message instanceof Request) { + Request request = (Request) message; + DefaultFuture.sent(channel, request); + } + if (exception != null) { + if (exception instanceof RuntimeException) { + throw (RuntimeException) exception; + } else if (exception instanceof RemotingException) { + throw (RemotingException) exception; + } else { + throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), + exception.getMessage(), exception); + } + } + } + + private static boolean isClientSide(Channel channel) { + InetSocketAddress address = channel.getRemoteAddress(); + URL url = channel.getUrl(); + return url.getPort() == address.getPort() && + NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + } + + public void received(Channel channel, Object message) throws RemotingException { + channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); + ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + try { + if (message instanceof Request) { + Request request = (Request) message; + if (request.isEvent()) { + handlerEvent(channel, request); + } else { + if (request.isTwoWay()) { + Response response = handleRequest(exchangeChannel, request); + channel.send(response); + } else { + handler.received(exchangeChannel, request.getData()); + } + } + } else if (message instanceof Response) { + handleResponse((Response) message); + } else if (message instanceof String) { + if (isClientSide(channel)) { + Exception e = new Exception("Dubbo client can not supported string message: " + + message + " in channel: " + channel + ", url: " + channel.getUrl()); + logger.error(e.getMessage(), e); + } else { + String echo = handler.telnet(channel, (String) message); + if (echo != null && echo.length() > 0) { + channel.send(echo); + } + } + } else { + handler.received(exchangeChannel, message); + } + } finally { + HeaderExchangeChannel.removeChannelIfDisconnected(channel); + } + } + + public void caught(Channel channel, Throwable exception) throws RemotingException { + if (exception instanceof ExecutionException) { + ExecutionException e = (ExecutionException) exception; + Object msg = e.getRequest(); + if (msg instanceof Request) { + Request req = (Request) msg; + if (req.isTwoWay() && !req.isHeartbeat()) { + Response.Builder builder = new Response.Builder(req.getId()); + builder.version(req.getVersion()).status(Response.SERVER_ERROR).errorMsg(StringUtils.toString(e)); + channel.send(builder.build()); + return; + } + } + } + ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + try { + handler.caught(exchangeChannel, exception); + } finally { + HeaderExchangeChannel.removeChannelIfDisconnected(channel); + } + } + + public ChannelHandler getHandler() { + if (handler instanceof ChannelHandlerDelegate) { + return ((ChannelHandlerDelegate) handler).getHandler(); + } else { + return handler; + } + } +} From 28acaf1f8d22fb2e8cbbd326363217a04c17d83b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Wed, 18 Jan 2017 20:43:51 +0800 Subject: [PATCH 12/69] add TrackerEngine... --- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../dubbo/remoting/exchange/Interceptor.java | 4 +- .../header/HeaderExchangeClientV2.java | 14 +- .../dubbo/rpc/filter/ContextFilter.java | 18 +-- .../protocol/dubbo/filter/FutureFilter.java | 4 +- .../tracker/ClientRequestInterceptor.java | 7 + .../tracker/ClientResponseInterceptor.java | 7 + .../ConsumerInvocationInterceptor.java | 9 -- .../tracker/ConsumerResultInterceptor.java | 10 -- .../alibaba/dubbo/tracker/DubboRequest.java | 41 ++++++ .../tracker/DubboRequestSpanNameProvider.java | 13 ++ .../alibaba/dubbo/tracker/DubboResponse.java | 40 ++++++ .../dubbo/tracker/InvocationInterceptor.java | 11 -- .../ProviderInvocationInterceptor.java | 6 - .../tracker/ProviderResultInterceptor.java | 6 - .../tracker/RpcRequestSpanNameProvider.java | 13 -- .../com/alibaba/dubbo/tracker/RpcTracker.java | 10 +- .../dubbo/tracker/RpcTrackerEngine.java | 8 ++ .../tracker/ServerRequestInterceptor.java | 4 + .../tracker/ServerResponseInterceptor.java | 4 + .../zipkin/BraveClientRequestAdapter.java | 59 -------- .../BraveConsumerInvocationInterceptor.java | 30 ---- .../BraveConsumerResultInterceptor.java | 26 ---- .../BraveDubboClientRequestInterceptor.java | 24 ++++ .../BraveDubboClientResponseInterceptor.java | 19 +++ .../BraveProviderInvocationInterceptor.java | 26 ---- .../BraveProviderResultInterceptor.java | 22 --- .../dubbo/tracker/zipkin/BraveRpcTracker.java | 66 --------- .../tracker/zipkin/BraveRpcTrackerEngine.java | 37 +++++ .../zipkin/BraveRpcTrackerFactory.java | 58 ++++---- .../zipkin/BraveServerRequestAdapter.java | 130 +++++++++--------- .../zipkin/BraveServerResponseAdapter.java | 58 ++++---- .../zipkin/DubboClientRequestAdapter.java | 60 ++++++++ .../zipkin/DubboClientRequestInterceptor.java | 8 ++ ...r.java => DubboClientResponseAdapter.java} | 22 +-- .../DubboClientResponseInterceptor.java | 8 ++ .../DubboRequestResponseInterceptor.java | 33 +++++ .../dubbo/tracker/zipkin/DubboRpcTracker.java | 30 ++++ .../MappedServerClientAndLocalSpanState.java | 62 --------- .../filter/BraveClientRpcTrackerFilter.java | 29 ---- ...ilter.java => BraveHttpServletFilter.java} | 7 +- .../filter/BraveServerRpcTrackerFilter.java | 29 ---- .../zipkin/http/HttpClientRequestAdapter.java | 55 ++++++++ .../http/HttpClientRequestInterceptor.java | 6 + .../http/HttpClientResponseInterceptor.java | 6 + .../http/HttpRequestResponseInterceptor.java | 31 +++++ .../tracker/zipkin/http/HttpRpcTracker.java | 30 ++++ 47 files changed, 636 insertions(+), 566 deletions(-) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{BraveClientResponseAdapter.java => DubboClientResponseAdapter.java} (54%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/{BraveServletFilter.java => BraveHttpServletFilter.java} (73%) delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index f4d474662e1..253030dd2a6 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -62,7 +62,7 @@ - + diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java index 28d2b6bce24..37a1b9dad78 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java @@ -7,12 +7,14 @@ */ public interface Interceptor { - Response intercept(Chain chain); + Response intercept(Chain chain) throws RemotingException; interface Chain { Request request(); + int timeout(); + Response proceed(Request request, int timeout) throws RemotingException; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java index 3cc7a19cab7..45050cb8183 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java @@ -128,7 +128,7 @@ public Response request(Object request, int timeout) throws RemotingException { Request.Builder builder = new Request.Builder(); builder.newId().version(Version.getVersion()).twoWay(true).data(request); Request req = builder.build(); - Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, req); + Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, req, timeout); return chain.proceed(req, timeout); } @@ -145,9 +145,12 @@ class ExchangeClientInterceptorChain implements Interceptor.Chain { private final Request request; - ExchangeClientInterceptorChain(int index, Request request) { + private final int timeout; + + ExchangeClientInterceptorChain(int index, Request request, int timeout) { this.index = index; this.request = request; + this.timeout = timeout; } @Override @@ -155,10 +158,15 @@ public Request request() { return request; } + @Override + public int timeout() { + return timeout; + } + @Override public Response proceed(Request request, int timeout) throws RemotingException { if (index < interceptors.size()) { - Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request); + Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request, timeout); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(chain); if (response == null) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java index 4097697ecfb..15b15739870 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java @@ -15,22 +15,16 @@ */ package com.alibaba.dubbo.rpc.filter; -import java.util.HashMap; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.*; + +import java.util.HashMap; +import java.util.Map; /** * ContextInvokerFilter - * + * * @author william.liangf */ @Activate(group = Constants.PROVIDER, order = -10000) @@ -64,7 +58,7 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } if (invocation instanceof RpcInvocation) { - ((RpcInvocation)invocation).setInvoker(invoker); + ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 9b907daaad1..0bb309a3465 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -102,7 +102,7 @@ private void fireInvokeCallback(final Invoker invoker, final Invocation invoc if (onInvokeMethod == null || onInvokeInst == null) { throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } - if (onInvokeMethod != null && !onInvokeMethod.isAccessible()) { + if (!onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); } @@ -128,7 +128,7 @@ private void fireReturnCallback(final Invoker invoker, final Invocation invoc if (onReturnMethod == null || onReturnInst == null) { throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } - if (onReturnMethod != null && !onReturnMethod.isAccessible()) { + if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java new file mode 100644 index 00000000000..c113aa5128a --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface ClientRequestInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java new file mode 100644 index 00000000000..b01a1aad797 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface ClientResponseInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java deleted file mode 100644 index 21018bfd880..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerInvocationInterceptor.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public interface ConsumerInvocationInterceptor { - - void handle(RpcRequest request); -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java deleted file mode 100644 index ed5f2aaf775..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ConsumerResultInterceptor.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public interface ConsumerResultInterceptor { - - void handle(RpcResponse response); - -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java new file mode 100644 index 00000000000..849d21a1a84 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -0,0 +1,41 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.rpc.RpcInvocation; + +public class DubboRequest { + + private final Request request; + + private RpcInvocation invocation; + + private boolean isTraceable; + + public DubboRequest(Request request) { + this.request = request; + if (request.getData() instanceof RpcInvocation) { + isTraceable = true; + invocation = (RpcInvocation) request.getData(); + } + } + + public String getMethodName() { + return invocation.getMethodName(); + } + + public boolean isTraceable() { + return isTraceable; + } + + public void addAttachment(String key, String value) { + invocation.setAttachment(key, value); + } + + public String providerAddress() { + return invocation.getInvoker().getUrl().getAddress(); + } + + public Request getRequest() { + return request; + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java new file mode 100644 index 00000000000..1a8b4056b56 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.RpcContext; + +/** + * @author Xs + */ +public class DubboRequestSpanNameProvider { + + public String spanName() { + return RpcContext.getContext().getMethodName(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java new file mode 100644 index 00000000000..453ff408dc1 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -0,0 +1,40 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.rpc.RpcResult; + +public class DubboResponse { + + private final Response response; + + private boolean isTraceable; + + private volatile RpcResult result; + + public DubboResponse(Response response) { + this.response = response; + if (response.getResult() instanceof RpcResult) { + isTraceable = true; + result = (RpcResult) response.getResult(); + } + } + + public boolean returnSuccessfully() { + return !result.hasException(); + } + + public boolean isTraceable() { + return isTraceable; + } + + public String exceptionMessage() { + if (returnSuccessfully()) { + return "result OK"; + } + Throwable throwable = result.getException(); + if (throwable instanceof NullPointerException) { + return "NullPointerException"; + } + return throwable.getMessage(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java deleted file mode 100644 index a5072247984..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/InvocationInterceptor.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public class InvocationInterceptor { - - private ConsumerInvocationInterceptor consumerInvocationInterceptor; - - -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java deleted file mode 100644 index dc5575d6fd4..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderInvocationInterceptor.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.alibaba.dubbo.tracker; - -public interface ProviderInvocationInterceptor { - - void handle(RpcRequest request); -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java deleted file mode 100644 index df7562d5d8e..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ProviderResultInterceptor.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.alibaba.dubbo.tracker; - -public interface ProviderResultInterceptor { - - void handle(RpcResponse response); -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java deleted file mode 100644 index 63150f2378b..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequestSpanNameProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.alibaba.dubbo.tracker; - -import com.alibaba.dubbo.rpc.Invocation; - -/** - * @author Xs - */ -public class RpcRequestSpanNameProvider { - - public String spanName(RpcRequest rpcRequest) { - return rpcRequest.getMethodName(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index a3aa2cff007..8ef4f2dd002 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -7,13 +7,11 @@ */ public interface RpcTracker { - ConsumerInvocationInterceptor clientRequestInterceptor(); + ClientRequestInterceptor clientRequestInterceptor(); - ConsumerResultInterceptor clientResponseInterceptor(); - - ProviderInvocationInterceptor serverRequestInterceptor(); - - ProviderResultInterceptor serverResponseInterceptor(); + ClientResponseInterceptor clientResponseInterceptor(); ServletFilter servletFilter(); + + RpcTrackerEngine trackerEngine(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java index d61587cb663..4c22fc1377a 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java @@ -1,4 +1,12 @@ package com.alibaba.dubbo.tracker; public interface RpcTrackerEngine { + + Object clientRequestInterceptor(); + + Object clientResponseInterceptor(); + + Object serverRequestInterceptor(); + + Object serverResponseInterceptor(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java new file mode 100644 index 00000000000..3a1110e6fd0 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java @@ -0,0 +1,4 @@ +package com.alibaba.dubbo.tracker; + +public interface ServerRequestInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java new file mode 100644 index 00000000000..a43e1a5d169 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java @@ -0,0 +1,4 @@ +package com.alibaba.dubbo.tracker; + +public interface ServerResponseInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java deleted file mode 100644 index b42b65064e4..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientRequestAdapter.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.TrackerKeys; -import com.github.kristofa.brave.ClientRequestAdapter; -import com.github.kristofa.brave.IdConversion; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.SpanId; -import com.twitter.zipkin.gen.Endpoint; - -import java.util.Collection; -import java.util.Collections; - -/** - * @author Xs - */ -public class BraveClientRequestAdapter implements ClientRequestAdapter { - - private final RpcRequestSpanNameProvider spanNameProvider; - - private final RpcRequest rpcRequest; - - public BraveClientRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { - this.rpcRequest = rpcRequest; - this.spanNameProvider = spanNameProvider; - } - - @Override - public String getSpanName() { - return spanNameProvider.spanName(rpcRequest); - } - - @Override - public void addSpanIdToRequest(SpanId spanId) { - if (spanId == null) { - rpcRequest.addAttachment(RpcAttachment.Sampled.getName(), "0"); - } else { - rpcRequest.addAttachment(RpcAttachment.Sampled.getName(), "1"); - rpcRequest.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); - rpcRequest.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); - if (spanId.nullableParentId() != null) { - rpcRequest.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); - } - } - } - - @Override - public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); - return Collections.singletonList(annotation); - } - - @Override - public Endpoint serverAddress() { - return null; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java deleted file mode 100644 index 05a24494f8e..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerInvocationInterceptor.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ConsumerInvocationInterceptor; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; -import com.github.kristofa.brave.ClientRequestInterceptor; - -/** - * @author Xs - */ -public class BraveConsumerInvocationInterceptor implements ConsumerInvocationInterceptor { - - private final ClientRequestInterceptor clientRequestInterceptor; - - private final RpcRequestSpanNameProvider spanNameProvider; - - public BraveConsumerInvocationInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor, - RpcRequestSpanNameProvider spanNameProvider) { - this.clientRequestInterceptor = clientRequestInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public void handle(RpcRequest request) { - if (!request.isTraceableRequest()) { - return; - } - clientRequestInterceptor.handle(new BraveClientRequestAdapter(request, spanNameProvider)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java deleted file mode 100644 index 736b7ff5feb..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveConsumerResultInterceptor.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ConsumerResultInterceptor; -import com.alibaba.dubbo.tracker.RpcResponse; -import com.github.kristofa.brave.ClientResponseInterceptor; - -/** - * @author Xs - */ -public class BraveConsumerResultInterceptor implements ConsumerResultInterceptor { - - private final ClientResponseInterceptor clientResponseInterceptor; - - - public BraveConsumerResultInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { - this.clientResponseInterceptor = clientResponseInterceptor; - } - - @Override - public void handle(RpcResponse response) { - if (!response.isTraceableResponse()) { - return; - } - clientResponseInterceptor.handle(new BraveClientResponseAdapter(response)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java new file mode 100644 index 00000000000..f8cd275b08e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java @@ -0,0 +1,24 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.github.kristofa.brave.ClientRequestInterceptor; + +public class BraveDubboClientRequestInterceptor implements DubboClientRequestInterceptor { + + private final ClientRequestInterceptor clientRequestInterceptor; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public BraveDubboClientRequestInterceptor(ClientRequestInterceptor clientRequestInterceptor, + DubboRequestSpanNameProvider spanNameProvider) { + this.clientRequestInterceptor = clientRequestInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public void handle(DubboClientRequestAdapter clientRequestAdapter) { + if (clientRequestAdapter.isTraceable()) { + clientRequestInterceptor.handle(clientRequestAdapter); + } + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java new file mode 100644 index 00000000000..19d6151a4e4 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.github.kristofa.brave.ClientResponseInterceptor; + +public class BraveDubboClientResponseInterceptor implements DubboClientResponseInterceptor { + + private final ClientResponseInterceptor clientResponseInterceptor; + + public BraveDubboClientResponseInterceptor(ClientResponseInterceptor clientResponseInterceptor) { + this.clientResponseInterceptor = clientResponseInterceptor; + } + + @Override + public void handle(DubboClientResponseAdapter clientResponseAdapter) { + if (clientResponseAdapter.isTraceable()) { + clientResponseInterceptor.handle(clientResponseAdapter); + } + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java deleted file mode 100644 index d5870dcfa1a..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderInvocationInterceptor.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.ProviderInvocationInterceptor; - -public class BraveProviderInvocationInterceptor implements ProviderInvocationInterceptor { - - private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; - - private final RpcRequestSpanNameProvider spanNameProvider; - - public BraveProviderInvocationInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor, - RpcRequestSpanNameProvider spanNameProvider) { - this.serverRequestInterceptor = serverRequestInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public void handle(RpcRequest request) { - if (!request.isTraceableRequest()) { - return; - } - serverRequestInterceptor.handle(new BraveServerRequestAdapter(request, spanNameProvider)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java deleted file mode 100644 index a7b7ea3ddaf..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveProviderResultInterceptor.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - - -import com.alibaba.dubbo.tracker.RpcResponse; -import com.alibaba.dubbo.tracker.ProviderResultInterceptor; - -public class BraveProviderResultInterceptor implements ProviderResultInterceptor { - - private final com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor; - - public BraveProviderResultInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { - this.serverResponseInterceptor = serverResponseInterceptor; - } - - @Override - public void handle(RpcResponse response) { - if (!response.isTraceableResponse()) { - return; - } - serverResponseInterceptor.handle(new BraveServerResponseAdapter(response)); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java deleted file mode 100644 index 4a6beb08fb2..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTracker.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.*; -import com.alibaba.dubbo.tracker.filter.ServletFilter; -import com.alibaba.dubbo.tracker.zipkin.filter.BraveServletFilter; -import com.github.kristofa.brave.Brave; -import com.github.kristofa.brave.http.DefaultSpanNameProvider; - -/** - * @author Xs - */ -public class BraveRpcTracker implements RpcTracker { - - private final BraveConsumerInvocationInterceptor clientRequestInterceptor; - - private final BraveConsumerResultInterceptor clientResponseInterceptor; - - private final BraveProviderInvocationInterceptor serverRequestInterceptor; - - private final BraveProviderResultInterceptor serverResponseInterceptor; - - private final BraveServletFilter braveServletFilter; - - static BraveRpcTracker create(URL url) { - return new BraveRpcTracker(url); - } - - private BraveRpcTracker(URL url) { - Brave.Builder builder = new Brave.Builder(url.getParameter("application", "demo")); - builder.spanCollector(SpanCollectorFactory.create(url)); - builder.traceSampler(SamplerFactory.create(url)); - Brave brave = builder.build(); - clientRequestInterceptor = new BraveConsumerInvocationInterceptor(brave.clientRequestInterceptor(), new RpcRequestSpanNameProvider()); - clientResponseInterceptor = new BraveConsumerResultInterceptor(brave.clientResponseInterceptor()); - serverRequestInterceptor = new BraveProviderInvocationInterceptor(brave.serverRequestInterceptor(), new RpcRequestSpanNameProvider()); - serverResponseInterceptor = new BraveProviderResultInterceptor(brave.serverResponseInterceptor()); - braveServletFilter = new BraveServletFilter(new com.github.kristofa.brave.servlet.BraveServletFilter( - brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider())); - } - - @Override - public ConsumerInvocationInterceptor clientRequestInterceptor() { - return clientRequestInterceptor; - } - - @Override - public ConsumerResultInterceptor clientResponseInterceptor() { - return clientResponseInterceptor; - } - - @Override - public ProviderInvocationInterceptor serverRequestInterceptor() { - return serverRequestInterceptor; - } - - @Override - public ProviderResultInterceptor serverResponseInterceptor() { - return serverResponseInterceptor; - } - - @Override - public ServletFilter servletFilter() { - return braveServletFilter; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java new file mode 100644 index 00000000000..b945698a42b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java @@ -0,0 +1,37 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.github.kristofa.brave.Brave; + +public class BraveRpcTrackerEngine implements RpcTrackerEngine { + + private final Brave brave; + + public BraveRpcTrackerEngine(URL url) { + Brave.Builder builder = new Brave.Builder(url.getParameter("application", "demo")); + builder.spanCollector(SpanCollectorFactory.create(url)); + builder.traceSampler(SamplerFactory.create(url)); + brave = builder.build(); + } + + @Override + public Object clientRequestInterceptor() { + return brave.clientRequestInterceptor(); + } + + @Override + public Object clientResponseInterceptor() { + return brave.clientResponseInterceptor(); + } + + @Override + public Object serverRequestInterceptor() { + return brave.serverRequestInterceptor(); + } + + @Override + public Object serverResponseInterceptor() { + return brave.serverResponseInterceptor(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index 7e4a2966d03..b4710b118b9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -1,29 +1,29 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; - -/** - * @author Xs - */ -public class BraveRpcTrackerFactory implements RpcTrackerFactory { - - private volatile BraveRpcTracker braveRpcTracker; - - @Override - public RpcTracker createRpcTracker(URL url) { - if (braveRpcTracker == null) { - braveRpcTracker = BraveRpcTracker.create(url); - } - return braveRpcTracker; - } - - @Override - public RpcTracker getTracker() { - if (braveRpcTracker == null) { - throw new IllegalStateException("braveRpcTracker must not be null"); - } - return braveRpcTracker; - } -} +//package com.alibaba.dubbo.tracker.zipkin; +// +//import com.alibaba.dubbo.common.URL; +//import com.alibaba.dubbo.tracker.RpcTracker; +//import com.alibaba.dubbo.tracker.RpcTrackerFactory; +// +///** +// * @author Xs +// */ +//public class BraveRpcTrackerFactory implements RpcTrackerFactory { +// +// private volatile BraveRpcTracker braveRpcTracker; +// +// @Override +// public RpcTracker createRpcTracker(URL url) { +// if (braveRpcTracker == null) { +// braveRpcTracker = BraveRpcTracker.create(url); +// } +// return braveRpcTracker; +// } +// +// @Override +// public RpcTracker getTracker() { +// if (braveRpcTracker == null) { +// throw new IllegalStateException("braveRpcTracker must not be null"); +// } +// return braveRpcTracker; +// } +//} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java index 5c89f690685..beb320c339c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java @@ -1,65 +1,65 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.TrackerKeys; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.ServerRequestAdapter; -import com.github.kristofa.brave.SpanId; -import com.github.kristofa.brave.TraceData; - -import java.util.Collection; -import java.util.Collections; - -import static com.github.kristofa.brave.IdConversion.convertToLong; - -public class BraveServerRequestAdapter implements ServerRequestAdapter { - - private final RpcRequestSpanNameProvider spanNameProvider; - - private final RpcRequest rpcRequest; - - public BraveServerRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { - this.spanNameProvider = spanNameProvider; - this.rpcRequest = rpcRequest; - } - - @Override - public TraceData getTraceData() { - final String sampled = rpcRequest.getAttachment(RpcAttachment.Sampled.getName()); - if (sampled != null) { - if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { - return TraceData.builder().sample(false).build(); - } else { - final String parentSpanId = rpcRequest.getAttachment(RpcAttachment.ParentSpanId.getName()); - final String traceId = rpcRequest.getAttachment(RpcAttachment.TraceId.getName()); - final String spanId = rpcRequest.getAttachment(RpcAttachment.SpanId.getName()); - - if (traceId != null && spanId != null) { - SpanId span = getSpanId(traceId, spanId, parentSpanId); - return TraceData.builder().sample(true).spanId(span).build(); - } - } - } - return TraceData.builder().build(); - } - - @Override - public String getSpanName() { - return spanNameProvider.spanName(rpcRequest); - } - - @Override - public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); - return Collections.singletonList(annotation); - } - - private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { - return SpanId.builder() - .traceId(convertToLong(traceId)) - .spanId(convertToLong(spanId)) - .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); - } -} +//package com.alibaba.dubbo.tracker.zipkin; +// +//import com.alibaba.dubbo.tracker.RpcAttachment; +//import com.alibaba.dubbo.tracker.RpcRequest; +//import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; +//import com.alibaba.dubbo.tracker.TrackerKeys; +//import com.github.kristofa.brave.KeyValueAnnotation; +//import com.github.kristofa.brave.ServerRequestAdapter; +//import com.github.kristofa.brave.SpanId; +//import com.github.kristofa.brave.TraceData; +// +//import java.util.Collection; +//import java.util.Collections; +// +//import static com.github.kristofa.brave.IdConversion.convertToLong; +// +//public class BraveServerRequestAdapter implements ServerRequestAdapter { +// +// private final RpcRequestSpanNameProvider spanNameProvider; +// +// private final RpcRequest rpcRequest; +// +// public BraveServerRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { +// this.spanNameProvider = spanNameProvider; +// this.rpcRequest = rpcRequest; +// } +// +// @Override +// public TraceData getTraceData() { +// final String sampled = rpcRequest.getAttachment(RpcAttachment.Sampled.getName()); +// if (sampled != null) { +// if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { +// return TraceData.builder().sample(false).build(); +// } else { +// final String parentSpanId = rpcRequest.getAttachment(RpcAttachment.ParentSpanId.getName()); +// final String traceId = rpcRequest.getAttachment(RpcAttachment.TraceId.getName()); +// final String spanId = rpcRequest.getAttachment(RpcAttachment.SpanId.getName()); +// +// if (traceId != null && spanId != null) { +// SpanId span = getSpanId(traceId, spanId, parentSpanId); +// return TraceData.builder().sample(true).spanId(span).build(); +// } +// } +// } +// return TraceData.builder().build(); +// } +// +// @Override +// public String getSpanName() { +// return spanNameProvider.spanName(rpcRequest); +// } +// +// @Override +// public Collection requestAnnotations() { +// KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); +// return Collections.singletonList(annotation); +// } +// +// private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { +// return SpanId.builder() +// .traceId(convertToLong(traceId)) +// .spanId(convertToLong(spanId)) +// .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); +// } +//} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java index c969eeefe29..4bca89a1be9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java @@ -1,29 +1,29 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.RpcResponse; -import com.alibaba.dubbo.tracker.TrackerKeys; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.ServerResponseAdapter; - -import java.util.Collection; -import java.util.Collections; - -public class BraveServerResponseAdapter implements ServerResponseAdapter { - - private final RpcResponse rpcResponse; - - public BraveServerResponseAdapter(RpcResponse rpcResponse) { - this.rpcResponse = rpcResponse; - } - - @Override - public Collection responseAnnotations() { - KeyValueAnnotation statusAnnotation; - if (rpcResponse.returnSuccessfully()) { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); - } else { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); - } - return Collections.singletonList(statusAnnotation); - } -} +//package com.alibaba.dubbo.tracker.zipkin; +// +//import com.alibaba.dubbo.tracker.RpcResponse; +//import com.alibaba.dubbo.tracker.TrackerKeys; +//import com.github.kristofa.brave.KeyValueAnnotation; +//import com.github.kristofa.brave.ServerResponseAdapter; +// +//import java.util.Collection; +//import java.util.Collections; +// +//public class BraveServerResponseAdapter implements ServerResponseAdapter { +// +// private final RpcResponse rpcResponse; +// +// public BraveServerResponseAdapter(RpcResponse rpcResponse) { +// this.rpcResponse = rpcResponse; +// } +// +// @Override +// public Collection responseAnnotations() { +// KeyValueAnnotation statusAnnotation; +// if (rpcResponse.returnSuccessfully()) { +// statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); +// } else { +// statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); +// } +// return Collections.singletonList(statusAnnotation); +// } +//} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java new file mode 100644 index 00000000000..d16ef5e5d53 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java @@ -0,0 +1,60 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.ClientRequestAdapter; +import com.github.kristofa.brave.IdConversion; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.SpanId; +import com.twitter.zipkin.gen.Endpoint; + +import java.util.Collection; +import java.util.Collections; + +public class DubboClientRequestAdapter implements ClientRequestAdapter { + + private final DubboRequest request; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public DubboClientRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { + this.request = request; + this.spanNameProvider = spanNameProvider; + } + + public boolean isTraceable() { + return request.isTraceable(); + } + + @Override + public String getSpanName() { + return spanNameProvider.spanName(); + } + + @Override + public void addSpanIdToRequest(SpanId spanId) { + if (spanId == null) { + request.addAttachment(RpcAttachment.Sampled.getName(), "0"); + } else { + request.addAttachment(RpcAttachment.Sampled.getName(), "1"); + request.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); + request.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); + if (spanId.nullableParentId() != null) { + request.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); + } + } + } + + @Override + public Collection requestAnnotations() { + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.providerAddress()); + return Collections.singletonList(annotation); + } + + @Override + public Endpoint serverAddress() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java new file mode 100644 index 00000000000..35ecc0f5180 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java @@ -0,0 +1,8 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; + +public interface DubboClientRequestInterceptor extends ClientRequestInterceptor { + + void handle(DubboClientRequestAdapter clientRequestAdapter); +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java similarity index 54% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java index 3a94de5fd3a..5ad7174423f 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.RpcResponse; +import com.alibaba.dubbo.tracker.DubboResponse; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientResponseAdapter; import com.github.kristofa.brave.KeyValueAnnotation; @@ -8,24 +8,24 @@ import java.util.Collection; import java.util.Collections; -/** - * @author Xs - */ -public class BraveClientResponseAdapter implements ClientResponseAdapter { +public class DubboClientResponseAdapter implements ClientResponseAdapter { - private final RpcResponse rpcResponse; + private final DubboResponse response; - public BraveClientResponseAdapter(RpcResponse rpcResponse) { - this.rpcResponse = rpcResponse; + public DubboClientResponseAdapter(DubboResponse response) { + this.response = response; + } + + public boolean isTraceable() { + return response.isTraceable(); } @Override public Collection responseAnnotations() { - if (!rpcResponse.returnSuccessfully()) { - KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); + if (!response.returnSuccessfully()) { + KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); return Collections.singletonList(statusAnnotation); } return Collections.emptyList(); - } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java new file mode 100644 index 00000000000..c06bf6418d2 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java @@ -0,0 +1,8 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; + +public interface DubboClientResponseInterceptor extends ClientResponseInterceptor { + + void handle(DubboClientResponseAdapter clientResponseAdapter); +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java new file mode 100644 index 00000000000..5973bdcc5ab --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java @@ -0,0 +1,33 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.Interceptor; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.DubboResponse; + +public class DubboRequestResponseInterceptor implements Interceptor { + + private final DubboClientRequestInterceptor clientRequestInterceptor; + private final DubboClientResponseInterceptor clientResponseInterceptor; + private final DubboRequestSpanNameProvider spanNameProvider; + + public DubboRequestResponseInterceptor(DubboClientRequestInterceptor clientRequestInterceptor, + DubboClientResponseInterceptor clientResponseInterceptor, + DubboRequestSpanNameProvider spanNameProvider) { + this.clientRequestInterceptor = clientRequestInterceptor; + this.clientResponseInterceptor = clientResponseInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public Response intercept(Chain chain) throws RemotingException { + Request request = chain.request(); + clientRequestInterceptor.handle(new DubboClientRequestAdapter(new DubboRequest(request), spanNameProvider)); + Response response = chain.proceed(request, chain.timeout()); + clientResponseInterceptor.handle(new DubboClientResponseAdapter(new DubboResponse(response))); + return response; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java new file mode 100644 index 00000000000..0c936d4f4aa --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.filter.ServletFilter; + +public class DubboRpcTracker implements RpcTracker { + + @Override + public ClientRequestInterceptor clientRequestInterceptor() { + return null; + } + + @Override + public ClientResponseInterceptor clientResponseInterceptor() { + return null; + } + + @Override + public ServletFilter servletFilter() { + return null; + } + + @Override + public RpcTrackerEngine trackerEngine() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java deleted file mode 100644 index 8c348af338f..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/MappedServerClientAndLocalSpanState.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.github.kristofa.brave.ServerClientAndLocalSpanState; -import com.github.kristofa.brave.ServerSpan; -import com.github.kristofa.brave.internal.Util; -import com.twitter.zipkin.gen.Endpoint; -import com.twitter.zipkin.gen.Span; - -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Xs - */ -public class MappedServerClientAndLocalSpanState implements ServerClientAndLocalSpanState { - - private final Endpoint endpoint; - - public MappedServerClientAndLocalSpanState(int ip, int port, String serviceName) { - Util.checkNotBlank(serviceName, "Service name must be specified."); - endpoint = Endpoint.create(serviceName, ip, port); - } - - @Override - public Span getCurrentClientSpan() { - return null; - } - - @Override - public void setCurrentClientSpan(Span span) { - - } - - @Override - public Span getCurrentLocalSpan() { - return null; - } - - @Override - public void setCurrentLocalSpan(Span span) { - - } - - @Override - public ServerSpan getCurrentServerSpan() { - return null; - } - - @Override - public void setCurrentServerSpan(ServerSpan span) { - - } - - @Override - public Boolean sample() { - return null; - } - - @Override - public Endpoint endpoint() { - return null; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java deleted file mode 100644 index b7e51e8eccd..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveClientRpcTrackerFilter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.filter; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcResponse; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.TrackerManager; -import com.alibaba.dubbo.tracker.filter.ClientRpcTrackerFilter; - -/** - * @author Xs - */ -//@Activate(group = Constants.CONSUMER, order = Integer.MAX_VALUE) -public class BraveClientRpcTrackerFilter implements ClientRpcTrackerFilter { - - @Override - public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - RpcTracker rpcTracker = TrackerManager.mockRpcTracker("192.168.150.132:9411", "consumer"); - rpcTracker.clientRequestInterceptor().handle(new RpcRequest(invoker, invocation)); - Result result = invoker.invoke(invocation); - rpcTracker.clientResponseInterceptor().handle(new RpcResponse(invoker, result)); - return result; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java similarity index 73% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java index 671db9a7b6e..fd1bb566df9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServletFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java @@ -1,15 +1,16 @@ package com.alibaba.dubbo.tracker.zipkin.filter; import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.github.kristofa.brave.servlet.BraveServletFilter; import javax.servlet.*; import java.io.IOException; -public class BraveServletFilter implements ServletFilter { +public class BraveHttpServletFilter implements ServletFilter { - private final com.github.kristofa.brave.servlet.BraveServletFilter servletFilter; + private final BraveServletFilter servletFilter; - public BraveServletFilter(com.github.kristofa.brave.servlet.BraveServletFilter servletFilter) { + public BraveHttpServletFilter(BraveServletFilter servletFilter) { this.servletFilter = servletFilter; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java deleted file mode 100644 index 7a04e78a8e5..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveServerRpcTrackerFilter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.filter; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.tracker.RpcRequest; -import com.alibaba.dubbo.tracker.RpcResponse; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.TrackerManager; -import com.alibaba.dubbo.tracker.filter.ServerRpcTrackerFilter; - -/** - * @author Xs - */ -//@Activate(group = Constants.PROVIDER, order = Integer.MIN_VALUE) -public class BraveServerRpcTrackerFilter implements ServerRpcTrackerFilter { - - @Override - public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - RpcTracker rpcTracker = TrackerManager.mockRpcTracker("192.168.150.132:9411", "provider"); - rpcTracker.serverRequestInterceptor().handle(new RpcRequest(invoker, invocation)); - Result result = invoker.invoke(invocation); - rpcTracker.serverResponseInterceptor().handle(new RpcResponse(invoker, result)); - return result; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java new file mode 100644 index 00000000000..4e4a9fbaf9b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java @@ -0,0 +1,55 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.github.kristofa.brave.*; +import com.github.kristofa.brave.http.HttpClientRequest; +import com.github.kristofa.brave.internal.Nullable; +import com.twitter.zipkin.gen.Endpoint; + +import java.net.URI; +import java.util.Collection; +import java.util.Collections; + +public class HttpClientRequestAdapter implements ClientRequestAdapter { + + private final HttpClientRequest request; + private final DubboRequestSpanNameProvider spanNameProvider; + + public HttpClientRequestAdapter(HttpClientRequest request, DubboRequestSpanNameProvider spanNameProvider) { + this.request = request; + this.spanNameProvider = spanNameProvider; + } + + @Override + public String getSpanName() { + return spanNameProvider.spanName(); + } + + @Override + public void addSpanIdToRequest(@Nullable SpanId spanId) { + if (spanId == null) { + request.addHeader(RpcAttachment.Sampled.getName(), "0"); + } else { + request.addHeader(RpcAttachment.Sampled.getName(), "1"); + request.addHeader(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); + request.addHeader(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); + if (spanId.nullableParentId() != null) { + request.addHeader(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); + } + request.addHeader(RpcAttachment.Method.getName(), getSpanName()); + } + } + + @Override + public Collection requestAnnotations() { + URI uri = request.getUri(); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TraceKeys.HTTP_URL, uri.toString()); + return Collections.singletonList(annotation); + } + + @Override + public Endpoint serverAddress() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java new file mode 100644 index 00000000000..845f0386dcb --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; + +public interface HttpClientRequestInterceptor extends ClientRequestInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java new file mode 100644 index 00000000000..77aaa1dc0d6 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; + +public interface HttpClientResponseInterceptor extends ClientResponseInterceptor { +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java new file mode 100644 index 00000000000..47759e6534f --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java @@ -0,0 +1,31 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.github.kristofa.brave.ClientRequestInterceptor; +import com.github.kristofa.brave.ClientResponseInterceptor; +import com.github.kristofa.brave.http.SpanNameProvider; +import okhttp3.Interceptor; +import okhttp3.Response; + +import java.io.IOException; + +public class HttpRequestResponseInterceptor implements Interceptor { + + private final ClientRequestInterceptor clientRequestInterceptor; + private final ClientResponseInterceptor clientResponseInterceptor; + + public HttpRequestResponseInterceptor(ClientRequestInterceptor clientRequestInterceptor, + ClientResponseInterceptor clientResponseInterceptor, + SpanNameProvider spanNameProvider) { + this.clientRequestInterceptor = clientRequestInterceptor; + this.clientResponseInterceptor = clientResponseInterceptor; + this.spanNameProvider = spanNameProvider; + } + + private final SpanNameProvider spanNameProvider; + + @Override + public Response intercept(Chain chain) throws IOException { + return null; + } + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java new file mode 100644 index 00000000000..1fdc0d6396d --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.filter.ServletFilter; + +public class HttpRpcTracker implements RpcTracker{ + + @Override + public ClientRequestInterceptor clientRequestInterceptor() { + return null; + } + + @Override + public ClientResponseInterceptor clientResponseInterceptor() { + return null; + } + + @Override + public ServletFilter servletFilter() { + return null; + } + + @Override + public RpcTrackerEngine trackerEngine() { + return null; + } +} From 4bc35da835ef031a4d4516891bca82a717f6f908 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 18 Jan 2017 23:31:40 +0800 Subject: [PATCH 13/69] BraveRpcTrackerEngineFactory --- .../alibaba/dubbo/tracker/DubboRequest.java | 4 ++ .../com/alibaba/dubbo/tracker/RpcTracker.java | 6 +- .../tracker/RpcTrackerEngineFactory.java | 17 +++++ .../dubbo/tracker/RpcTrackerFactory.java | 2 - .../alibaba/dubbo/tracker/TrackerManager.java | 43 +++++++++-- .../BraveDubboClientRequestInterceptor.java | 7 +- .../BraveDubboServerRequestInterceptor.java | 23 ++++++ .../BraveDubboServerResponseInterceptor.java | 23 ++++++ .../tracker/zipkin/BraveRpcTrackerEngine.java | 6 +- .../zipkin/BraveRpcTrackerEngineFactory.java | 26 +++++++ .../zipkin/BraveRpcTrackerFactory.java | 54 +++++++------- .../zipkin/BraveServerRequestAdapter.java | 65 ----------------- .../zipkin/BraveServerResponseAdapter.java | 29 -------- .../dubbo/tracker/zipkin/DubboRpcTracker.java | 43 ++++++++--- .../zipkin/DubboServerRequestAdapter.java | 72 +++++++++++++++++++ .../zipkin/DubboServerRequestInterceptor.java | 12 ++++ .../zipkin/DubboServerResponseAdapter.java | 37 ++++++++++ .../DubboServerResponseInterceptor.java | 11 +++ .../tracker/zipkin/http/HttpRpcTracker.java | 15 ++-- ...baba.dubbo.tracker.RpcTrackerEngineFactory | 1 + .../tracker/zipkin/test/ExtensionTest.java | 22 +++++- ...baba.dubbo.tracker.RpcTrackerEngineFactory | 1 + 22 files changed, 360 insertions(+), 159 deletions(-) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java index 849d21a1a84..aafe335d6dc 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -31,6 +31,10 @@ public void addAttachment(String key, String value) { invocation.setAttachment(key, value); } + public String getAttachment(String key){ + return invocation.getAttachment(key); + } + public String providerAddress() { return invocation.getInvoker().getUrl().getAddress(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index 8ef4f2dd002..28d5e1c24b1 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.sun.javafx.scene.traversal.TraversalEngine; /** * @author Xs @@ -11,7 +11,9 @@ public interface RpcTracker { ClientResponseInterceptor clientResponseInterceptor(); - ServletFilter servletFilter(); + ServerRequestInterceptor serverRequestInterceptor(); + + ServerResponseInterceptor serverResponseInterceptor(); RpcTrackerEngine trackerEngine(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java new file mode 100644 index 00000000000..74af47aeb70 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java @@ -0,0 +1,17 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * @author Xs + */ +@SPI("zipkin") +public interface RpcTrackerEngineFactory { + + @Adaptive("protocol") + RpcTrackerEngine createRpcTrackerEngine(URL url); + + RpcTrackerEngine getTrackerEngine(); +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java index 51c525ccdff..be1ce7aec20 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -13,6 +13,4 @@ public interface RpcTrackerFactory { @Adaptive("protocol") RpcTracker createRpcTracker(URL url); - RpcTracker getTracker(); - } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java index 4d29eac9bbf..9742866dde8 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java @@ -3,6 +3,9 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; +import java.util.HashMap; +import java.util.Map; + /** * @author Xs */ @@ -10,24 +13,54 @@ public class TrackerManager { private static RpcTrackerFactory rpcTrackerFactory; - private static RpcTracker rpcTracker; + private static RpcTrackerEngineFactory rpcTrackerEngineFactory; + + private static RpcTrackerEngine rpcTrackerEngine; + + private static Map rpcTrackerMap = new HashMap(); static { - rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getAdaptiveExtension(); + rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getDefaultExtension(); + rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); } public static RpcTrackerFactory getTrackerFactory() { return rpcTrackerFactory; } - public static synchronized RpcTracker create(URL url) { + public static RpcTrackerEngineFactory getRpcTrackerEngineFactory() { + return rpcTrackerEngineFactory; + } + + public static RpcTrackerEngine getRpcTrackerEngine() { + if (rpcTrackerEngine == null) { + throw new IllegalStateException("rpcTrackerEngine should create first"); + } + return rpcTrackerEngine; + } + + public static synchronized RpcTrackerEngine createRpcTrackerEngine(URL url) { + if (rpcTrackerEngine == null) { + rpcTrackerEngine = rpcTrackerEngineFactory.createRpcTrackerEngine(url); + } + return rpcTrackerEngine; + } + + public static synchronized RpcTracker createRpcTracker(URL url) { + String protocol = url.getProtocol(); + RpcTracker rpcTracker = rpcTrackerMap.get(protocol); if (rpcTracker == null) { rpcTracker = rpcTrackerFactory.createRpcTracker(url); + if (rpcTracker == null) { + throw new IllegalStateException("rpcTracker should not be null here, url: " + url); + } + rpcTrackerMap.put(protocol, rpcTracker); } return rpcTracker; } - public static RpcTracker getRpcTracker() { + public static RpcTracker getRpcTracker(String protocol) { + RpcTracker rpcTracker = rpcTrackerMap.get(protocol); if (rpcTracker == null) { throw new IllegalStateException("rpcTracker should be create first!"); } @@ -37,6 +70,6 @@ public static RpcTracker getRpcTracker() { public static RpcTracker mockRpcTracker(String address, String application) { String urlStr = "zipkin://" + address + "?application=" + application + "&collector=http"; URL url = URL.valueOf(urlStr); - return create(url); + return createRpcTracker(url); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java index f8cd275b08e..ec4ac43482c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java @@ -1,18 +1,13 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; import com.github.kristofa.brave.ClientRequestInterceptor; public class BraveDubboClientRequestInterceptor implements DubboClientRequestInterceptor { private final ClientRequestInterceptor clientRequestInterceptor; - private final DubboRequestSpanNameProvider spanNameProvider; - - public BraveDubboClientRequestInterceptor(ClientRequestInterceptor clientRequestInterceptor, - DubboRequestSpanNameProvider spanNameProvider) { + public BraveDubboClientRequestInterceptor(ClientRequestInterceptor clientRequestInterceptor) { this.clientRequestInterceptor = clientRequestInterceptor; - this.spanNameProvider = spanNameProvider; } @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java new file mode 100644 index 00000000000..f7d9dd60c84 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.github.kristofa.brave.ServerRequestInterceptor; + +/** + * @author Xs + */ +public class BraveDubboServerRequestInterceptor implements DubboServerRequestInterceptor { + + private final ServerRequestInterceptor serverRequestInterceptor; + + public BraveDubboServerRequestInterceptor(ServerRequestInterceptor serverRequestInterceptor) { + this.serverRequestInterceptor = serverRequestInterceptor; + } + + @Override + public void handle(DubboServerRequestAdapter serverRequestAdapter) { + if (serverRequestAdapter.isTraceable()) { + serverRequestInterceptor.handle(serverRequestAdapter); + } + } + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java new file mode 100644 index 00000000000..d5fe2f8d7d4 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.github.kristofa.brave.ServerResponseInterceptor; + +/** + * @author Xs + */ +public class BraveDubboServerResponseInterceptor implements DubboServerResponseInterceptor { + + private final ServerResponseInterceptor serverResponseInterceptor; + + public BraveDubboServerResponseInterceptor(ServerResponseInterceptor serverResponseInterceptor) { + this.serverResponseInterceptor = serverResponseInterceptor; + } + + @Override + public void handle(DubboServerResponseAdapter serverResponseAdapter) { + if (serverResponseAdapter.isTraceable()) { + serverResponseInterceptor.handle(serverResponseAdapter); + } + } + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java index b945698a42b..ebacf191c6e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java @@ -8,13 +8,17 @@ public class BraveRpcTrackerEngine implements RpcTrackerEngine { private final Brave brave; - public BraveRpcTrackerEngine(URL url) { + BraveRpcTrackerEngine(URL url) { Brave.Builder builder = new Brave.Builder(url.getParameter("application", "demo")); builder.spanCollector(SpanCollectorFactory.create(url)); builder.traceSampler(SamplerFactory.create(url)); brave = builder.build(); } + public static BraveRpcTrackerEngine create(URL url) { + return new BraveRpcTrackerEngine(url); + } + @Override public Object clientRequestInterceptor() { return brave.clientRequestInterceptor(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java new file mode 100644 index 00000000000..dcfa7ac065b --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.RpcTrackerEngineFactory; + +/** + * @author Xs + */ +public class BraveRpcTrackerEngineFactory implements RpcTrackerEngineFactory { + + private volatile BraveRpcTrackerEngine braveRpcTrackerEngine; + + @Override + public RpcTrackerEngine createRpcTrackerEngine(URL url) { + if (braveRpcTrackerEngine == null) { + braveRpcTrackerEngine = BraveRpcTrackerEngine.create(url); + } + return braveRpcTrackerEngine; + } + + @Override + public RpcTrackerEngine getTrackerEngine() { + return braveRpcTrackerEngine; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index b4710b118b9..bff3430bb92 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -1,29 +1,25 @@ -//package com.alibaba.dubbo.tracker.zipkin; -// -//import com.alibaba.dubbo.common.URL; -//import com.alibaba.dubbo.tracker.RpcTracker; -//import com.alibaba.dubbo.tracker.RpcTrackerFactory; -// -///** -// * @author Xs -// */ -//public class BraveRpcTrackerFactory implements RpcTrackerFactory { -// -// private volatile BraveRpcTracker braveRpcTracker; -// -// @Override -// public RpcTracker createRpcTracker(URL url) { -// if (braveRpcTracker == null) { -// braveRpcTracker = BraveRpcTracker.create(url); -// } -// return braveRpcTracker; -// } -// -// @Override -// public RpcTracker getTracker() { -// if (braveRpcTracker == null) { -// throw new IllegalStateException("braveRpcTracker must not be null"); -// } -// return braveRpcTracker; -// } -//} +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.TrackerManager; +import com.alibaba.dubbo.tracker.zipkin.http.HttpRpcTracker; + +/** + * @author Xs + */ +public class BraveRpcTrackerFactory implements RpcTrackerFactory { + + @Override + public RpcTracker createRpcTracker(URL url) { + String protocol = url.getProtocol(); + RpcTracker rpcTracker = null; + if (protocol.equals("dubbo")) { + rpcTracker = new DubboRpcTracker((BraveRpcTrackerEngine) TrackerManager.getRpcTrackerEngine()); + } else if (protocol.equals("http") || protocol.equals("hessian")) { + rpcTracker = new HttpRpcTracker(); + } + return rpcTracker; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java deleted file mode 100644 index beb320c339c..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerRequestAdapter.java +++ /dev/null @@ -1,65 +0,0 @@ -//package com.alibaba.dubbo.tracker.zipkin; -// -//import com.alibaba.dubbo.tracker.RpcAttachment; -//import com.alibaba.dubbo.tracker.RpcRequest; -//import com.alibaba.dubbo.tracker.RpcRequestSpanNameProvider; -//import com.alibaba.dubbo.tracker.TrackerKeys; -//import com.github.kristofa.brave.KeyValueAnnotation; -//import com.github.kristofa.brave.ServerRequestAdapter; -//import com.github.kristofa.brave.SpanId; -//import com.github.kristofa.brave.TraceData; -// -//import java.util.Collection; -//import java.util.Collections; -// -//import static com.github.kristofa.brave.IdConversion.convertToLong; -// -//public class BraveServerRequestAdapter implements ServerRequestAdapter { -// -// private final RpcRequestSpanNameProvider spanNameProvider; -// -// private final RpcRequest rpcRequest; -// -// public BraveServerRequestAdapter(RpcRequest rpcRequest, RpcRequestSpanNameProvider spanNameProvider) { -// this.spanNameProvider = spanNameProvider; -// this.rpcRequest = rpcRequest; -// } -// -// @Override -// public TraceData getTraceData() { -// final String sampled = rpcRequest.getAttachment(RpcAttachment.Sampled.getName()); -// if (sampled != null) { -// if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { -// return TraceData.builder().sample(false).build(); -// } else { -// final String parentSpanId = rpcRequest.getAttachment(RpcAttachment.ParentSpanId.getName()); -// final String traceId = rpcRequest.getAttachment(RpcAttachment.TraceId.getName()); -// final String spanId = rpcRequest.getAttachment(RpcAttachment.SpanId.getName()); -// -// if (traceId != null && spanId != null) { -// SpanId span = getSpanId(traceId, spanId, parentSpanId); -// return TraceData.builder().sample(true).spanId(span).build(); -// } -// } -// } -// return TraceData.builder().build(); -// } -// -// @Override -// public String getSpanName() { -// return spanNameProvider.spanName(rpcRequest); -// } -// -// @Override -// public Collection requestAnnotations() { -// KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, rpcRequest.providerAddress()); -// return Collections.singletonList(annotation); -// } -// -// private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { -// return SpanId.builder() -// .traceId(convertToLong(traceId)) -// .spanId(convertToLong(spanId)) -// .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); -// } -//} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java deleted file mode 100644 index 4bca89a1be9..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveServerResponseAdapter.java +++ /dev/null @@ -1,29 +0,0 @@ -//package com.alibaba.dubbo.tracker.zipkin; -// -//import com.alibaba.dubbo.tracker.RpcResponse; -//import com.alibaba.dubbo.tracker.TrackerKeys; -//import com.github.kristofa.brave.KeyValueAnnotation; -//import com.github.kristofa.brave.ServerResponseAdapter; -// -//import java.util.Collection; -//import java.util.Collections; -// -//public class BraveServerResponseAdapter implements ServerResponseAdapter { -// -// private final RpcResponse rpcResponse; -// -// public BraveServerResponseAdapter(RpcResponse rpcResponse) { -// this.rpcResponse = rpcResponse; -// } -// -// @Override -// public Collection responseAnnotations() { -// KeyValueAnnotation statusAnnotation; -// if (rpcResponse.returnSuccessfully()) { -// statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); -// } else { -// statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, rpcResponse.exceptionMessage()); -// } -// return Collections.singletonList(statusAnnotation); -// } -//} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java index 0c936d4f4aa..ce71582566e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java @@ -1,30 +1,53 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.alibaba.dubbo.tracker.*; public class DubboRpcTracker implements RpcTracker { + private final ClientRequestInterceptor clientRequestInterceptor; + + private final ClientResponseInterceptor clientResponseInterceptor; + + private final ServerRequestInterceptor serverRequestInterceptor; + + private final ServerResponseInterceptor serverResponseInterceptor; + + private final BraveRpcTrackerEngine trackerEngine; + + public DubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { + this.trackerEngine = trackerEngine; + this.clientRequestInterceptor = new BraveDubboClientRequestInterceptor( + (com.github.kristofa.brave.ClientRequestInterceptor) trackerEngine.clientRequestInterceptor()); + this.clientResponseInterceptor = new BraveDubboClientResponseInterceptor( + (com.github.kristofa.brave.ClientResponseInterceptor) trackerEngine.clientResponseInterceptor()); + this.serverRequestInterceptor = new BraveDubboServerRequestInterceptor( + (com.github.kristofa.brave.ServerRequestInterceptor) trackerEngine.serverRequestInterceptor()); + this.serverResponseInterceptor = new BraveDubboServerResponseInterceptor( + (com.github.kristofa.brave.ServerResponseInterceptor) trackerEngine.serverResponseInterceptor()); + } + @Override public ClientRequestInterceptor clientRequestInterceptor() { - return null; + return clientRequestInterceptor; } @Override public ClientResponseInterceptor clientResponseInterceptor() { - return null; + return clientResponseInterceptor; + } + + @Override + public ServerRequestInterceptor serverRequestInterceptor() { + return serverRequestInterceptor; } @Override - public ServletFilter servletFilter() { - return null; + public ServerResponseInterceptor serverResponseInterceptor() { + return serverResponseInterceptor; } @Override public RpcTrackerEngine trackerEngine() { - return null; + return trackerEngine; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java new file mode 100644 index 00000000000..672969c7971 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java @@ -0,0 +1,72 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.ServerRequestAdapter; +import com.github.kristofa.brave.SpanId; +import com.github.kristofa.brave.TraceData; + +import java.util.Collection; +import java.util.Collections; + +import static com.github.kristofa.brave.IdConversion.convertToLong; + +/** + * @author Xs + */ +public class DubboServerRequestAdapter implements ServerRequestAdapter { + + private final DubboRequest request; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public DubboServerRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { + this.request = request; + this.spanNameProvider = spanNameProvider; + } + + public boolean isTraceable() { + return request.isTraceable(); + } + + @Override + public TraceData getTraceData() { + final String sampled = request.getAttachment(RpcAttachment.Sampled.getName()); + if (sampled != null) { + if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { + return TraceData.builder().sample(false).build(); + } else { + final String parentSpanId = request.getAttachment(RpcAttachment.ParentSpanId.getName()); + final String traceId = request.getAttachment(RpcAttachment.TraceId.getName()); + final String spanId = request.getAttachment(RpcAttachment.SpanId.getName()); + + if (traceId != null && spanId != null) { + SpanId span = getSpanId(traceId, spanId, parentSpanId); + return TraceData.builder().sample(true).spanId(span).build(); + } + } + } + return TraceData.builder().build(); + } + + @Override + public String getSpanName() { + return spanNameProvider.spanName(); + } + + @Override + public Collection requestAnnotations() { + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.providerAddress()); + return Collections.singletonList(annotation); + } + + private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { + return SpanId.builder() + .traceId(convertToLong(traceId)) + .spanId(convertToLong(spanId)) + .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java new file mode 100644 index 00000000000..13ce478e8a9 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java @@ -0,0 +1,12 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ServerRequestInterceptor; + +/** + * @author Xs + */ +public interface DubboServerRequestInterceptor extends ServerRequestInterceptor { + + void handle(DubboServerRequestAdapter serverRequestAdapter); + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java new file mode 100644 index 00000000000..7e42bad16f1 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java @@ -0,0 +1,37 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.TrackerKeys; +import com.github.kristofa.brave.KeyValueAnnotation; +import com.github.kristofa.brave.ServerResponseAdapter; + +import java.util.Collection; +import java.util.Collections; + +/** + * @author Xs + */ +public class DubboServerResponseAdapter implements ServerResponseAdapter { + + private final DubboResponse response; + + public DubboServerResponseAdapter(DubboResponse response) { + this.response = response; + } + + public boolean isTraceable() { + return response.isTraceable(); + } + + @Override + public Collection responseAnnotations() { + KeyValueAnnotation statusAnnotation; + if (response.returnSuccessfully()) { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); + } else { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); + } + return Collections.singletonList(statusAnnotation); + } + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java new file mode 100644 index 00000000000..f303b16d958 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java @@ -0,0 +1,11 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.ServerResponseInterceptor; + +/** + * @author Xs + */ +public interface DubboServerResponseInterceptor extends ServerResponseInterceptor { + + void handle(DubboServerResponseAdapter serverResponseAdapter); +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java index 1fdc0d6396d..c10c288127e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java @@ -1,12 +1,8 @@ package com.alibaba.dubbo.tracker.zipkin.http; -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.alibaba.dubbo.tracker.*; -public class HttpRpcTracker implements RpcTracker{ +public class HttpRpcTracker implements RpcTracker { @Override public ClientRequestInterceptor clientRequestInterceptor() { @@ -19,7 +15,12 @@ public ClientResponseInterceptor clientResponseInterceptor() { } @Override - public ServletFilter servletFilter() { + public ServerRequestInterceptor serverRequestInterceptor() { + return null; + } + + @Override + public ServerResponseInterceptor serverResponseInterceptor() { return null; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory new file mode 100644 index 00000000000..7c3398aefc3 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngineFactory \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java index 2701c002aa5..ecdbde28e9f 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java @@ -2,13 +2,23 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.TrackerManager; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; public class ExtensionTest { + private static RpcTrackerEngine trackerEngine; + + @BeforeClass + public static void before(){ + URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); + trackerEngine = TrackerManager.createRpcTrackerEngine(url); + } + @Test public void test_rpc_factory() { RpcTrackerFactory factory = TrackerManager.getTrackerFactory(); @@ -18,9 +28,15 @@ public void test_rpc_factory() { @Test public void test_create_tracker() { - RpcTrackerFactory factory = TrackerManager.getTrackerFactory(); + URL url = URL.valueOf("dubbo://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); + RpcTracker rpcTracker = TrackerManager.createRpcTracker(url); + RpcTracker rpcTracker1 = TrackerManager.createRpcTracker(url); + Assert.assertEquals(rpcTracker, rpcTracker1); + } + + @Test + public void test_create_engine(){ URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - RpcTracker rpcTracker = TrackerManager.create(url); - Assert.assertEquals(rpcTracker, TrackerManager.getRpcTracker()); + RpcTrackerEngine trackerEngine = TrackerManager.getRpcTrackerEngine(); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory new file mode 100644 index 00000000000..7c3398aefc3 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngineFactory \ No newline at end of file From 54b5cb708b9d49e65b1491ad9b3f85dc2a7582ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Thu, 19 Jan 2017 20:04:48 +0800 Subject: [PATCH 14/69] rpc tracker component --- .../registry/common/domain/LoadBalance.java | 28 +- .../registry/common/domain/Registry.java | 22 +- .../registry/common/route/RouteRule.java | 291 ++++++++---------- .../loadbalance/RandomLoadBalance.java | 56 ++-- .../cluster/router/MockInvokersSelector.java | 112 +++---- .../router/condition/ConditionRouter.java | 46 ++- .../support/AbstractClusterInvoker.java | 7 +- .../support/FailoverClusterInvoker.java | 52 ++-- .../support/MergeableClusterInvoker.java | 174 +++++------ .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 32 +- .../integration/RegistryDirectory.java | 291 +++++++++--------- .../integration/RegistryProtocol.java | 261 ++++++++-------- .../registry/support/FailbackRegistry.java | 52 ++-- .../dubbo/remoting/exchange/Interceptor.java | 2 + .../header/HeaderExchangeClientV2.java | 5 + .../header/HeaderExchangeHandlerV2.java | 73 ++++- .../alibaba/dubbo/tracker/DubboResponse.java | 8 +- .../dubbo/tracker/HttpTrackerComponent.java | 8 - .../dubbo/tracker/RpcTrackerEngine.java | 5 + ...kerManager.java => RpcTrackerManager.java} | 2 +- .../filter/ClientRpcTrackerFilter.java | 9 - .../filter/ServerRpcTrackerFilter.java | 9 - .../tracker/zipkin/BraveRpcTrackerEngine.java | 15 +- .../zipkin/BraveRpcTrackerFactory.java | 4 +- ...ubboClientRequestResponseInterceptor.java} | 8 +- .../dubbo/tracker/zipkin/DubboRpcTracker.java | 13 +- ...DubboServerRequestResponseInterceptor.java | 35 +++ .../zipkin/DubboServerResponseAdapter.java | 2 +- .../zipkin/http/HttpClientRequestAdapter.java | 3 + .../http/HttpClientResponseInterceptor.java | 3 + .../tracker/zipkin/http/HttpRpcTracker.java | 3 + .../tracker/zipkin/test/ExtensionTest.java | 14 +- 33 files changed, 836 insertions(+), 811 deletions(-) delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{TrackerManager.java => RpcTrackerManager.java} (98%) delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{DubboRequestResponseInterceptor.java => DubboClientRequestResponseInterceptor.java} (76%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java index 1d83f89e405..53c171face2 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/LoadBalance.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server-1.1.0-SNAPSHOT - * + *

* File Created at 2010-10-21 * $Id: LoadBalance.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -20,19 +20,19 @@ * @author rain.chenjr * */ -public class LoadBalance extends Entity{ +public class LoadBalance extends Entity { private static final long serialVersionUID = -6050324375352581440L; - + public static final String ALL_METHOD = "*"; - private String service; /* 服务名称 */ - - private String method; /* 方法名称 */ - - private String strategy; /*负载均衡策略*/ - - private String username; /*用户名*/ + private String service; /* 服务名称 */ + + private String method; /* 方法名称 */ + + private String strategy; /*负载均衡策略*/ + + private String username; /*用户名*/ public LoadBalance() { } @@ -40,7 +40,7 @@ public LoadBalance() { public LoadBalance(Long id) { super(id); } - + public String getService() { return service; } @@ -73,5 +73,5 @@ public void setUsername(String username) { this.username = username; } - + } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java index 4c00f8eb4d1..601d3f050d8 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/domain/Registry.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry-1.1.0-SNAPSHOT - * + *

* File Created at 2010-4-9 * $Id: Registry.java 181192 2012-06-21 05:05:47Z tony.chenl $ - * + *

* Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -19,7 +19,7 @@ /** * Registry - * + * * @author william.liangf */ public class Registry extends Entity { @@ -27,22 +27,22 @@ public class Registry extends Entity { private static final long serialVersionUID = -8866645978415551309L; private String registry;/* 注册中心地址 */ - + private String url; - + private int connections = 0;/*注册中心连接数*/ private Date expired; /*过期时间*/ - + private long alived; - + public Registry() { } public Registry(Long id) { super(id); } - + public Registry(String registryAddress, String consoleUrl, int aliveSeconds) { this.registry = registryAddress; this.url = consoleUrl; @@ -81,12 +81,12 @@ public void setAlived(long aliveSeconds) { this.alived = aliveSeconds; } - + public int getConnections() { return connections; } - + public void setConnections(int connections) { this.connections = connections; } diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java index 6f2732e7d98..12be17acfa5 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/route/RouteRule.java @@ -1,12 +1,12 @@ /** * Project: dubbo.registry.server - * + *

* File Created at Oct 18, 2010 * $Id: RouteRule.java 182348 2012-06-27 09:16:58Z tony.chenl $ - * + *

* Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. - * + *

* This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in @@ -15,19 +15,15 @@ */ package com.alibaba.dubbo.registry.common.route; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.registry.common.domain.Route; + import java.text.ParseException; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.registry.common.domain.Route; - /** * Rule分成两部分,When条件和Then条件。
@@ -37,63 +33,64 @@ * 使用条件对样本进行的匹配的过程称为“过滤”(或称为“筛选”)(Filter)。 * 使用When条件过滤和使用Then条件过滤的样本,不需要是相同的集合。如在Dubbo中,分别对应的是Consumer和Provider。 * 对于RouteRule(路由规则)含义即,符合When条件的Consumer,则对Provider进行Then过滤,出来的Provide即是提供给这个Consumer的Provider。
- * + * * Rule的字符串格式如下: * key1 = value11,value12 & key2 = value21 & key2 != value22 => key3 = value3 & key4 = value41,vlaue42 & key5 !=value51 * 。 * =>之前的称为When条件,是KV对;之后是Then条件,是KV对。KV的Value可以有多个值。

- * + * * 值对象,线程安全。 - * + * * @author william.liangf * @author ding.lid */ public class RouteRule { public static class MatchPair { - Set matches = new HashSet(); + Set matches = new HashSet(); Set unmatches = new HashSet(); public MatchPair() { } - + public MatchPair(Set matches, Set unmatches) { - if(matches == null || unmatches == null) { + if (matches == null || unmatches == null) { throw new IllegalArgumentException("argument of MatchPair is null!"); } - + this.matches = matches; this.unmatches = unmatches; } - + public Set getMatches() { return matches; } - + public Set getUnmatches() { return unmatches; } - + public MatchPair copy() { MatchPair ret = new MatchPair(); ret.matches.addAll(matches); ret.unmatches.addAll(unmatches); return ret; } - + private volatile boolean freezed = false; + void freeze() { - if(freezed) return; + if (freezed) return; synchronized (this) { - if(freezed) return; + if (freezed) return; matches = Collections.unmodifiableSet(matches); unmatches = Collections.unmodifiableSet(unmatches); } } - + public boolean containeValue(String value) { return matches.contains(value) || unmatches.contains(value); } - + /** * 给定的值是否通过该{@link MatchPair}匹配。

* 返回{@code false},如果 @@ -104,16 +101,14 @@ public boolean containeValue(String value) { * otherwise返回true。 */ public boolean pass(String sample) { - if(unmatches.contains(sample)) return false; - if(matches.isEmpty()) return true; - return matches.contains(sample); + return !unmatches.contains(sample) && (matches.isEmpty() || matches.contains(sample)); } - + @Override public String toString() { return String.format("{matches=%s,unmatches=%s}", matches.toString(), unmatches.toString()); } - + // 用Eclipse自动生成 @Override public int hashCode() { @@ -152,15 +147,15 @@ public boolean equals(Object obj) { final Map thenCondition; private static Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)"); - + private static Pattern CONDITION_SEPERATOR = Pattern.compile("(.*)=>(.*)"); - + public static Map parseRule(String rule) throws ParseException { - Map condition = new HashMap(); - if(StringUtils.isBlank(rule)) { + Map condition = new HashMap(); + if (StringUtils.isBlank(rule)) { return condition; - } + } // 匹配或不匹配Key-Value对 MatchPair pair = null; // 多个Value值 @@ -222,27 +217,27 @@ else if (",".equals(separator)) { // 如果为逗号表示 } return condition; } - + // FIXME 集合都要加上unmodified的Wrapper,避免构造后的对象被修改 private RouteRule(Map when, Map then) { - for(Map.Entry entry : when.entrySet()) { + for (Map.Entry entry : when.entrySet()) { entry.getValue().freeze(); } - for(Map.Entry entry : then.entrySet()) { + for (Map.Entry entry : then.entrySet()) { entry.getValue().freeze(); } - + // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件 this.whenCondition = when; this.thenCondition = then; } @SuppressWarnings("unchecked") - static RouteRule EMPTY = new RouteRule(Collections.EMPTY_MAP, Collections.EMPTY_MAP); - + static RouteRule EMPTY = new RouteRule(Collections.EMPTY_MAP, Collections.EMPTY_MAP); + /** * 把字符串形式的RouteRule的解析成对象。 - * + * * @throws ParseException RouteRule字符串格式不对了。以下输入的情况,RouteRule都是非法的。 *

  • 输入是null。 *
  • 输入是空串,或是空白串。 @@ -251,39 +246,39 @@ private RouteRule(Map when, Map then) { *
*/ public static RouteRule parse(Route route) throws ParseException { - if(route == null) + if (route == null) throw new ParseException("null route!", 0); - - if(route.getMatchRule() == null && route.getFilterRule() == null) { + + if (route.getMatchRule() == null && route.getFilterRule() == null) { return parse(route.getRule()); } - - return parse(route == null ? null : route.getMatchRule(), route == null ? null : route.getFilterRule()); + + return parse(route.getMatchRule(), route.getFilterRule()); } - + public static RouteRule parse(String whenRule, String thenRule) throws ParseException { - /*if (whenRule == null || whenRule.trim().length() == 0) { + /*if (whenRule == null || whenRule.trim().length() == 0) { throw new ParseException("Illegal route rule without when express", 0); }*/ - if (thenRule == null || thenRule.trim().length() == 0) { - throw new ParseException("Illegal route rule without then express", 0); - } - Map when = parseRule(whenRule.trim()); + if (thenRule == null || thenRule.trim().length() == 0) { + throw new ParseException("Illegal route rule without then express", 0); + } + Map when = parseRule(whenRule.trim()); Map then = parseRule(thenRule.trim()); return new RouteRule(when, then); } - + public static RouteRule parse(String rule) throws ParseException { - if(StringUtils.isBlank(rule)) { + if (StringUtils.isBlank(rule)) { throw new ParseException("Illegal blank route rule", 0); } - + final Matcher matcher = CONDITION_SEPERATOR.matcher(rule); - if(!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); - + if (!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); + return parse(matcher.group(1), matcher.group(2)); } - + /** * @see #parse(String) * @throws RuntimeException 解析出错时,Wrap了{@link #parse(String)}方法的抛出的{@link ParseException}的异常。 @@ -292,150 +287,149 @@ public static RouteRule parseQuitely(Route route) { try { return parse(route); } catch (ParseException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } } - + private static Pattern VALUE_LIST_SEPARATOR = Pattern.compile("\\s*,\\s*"); - + static Map parseNameAndValueListString2Condition(Map params, Map notParams) { Map condition = new HashMap(); - - for(Entry entry : params.entrySet()) { + + for (Entry entry : params.entrySet()) { String valueListString = entry.getValue(); - if(StringUtils.isBlank(valueListString)) { + if (StringUtils.isBlank(valueListString)) { continue; } String[] list = VALUE_LIST_SEPARATOR.split(valueListString); Set set = new HashSet(); - for(String item : list) { - if(StringUtils.isBlank(item)) { + for (String item : list) { + if (StringUtils.isBlank(item)) { continue; } set.add(item.trim()); } - if(set.isEmpty()) { + if (set.isEmpty()) { continue; } - + String key = entry.getKey(); MatchPair matchPair = condition.get(key); - if(null == matchPair) { + if (null == matchPair) { matchPair = new MatchPair(); condition.put(key, matchPair); } - + matchPair.matches = set; } - for(Entry entry : notParams.entrySet()) { + for (Entry entry : notParams.entrySet()) { String valueListString = entry.getValue(); - if(StringUtils.isBlank(valueListString)) { + if (StringUtils.isBlank(valueListString)) { continue; } String[] list = VALUE_LIST_SEPARATOR.split(valueListString); Set set = new HashSet(); - for(String item : list) { - if(StringUtils.isBlank(item)) { + for (String item : list) { + if (StringUtils.isBlank(item)) { continue; } set.add(item.trim()); } - if(set.isEmpty()) { + if (set.isEmpty()) { continue; } - + String key = entry.getKey(); MatchPair matchPair = condition.get(key); - if(null == matchPair) { + if (null == matchPair) { matchPair = new MatchPair(); condition.put(key, matchPair); } - + matchPair.unmatches = set; } - + return condition; } - + public static RouteRule createFromNameAndValueListString(Map whenParams, Map notWhenParams, Map thenParams, Map notThenParams) { Map when = parseNameAndValueListString2Condition(whenParams, notWhenParams); Map then = parseNameAndValueListString2Condition(thenParams, notThenParams); - + return new RouteRule(when, then); } - + public static RouteRule createFromCondition(Map whenCondition, Map thenCondition) { return new RouteRule(whenCondition, thenCondition); } - + public static RouteRule copyWithRemove(RouteRule copy, Set whenParams, Set thenParams) { Map when = new HashMap(); - for(Entry entry : copy.getWhenCondition().entrySet()) { - if(whenParams == null || !whenParams.contains(entry.getKey())) { + for (Entry entry : copy.getWhenCondition().entrySet()) { + if (whenParams == null || !whenParams.contains(entry.getKey())) { when.put(entry.getKey(), entry.getValue()); } } - + Map then = new HashMap(); - for(Entry entry : copy.getThenCondition().entrySet()) { - if(thenParams ==null || !thenParams.contains(entry.getKey())) { + for (Entry entry : copy.getThenCondition().entrySet()) { + if (thenParams == null || !thenParams.contains(entry.getKey())) { then.put(entry.getKey(), entry.getValue()); } } - + return new RouteRule(when, then); } - + /** * 使用新的条件值来替换。 - * + * * @param copy 替换的Base * @param whenCondition 要替换的whenCondition,如果Base没有项目,则直接插入。 * @param thenCondition 要替换的thenCondition,如果Base没有项目,则直接插入。 * @return 替换后的RouteRule */ public static RouteRule copyWithReplace(RouteRule copy, Map whenCondition, Map thenCondition) { - if(null == copy) { + if (null == copy) { throw new NullPointerException("Argument copy is null!"); } - + Map when = new HashMap(); when.putAll(copy.getWhenCondition()); - if(whenCondition != null) { + if (whenCondition != null) { when.putAll(whenCondition); } - + Map then = new HashMap(); then.putAll(copy.getThenCondition()); - if(thenCondition != null) { + if (thenCondition != null) { then.putAll(thenCondition); } - + return new RouteRule(when, then); } - + // TODO 目前ToString出来的列表是乱序的,是否要排序? static void join(StringBuilder sb, Set valueSet) { boolean isFirst = true; - for(String s : valueSet) { - if(isFirst) { - isFirst = false; - } - else { - sb.append(","); - } - - sb.append(s); + for (String s : valueSet) { + if (isFirst) { + isFirst = false; + } else { + sb.append(","); + } + + sb.append(s); } } - + /** * 样本是否通过条件。 *

* 如果样本的KV中,存在Key有对应的MatchPair,且Value不通过MatchPair里,返回{@code false}; * 否则返回{@code true}。 - * + * * @see MatchPair#pass(String) */ public static boolean matchCondition(Map sample, @@ -450,66 +444,59 @@ public static boolean matchCondition(Map sample, } return true; } - - + + // FIXME 去掉这样的方法调用 public static String join(Set valueSet) { StringBuilder sb = new StringBuilder(128); join(sb, valueSet); return sb.toString(); } - + // TODO 目前Condition的多个Key是乱序的,是否要排序? public static void contidionToString(StringBuilder sb, Map condition) { boolean isFirst = true; - for(Entry entry: condition.entrySet()) { + for (Entry entry : condition.entrySet()) { String keyName = entry.getKey(); MatchPair p = entry.getValue(); - + @SuppressWarnings("unchecked") Set[] setArray = new Set[]{p.matches, p.unmatches}; String[] opArray = {" = ", " != "}; - - for(int i = 0; i < setArray.length; ++i) { - if(setArray[i].isEmpty()) { + + for (int i = 0; i < setArray.length; ++i) { + if (setArray[i].isEmpty()) { continue; } - if(isFirst) { + if (isFirst) { isFirst = false; - } - else { + } else { sb.append(" & "); } - + sb.append(keyName); sb.append(opArray[i]); join(sb, setArray[i]); } } } - + public boolean isWhenContainValue(String key, String value) { MatchPair matchPair = whenCondition.get(key); - if(null == matchPair) { - return false; - } - - return matchPair.containeValue(value); + return null != matchPair && matchPair.containeValue(value); + } - + public boolean isThenContainValue(String key, String value) { MatchPair matchPair = thenCondition.get(key); - if(null == matchPair) { - return false; - } - - return matchPair.containeValue(value); + return null != matchPair && matchPair.containeValue(value); + } - + public boolean isContainValue(String key, String value) { return isWhenContainValue(key, value) || isThenContainValue(key, value); } - + public Map getWhenCondition() { return whenCondition; } @@ -517,25 +504,25 @@ public Map getWhenCondition() { public Map getThenCondition() { return thenCondition; } - + public String getWhenConditionString() { - StringBuilder sb = new StringBuilder(512); + StringBuilder sb = new StringBuilder(512); contidionToString(sb, whenCondition); - return sb.toString(); + return sb.toString(); } public String getThenConditionString() { - StringBuilder sb = new StringBuilder(512); + StringBuilder sb = new StringBuilder(512); contidionToString(sb, thenCondition); - return sb.toString(); + return sb.toString(); } private volatile String tostring = null; - + @Override public String toString() { - if(tostring != null) - return tostring; + if (tostring != null) + return tostring; StringBuilder sb = new StringBuilder(512); contidionToString(sb, whenCondition); sb.append(" => "); @@ -548,8 +535,8 @@ public String toString() { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((thenCondition == null) ? 0 : thenCondition.hashCode()); - result = prime * result + ((whenCondition == null) ? 0 : whenCondition.hashCode()); + result = prime * result + (thenCondition.hashCode()); + result = prime * result + (whenCondition.hashCode()); return result; } @@ -563,15 +550,9 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; RouteRule other = (RouteRule) obj; - if (thenCondition == null) { - if (other.thenCondition != null) - return false; - } else if (!thenCondition.equals(other.thenCondition)) + if (!thenCondition.equals(other.thenCondition)) return false; - if (whenCondition == null) { - if (other.whenCondition != null) - return false; - } else if (!whenCondition.equals(other.whenCondition)) + if (!whenCondition.equals(other.whenCondition)) return false; return true; } diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java index de5002c489a..0a058c41417 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java @@ -1,26 +1,26 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.cluster.loadbalance; -import java.util.List; -import java.util.Random; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; + +import java.util.List; +import java.util.Random; /** * random load balance. @@ -28,14 +28,14 @@ * @author qianlei * @author william.liangf */ -public class RandomLoadBalance extends AbstractLoadBalance { +public class RandomLoadBalance extends AbstractLoadBalance { public static final String NAME = "random"; private final Random random = new Random(); protected Invoker doSelect(List> invokers, URL url, Invocation invocation) { - int length = invokers.size(); // 总个数 + int length = invokers.size(); // 总个数 int totalWeight = 0; // 总权重 boolean sameWeight = true; // 权重是否都一样 for (int i = 0; i < length; i++) { @@ -46,19 +46,19 @@ protected Invoker doSelect(List> invokers, URL url, Invocation sameWeight = false; // 计算所有权重是否一样 } } - if (totalWeight > 0 && ! sameWeight) { + if (totalWeight > 0 && !sameWeight) { // 如果权重不相同且权重大于0则按总权重数随机 int offset = random.nextInt(totalWeight); // 并确定随机值落在哪个片断上 - for (int i = 0; i < length; i++) { - offset -= getWeight(invokers.get(i), invocation); + for (Invoker invoker : invokers) { + offset -= getWeight(invoker, invocation); if (offset < 0) { - return invokers.get(i); + return invoker; } } } // 如果权重相同或权重为0则均等随机 return invokers.get(random.nextInt(length)); - } + } } \ No newline at end of file diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/MockInvokersSelector.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/MockInvokersSelector.java index 8ec3a2b40cd..37158b044cb 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/MockInvokersSelector.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/MockInvokersSelector.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.rpc.cluster.router; -import java.util.ArrayList; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; @@ -25,65 +22,68 @@ import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Router; +import java.util.ArrayList; +import java.util.List; + /** * mock invoker选择器 - * @author chao.liuc * + * @author chao.liuc */ public class MockInvokersSelector implements Router { - public List> route(final List> invokers, - URL url, final Invocation invocation) throws RpcException { - if (invocation.getAttachments() == null) { - return getNormalInvokers(invokers); - } else { - String value = invocation.getAttachments().get(Constants.INVOCATION_NEED_MOCK); - if (value == null) - return getNormalInvokers(invokers); - else if (Boolean.TRUE.toString().equalsIgnoreCase(value)){ - return getMockedInvokers(invokers); - } - } - return invokers; - } - - private List> getMockedInvokers(final List> invokers) { - if (! hasMockProviders(invokers)){ - return null; - } - List> sInvokers = new ArrayList>(1); - for (Invoker invoker : invokers){ - if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)){ - sInvokers.add(invoker); - } - } - return sInvokers; - } - - private List> getNormalInvokers(final List> invokers){ - if (! hasMockProviders(invokers)){ - return invokers; - } else { - List> sInvokers = new ArrayList>(invokers.size()); - for (Invoker invoker : invokers){ - if (! invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)){ - sInvokers.add(invoker); - } - } - return sInvokers; - } - } - - private boolean hasMockProviders(final List> invokers){ - boolean hasMockProvider = false; - for (Invoker invoker : invokers){ - if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)){ - hasMockProvider = true; - break; - } - } - return hasMockProvider; - } + public List> route(final List> invokers, + URL url, final Invocation invocation) throws RpcException { + if (invocation.getAttachments() == null) { + return getNormalInvokers(invokers); + } else { + String value = invocation.getAttachments().get(Constants.INVOCATION_NEED_MOCK); + if (value == null) + return getNormalInvokers(invokers); + else if (Boolean.TRUE.toString().equalsIgnoreCase(value)) { + return getMockedInvokers(invokers); + } + } + return invokers; + } + + private List> getMockedInvokers(final List> invokers) { + if (!hasMockProviders(invokers)) { + return null; + } + List> sInvokers = new ArrayList>(1); + for (Invoker invoker : invokers) { + if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + sInvokers.add(invoker); + } + } + return sInvokers; + } + + private List> getNormalInvokers(final List> invokers) { + if (!hasMockProviders(invokers)) { + return invokers; + } else { + List> sInvokers = new ArrayList>(invokers.size()); + for (Invoker invoker : invokers) { + if (!invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + sInvokers.add(invoker); + } + } + return sInvokers; + } + } + + private boolean hasMockProviders(final List> invokers) { + boolean hasMockProvider = false; + for (Invoker invoker : invokers) { + if (invoker.getUrl().getProtocol().equals(Constants.MOCK_PROTOCOL)) { + hasMockProvider = true; + break; + } + } + return hasMockProvider; + } public URL getUrl() { return null; diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java index d9bca59ef20..eac784f8e23 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -15,16 +15,6 @@ */ package com.alibaba.dubbo.rpc.cluster.router.condition; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -37,23 +27,28 @@ import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Router; +import java.text.ParseException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * ConditionRouter - * + * * @author william.liangf */ public class ConditionRouter implements Router, Comparable { - + private static final Logger logger = LoggerFactory.getLogger(ConditionRouter.class); private final URL url; - + private final int priority; private final boolean force; private final Map whenCondition; - + private final Map thenCondition; public ConditionRouter(URL url) { @@ -85,12 +80,12 @@ public List> route(List> invokers, URL url, Invocation return invokers; } try { - if (! matchWhen(url)) { + if (!matchWhen(url)) { return invokers; } List> result = new ArrayList>(); if (thenCondition == null) { - logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); + logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker invoker : invokers) { @@ -101,8 +96,8 @@ public List> route(List> invokers, URL url, Invocation if (result.size() > 0) { return result; } else if (force) { - logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); - return result; + logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); + return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); @@ -129,27 +124,27 @@ public boolean matchWhen(URL url) { public boolean matchThen(URL url, URL param) { return thenCondition != null && matchCondition(thenCondition, url, param); } - + private boolean matchCondition(Map condition, URL url, URL param) { Map sample = url.toMap(); for (Map.Entry entry : sample.entrySet()) { String key = entry.getKey(); MatchPair pair = condition.get(key); - if (pair != null && ! pair.isMatch(entry.getValue(), param)) { + if (pair != null && !pair.isMatch(entry.getValue(), param)) { return false; } } return true; } - + private static Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)"); - + private static Map parseRule(String rule) throws ParseException { Map condition = new HashMap(); - if(StringUtils.isBlank(rule)) { + if (StringUtils.isBlank(rule)) { return condition; - } + } // 匹配或不匹配Key-Value对 MatchPair pair = null; // 多个Value值 @@ -214,9 +209,10 @@ else if (",".equals(separator)) { // 如果为逗号表示 private static final class MatchPair { final Set matches = new HashSet(); final Set mismatches = new HashSet(); + public boolean isMatch(String value, URL param) { for (String match : matches) { - if (! UrlUtils.isMatchGlobPattern(match, value, param)) { + if (!UrlUtils.isMatchGlobPattern(match, value, param)) { return false; } } diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index c3017c7ed24..c19806f7340 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -90,8 +90,7 @@ public void destroy() { * a)先lb选择,如果在selected列表中 或者 不可用且做检验时,进入下一步(重选),否则直接返回
* b)重选验证规则:selected > available .保证重选出的结果尽量不在select中,并且是可用的 * - * @param availablecheck 如果设置true,在选择的时候先选invoker.available == true - * @param selected 已选过的invoker.注意:输入保证不重复 + * @param selected 已选过的invoker.注意:输入保证不重复 */ protected Invoker select(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { if (invokers == null || invokers.size() == 0) @@ -228,7 +227,6 @@ public Result invoke(final Invocation invocation) throws RpcException { } protected void checkWheatherDestoried() { - if (destroyed) { throw new RpcException("Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() @@ -257,7 +255,6 @@ protected abstract Result doInvoke(Invocation invocation, List> invok LoadBalance loadbalance) throws RpcException; protected List> list(Invocation invocation) throws RpcException { - List> invokers = directory.list(invocation); - return invokers; + return directory.list(invocation); } } \ No newline at end of file diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java index 71c7f283283..bc7423acb77 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java @@ -15,29 +15,25 @@ */ package com.alibaba.dubbo.rpc.cluster.support; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * 失败转移,当出现失败,重试其它服务器,通常用于读操作,但重试会带来更长延迟。 - * + *

* Failover - * + * * @author william.liangf * @author chao.liuc */ @@ -49,10 +45,10 @@ public FailoverClusterInvoker(Directory directory) { super(directory); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { - List> copyinvokers = invokers; - checkInvokers(copyinvokers, invocation); + List> copyinvokers = invokers; + checkInvokers(copyinvokers, invocation); int len = getUrl().getMethodParameter(invocation.getMethodName(), Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1; if (len <= 0) { len = 1; @@ -62,24 +58,24 @@ public Result doInvoke(Invocation invocation, final List> invokers, L List> invoked = new ArrayList>(copyinvokers.size()); // invoked invokers. Set providers = new HashSet(len); for (int i = 0; i < len; i++) { - //重试时,进行重新选择,避免重试时invoker列表已发生变化. - //注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变 - if (i > 0) { - checkWheatherDestoried(); - copyinvokers = list(invocation); - //重新检查一下 - checkInvokers(copyinvokers, invocation); - } + //重试时,进行重新选择,避免重试时invoker列表已发生变化. + //注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变 + if (i > 0) { + checkWheatherDestoried(); + copyinvokers = list(invocation); + //重新检查一下 + checkInvokers(copyinvokers, invocation); + } Invoker invoker = select(loadbalance, invocation, copyinvokers, invoked); invoked.add(invoker); - RpcContext.getContext().setInvokers((List)invoked); + RpcContext.getContext().setInvokers((List) invoked); try { Result result = invoker.invoke(invocation); if (le != null && logger.isWarnEnabled()) { logger.warn("Although retry the method " + invocation.getMethodName() + " in the service " + getInterface().getName() + " was successful by the provider " + invoker.getUrl().getAddress() - + ", but there have been failed providers " + providers + + ", but there have been failed providers " + providers + " (" + providers.size() + "/" + copyinvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() @@ -99,9 +95,9 @@ public Result doInvoke(Invocation invocation, final List> invokers, L } } throw new RpcException(le != null ? le.getCode() : 0, "Failed to invoke the method " - + invocation.getMethodName() + " in the service " + getInterface().getName() - + ". Tried " + len + " times of the providers " + providers - + " (" + providers.size() + "/" + copyinvokers.size() + + invocation.getMethodName() + " in the service " + getInterface().getName() + + ". Tried " + len + " times of the providers " + providers + + " (" + providers.size() + "/" + copyinvokers.size() + ") from the registry " + directory.getUrl().getAddress() + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + Version.getVersion() + ". Last error is: " diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index f1d8e479e4f..073cdac0151 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -15,19 +15,6 @@ */ package com.alibaba.dubbo.rpc.cluster.support; -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; @@ -35,26 +22,30 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.ConfigUtils; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.Merger; import com.alibaba.dubbo.rpc.cluster.merger.MergerFactory; +import java.lang.reflect.Array; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; + /** * @author kimi */ -@SuppressWarnings( "unchecked" ) +@SuppressWarnings("unchecked") public class MergeableClusterInvoker implements Invoker { private static final Logger log = LoggerFactory.getLogger(MergeableClusterInvoker.class); private ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("mergeable-cluster-executor", true)); - + private final Directory directory; public MergeableClusterInvoker(Directory directory) { @@ -62,121 +53,120 @@ public MergeableClusterInvoker(Directory directory) { } @SuppressWarnings("rawtypes") - public Result invoke(final Invocation invocation) throws RpcException { + public Result invoke(final Invocation invocation) throws RpcException { List> invokers = directory.list(invocation); - - String merger = getUrl().getMethodParameter( invocation.getMethodName(), Constants.MERGER_KEY ); - if ( ConfigUtils.isEmpty(merger) ) { // 如果方法不需要Merge,退化为只调一个Group - for(final Invoker invoker : invokers ) { + + String merger = getUrl().getMethodParameter(invocation.getMethodName(), Constants.MERGER_KEY); + if (ConfigUtils.isEmpty(merger)) { // 如果方法不需要Merge,退化为只调一个Group + for (final Invoker invoker : invokers) { if (invoker.isAvailable()) { return invoker.invoke(invocation); } } return invokers.iterator().next().invoke(invocation); } - + Class returnType; try { - returnType = getInterface().getMethod( - invocation.getMethodName(), invocation.getParameterTypes() ).getReturnType(); - } catch ( NoSuchMethodException e ) { + returnType = getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()).getReturnType(); + } catch (NoSuchMethodException e) { returnType = null; } - + Map> results = new HashMap>(); - for( final Invoker invoker : invokers ) { - Future future = executor.submit( new Callable() { + for (final Invoker invoker : invokers) { + Future future = executor.submit(new Callable() { public Result call() throws Exception { return invoker.invoke(new RpcInvocation(invocation, invoker)); } - } ); - results.put( invoker.getUrl().getServiceKey(), future ); + }); + results.put(invoker.getUrl().getServiceKey(), future); } Object result = null; - - List resultList = new ArrayList( results.size() ); - - int timeout = getUrl().getMethodParameter( invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT ); - for ( Map.Entry> entry : results.entrySet() ) { + + List resultList = new ArrayList(results.size()); + + int timeout = getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + for (Map.Entry> entry : results.entrySet()) { Future future = entry.getValue(); try { Result r = future.get(timeout, TimeUnit.MILLISECONDS); if (r.hasException()) { log.error(new StringBuilder(32).append("Invoke ") - .append(getGroupDescFromServiceKey(entry.getKey())) - .append(" failed: ") - .append(r.getException().getMessage()).toString(), - r.getException()); + .append(getGroupDescFromServiceKey(entry.getKey())) + .append(" failed: ") + .append(r.getException().getMessage()).toString(), + r.getException()); } else { resultList.add(r); } - } catch ( Exception e ) { - throw new RpcException( new StringBuilder( 32 ) - .append( "Failed to invoke service " ) - .append( entry.getKey() ) - .append( ": " ) - .append( e.getMessage() ).toString(), - e ); + } catch (Exception e) { + throw new RpcException(new StringBuilder(32) + .append("Failed to invoke service ") + .append(entry.getKey()) + .append(": ") + .append(e.getMessage()).toString(), + e); } } - + if (resultList.size() == 0) { - return new RpcResult((Object)null); + return new RpcResult((Object) null); } else if (resultList.size() == 1) { return resultList.iterator().next(); } if (returnType == void.class) { - return new RpcResult((Object)null); + return new RpcResult((Object) null); } - if ( merger.startsWith(".") ) { + if (merger.startsWith(".")) { merger = merger.substring(1); Method method; try { - method = returnType.getMethod( merger, returnType ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( new StringBuilder( 32 ) - .append( "Can not merge result because missing method [ " ) - .append( merger ) - .append( " ] in class [ " ) - .append( returnType.getClass().getName() ) - .append( " ]" ) - .toString() ); + method = returnType.getMethod(merger, returnType); + } catch (NoSuchMethodException e) { + throw new RpcException(new StringBuilder(32) + .append("Can not merge result because missing method [ ") + .append(merger) + .append(" ] in class [ ") + .append(returnType.getClass().getName()) + .append(" ]") + .toString()); } - if ( method != null ) { - if ( !Modifier.isPublic( method.getModifiers() ) ) { - method.setAccessible( true ); + if (method != null) { + if (!Modifier.isPublic(method.getModifiers())) { + method.setAccessible(true); } - result = resultList.remove( 0 ).getValue(); + result = resultList.remove(0).getValue(); try { - if ( method.getReturnType() != void.class - && method.getReturnType().isAssignableFrom( result.getClass() ) ) { - for ( Result r : resultList ) { - result = method.invoke( result, r.getValue() ); + if (method.getReturnType() != void.class + && method.getReturnType().isAssignableFrom(result.getClass())) { + for (Result r : resultList) { + result = method.invoke(result, r.getValue()); } } else { - for ( Result r : resultList ) { - method.invoke( result, r.getValue() ); + for (Result r : resultList) { + method.invoke(result, r.getValue()); } } - } catch ( Exception e ) { - throw new RpcException( - new StringBuilder( 32 ) - .append( "Can not merge result: " ) - .append( e.getMessage() ).toString(), - e ); + } catch (Exception e) { + throw new RpcException( + new StringBuilder(32) + .append("Can not merge result: ") + .append(e.getMessage()).toString(), + e); } } else { throw new RpcException( - new StringBuilder( 32 ) - .append( "Can not merge result because missing method [ " ) - .append( merger ) - .append( " ] in class [ " ) - .append( returnType.getClass().getName() ) - .append( " ]" ) - .toString() ); + new StringBuilder(32) + .append("Can not merge result because missing method [ ") + .append(merger) + .append(" ] in class [ ") + .append(returnType.getClass().getName()) + .append(" ]") + .toString()); } } else { Merger resultMerger; @@ -187,16 +177,16 @@ public Result call() throws Exception { } if (resultMerger != null) { List rets = new ArrayList(resultList.size()); - for(Result r : resultList) { + for (Result r : resultList) { rets.add(r.getValue()); } result = resultMerger.merge( - rets.toArray((Object[])Array.newInstance(returnType, 0))); + rets.toArray((Object[]) Array.newInstance(returnType, 0))); } else { - throw new RpcException( "There is no merger to merge result." ); + throw new RpcException("There is no merger to merge result."); } } - return new RpcResult( result ); + return new RpcResult(result); } public Class getInterface() { @@ -219,7 +209,7 @@ private String getGroupDescFromServiceKey(String key) { int index = key.indexOf("/"); if (index > 0) { return new StringBuilder(32).append("group [ ") - .append(key.substring(0, index)).append(" ]").toString(); + .append(key.substring(0, index)).append(" ]").toString(); } return key; } diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index b369bc867fc..5050598395b 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -12,7 +12,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 253030dd2a6..21968c0754a 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -15,9 +15,9 @@ - limitations under the License. --> @@ -28,7 +28,7 @@ - + @@ -48,31 +48,31 @@ - - - - - - + + + + + + - + - + - - + + - + - + diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java index 307ffadf764..7334b127881 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java @@ -15,17 +15,6 @@ */ package com.alibaba.dubbo.registry.integration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -36,34 +25,28 @@ import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.cluster.Cluster; -import com.alibaba.dubbo.rpc.cluster.Configurator; -import com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory; -import com.alibaba.dubbo.rpc.cluster.Router; -import com.alibaba.dubbo.rpc.cluster.RouterFactory; +import com.alibaba.dubbo.rpc.*; +import com.alibaba.dubbo.rpc.cluster.*; import com.alibaba.dubbo.rpc.cluster.directory.AbstractDirectory; import com.alibaba.dubbo.rpc.cluster.directory.StaticDirectory; import com.alibaba.dubbo.rpc.cluster.support.ClusterUtils; import com.alibaba.dubbo.rpc.protocol.InvokerWrapper; import com.alibaba.dubbo.rpc.support.RpcUtils; +import java.util.*; + /** * RegistryDirectory - * + * * @author william.liangf * @author chao.liuc */ public class RegistryDirectory extends AbstractDirectory implements NotifyListener { private static final Logger logger = LoggerFactory.getLogger(RegistryDirectory.class); - + private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); - + private static final RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getAdaptiveExtension(); private static final ConfiguratorFactory configuratorFactory = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class).getAdaptiveExtension(); @@ -75,17 +58,17 @@ public class RegistryDirectory extends AbstractDirectory implements Notify private final String serviceKey; // 构造时初始化,断言不为null private final Class serviceType; // 构造时初始化,断言不为null - + private final Map queryMap; // 构造时初始化,断言不为null private final URL directoryUrl; // 构造时初始化,断言不为null,并且总是赋非null值 - + private final String[] serviceMethods; private final boolean multiGroup; private volatile boolean forbidden = false; - + private volatile URL overrideDirectoryUrl; // 构造时初始化,断言不为null,并且总是赋非null值 /*override规则 @@ -94,28 +77,28 @@ public class RegistryDirectory extends AbstractDirectory implements Notify * 第二种规则:针对所有provider <* ,timeout=5000> */ private volatile List configurators; // 初始为null以及中途可能被赋为null,请使用局部变量引用 - + // Map cache service url to invoker mapping. private volatile Map> urlInvokerMap; // 初始为null以及中途可能被赋为null,请使用局部变量引用 - + // Map cache service method to invokers mapping. private volatile Map>> methodInvokerMap; // 初始为null以及中途可能被赋为null,请使用局部变量引用 - + // Set cache invokeUrls to invokers mapping. private volatile Set cachedInvokerUrls; // 初始为null以及中途可能被赋为null,请使用局部变量引用 public RegistryDirectory(Class serviceType, URL url) { super(url); - if(serviceType == null ) + if (serviceType == null) throw new IllegalArgumentException("service type is null."); - if(url.getServiceKey() == null || url.getServiceKey().length() == 0) + if (url.getServiceKey() == null || url.getServiceKey().length() == 0) throw new IllegalArgumentException("registry serviceKey is null."); this.serviceType = serviceType; this.serviceKey = url.getServiceKey(); this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = url.setPath(url.getServiceInterface()).clearParameters().addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); - String group = directoryUrl.getParameter( Constants.GROUP_KEY, "" ); - this.multiGroup = group != null && ("*".equals(group) || group.contains( "," )); + String group = directoryUrl.getParameter(Constants.GROUP_KEY, ""); + this.multiGroup = group != null && ("*".equals(group) || group.contains(",")); String methods = queryMap.get(Constants.METHODS_KEY); this.serviceMethods = methods == null ? null : Constants.COMMA_SPLIT_PATTERN.split(methods); } @@ -127,19 +110,19 @@ public void setProtocol(Protocol protocol) { public void setRegistry(Registry registry) { this.registry = registry; } - + public void subscribe(URL url) { setConsumerUrl(url); registry.subscribe(url, this); } public void destroy() { - if(isDestroyed()) { + if (isDestroyed()) { return; } // unsubscribe. try { - if(getConsumerUrl() != null && registry != null && registry.isAvailable()) { + if (getConsumerUrl() != null && registry != null && registry.isAvailable()) { registry.unsubscribe(getConsumerUrl(), this); } } catch (Throwable t) { @@ -160,10 +143,10 @@ public synchronized void notify(List urls) { for (URL url : urls) { String protocol = url.getProtocol(); String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); - if (Constants.ROUTERS_CATEGORY.equals(category) + if (Constants.ROUTERS_CATEGORY.equals(category) || Constants.ROUTE_PROTOCOL.equals(protocol)) { routerUrls.add(url); - } else if (Constants.CONFIGURATORS_CATEGORY.equals(category) + } else if (Constants.CONFIGURATORS_CATEGORY.equals(category) || Constants.OVERRIDE_PROTOCOL.equals(protocol)) { configuratorUrls.add(url); } else if (Constants.PROVIDERS_CATEGORY.equals(category)) { @@ -173,13 +156,13 @@ public synchronized void notify(List urls) { } } // configurators - if (configuratorUrls != null && configuratorUrls.size() >0 ){ + if (configuratorUrls.size() > 0) { this.configurators = toConfigurators(configuratorUrls); } // routers - if (routerUrls != null && routerUrls.size() >0 ){ + if (routerUrls.size() > 0) { List routers = toRouters(routerUrls); - if(routers != null){ // null - do nothing + if (routers != null) { // null - do nothing setRouters(routers); } } @@ -194,16 +177,17 @@ public synchronized void notify(List urls) { // providers refreshInvoker(invokerUrls); } - - + + /** * 根据invokerURL列表转换为invoker列表。转换规则如下: * 1.如果url已经被转换为invoker,则不在重新引用,直接从缓存中获取,注意如果url中任何一个参数变更也会重新引用 * 2.如果传入的invoker列表不为空,则表示最新的invoker列表 * 3.如果传入的invokerUrl列表是空,则表示只是下发的override规则或route规则,需要重新交叉对比,决定是否需要重新引用。 + * * @param invokerUrls 传入的参数不能为null */ - private void refreshInvoker(List invokerUrls){ + 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; // 禁止访问 @@ -212,33 +196,34 @@ private void refreshInvoker(List invokerUrls){ } else { this.forbidden = false; // 允许访问 Map> oldUrlInvokerMap = this.urlInvokerMap; // local reference - if (invokerUrls.size() == 0 && this.cachedInvokerUrls != null){ + assert invokerUrls != null; + 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; + if (invokerUrls.size() == 0) { + return; } - Map> newUrlInvokerMap = toInvokers(invokerUrls) ;// 将URL列表转成Invoker列表 + Map> newUrlInvokerMap = toInvokers(invokerUrls);// 将URL列表转成Invoker列表 Map>> newMethodInvokerMap = toMethodInvokers(newUrlInvokerMap); // 换方法名映射Invoker列表 // 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 ; + 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) { + try { + destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // 关闭未使用的Invoker + } catch (Exception e) { logger.warn("destroyUnusedInvokers error. ", e); } } } - + private Map>> toMergeMethodInvokerMap(Map>> methodMap) { Map>> result = new HashMap>>(); for (Map.Entry>> entry : methodMap.entrySet()) { @@ -268,32 +253,32 @@ private Map>> toMergeMethodInvokerMap(Map1.override://0.0.0.0/...(或override://ip:port...?anyhost=true)¶1=value1...表示全局规则(对所有的提供者全部生效) - *
2.override://ip:port...?anyhost=false 特例规则(只针对某个提供者生效) - *
3.不支持override://规则... 需要注册中心自行计算. - *
4.不带参数的override://0.0.0.0/ 表示清除override + * + * @param urls 契约: + *
1.override://0.0.0.0/...(或override://ip:port...?anyhost=true)¶1=value1...表示全局规则(对所有的提供者全部生效) + *
2.override://ip:port...?anyhost=false 特例规则(只针对某个提供者生效) + *
3.不支持override://规则... 需要注册中心自行计算. + *
4.不带参数的override://0.0.0.0/ 表示清除override * @return */ - public static List toConfigurators(List urls){ + public static List toConfigurators(List urls) { List configurators = new ArrayList(urls.size()); - if (urls == null || urls.size() == 0){ + if (urls.size() == 0) { return configurators; } - for(URL url : urls){ + for (URL url : urls) { if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) { configurators.clear(); break; } - Map override = new HashMap(url.getParameters()); + Map override = new HashMap(url.getParameters()); //override 上的anyhost可能是自动添加的,不能影响改变url判断 override.remove(Constants.ANYHOST_KEY); - if (override.size() == 0){ + if (override.size() == 0) { configurators.clear(); continue; } @@ -302,42 +287,41 @@ public static List toConfigurators(List urls){ Collections.sort(configurators); return configurators; } - + /** - * * @param urls * @return null : no routers ,do nothing - * else :routers list + * else :routers list */ private List toRouters(List urls) { List routers = new ArrayList(); - if(urls == null || urls.size() < 1){ - return routers ; + if (urls == null || urls.size() < 1) { + return routers; } - if (urls != null && urls.size() > 0) { + if (urls.size() > 0) { for (URL url : urls) { if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) { continue; } String routerType = url.getParameter(Constants.ROUTER_KEY); - if (routerType != null && routerType.length() > 0){ + if (routerType != null && routerType.length() > 0) { url = url.setProtocol(routerType); } - try{ + try { Router router = routerFactory.getRouter(url); if (!routers.contains(router)) routers.add(router); } catch (Throwable t) { - logger.error("convert router url to router error, url: "+ url, t); + logger.error("convert router url to router error, url: " + url, t); } } } return routers; } - + /** * 将urls转成invokers,如果url已经被refer过,不再重新引用。 - * + * * @param urls * @param overrides * @param query @@ -345,36 +329,36 @@ private List toRouters(List urls) { */ private Map> toInvokers(List urls) { Map> newUrlInvokerMap = new HashMap>(); - if(urls == null || urls.size() == 0){ + 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; - } - } + //如果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())); + 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; } URL url = mergeUrl(providerUrl); - + String key = url.toFullString(); // URL参数是排序的 if (keys.contains(key)) { // 重复URL continue; @@ -385,50 +369,51 @@ private Map> toInvokers(List urls) { 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 = new InvokerDelegete(protocol.refer(serviceType, url), url, providerUrl); - } + 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 = 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); + logger.error("Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t); } if (invoker != null) { // 将新的引用放入缓存 newUrlInvokerMap.put(key, invoker); } - }else { + } else { newUrlInvokerMap.put(key, invoker); } } keys.clear(); return newUrlInvokerMap; } - + /** * 合并url参数 顺序为override > -D >Consumer > Provider + * * @param providerUrl * @param overrides * @return */ - private URL mergeUrl(URL providerUrl){ + private URL mergeUrl(URL providerUrl) { providerUrl = ClusterUtils.mergeUrl(providerUrl, queryMap); // 合并消费端参数 - + List localConfigurators = this.configurators; // local reference if (localConfigurators != null && localConfigurators.size() > 0) { for (Configurator configurator : localConfigurators) { providerUrl = configurator.configure(providerUrl); } } - + providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false)); // 不检查连接是否成功,总是创建Invoker! - + //directoryUrl 与 override 合并是在notify的最后,这里不能够处理 this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // 合并提供者参数 - + if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0) && "dubbo".equals(providerUrl.getProtocol())) { // 兼容1.0 //fix by tony.chenl DUBBO-44 @@ -450,10 +435,10 @@ private URL mergeUrl(URL providerUrl){ private List> route(List> invokers, String method) { Invocation invocation = new RpcInvocation(method, new Class[0], new Object[0]); - List routers = getRouters(); + List routers = getRouters(); if (routers != null) { for (Router router : routers) { - if (router.getUrl() != null && ! router.getUrl().getParameter(Constants.RUNTIME_KEY, true)) { + if (router.getUrl() != null && !router.getUrl().getParameter(Constants.RUNTIME_KEY, true)) { invokers = router.route(invokers, getConsumerUrl(), invocation); } } @@ -463,7 +448,7 @@ private List> route(List> invokers, String method) { /** * 将invokers列表转成与方法的映射关系 - * + * * @param invokersMap Invoker列表 * @return Invoker与方法的映射关系 */ @@ -478,8 +463,8 @@ private Map>> toMethodInvokers(Map> i String[] methods = Constants.COMMA_SPLIT_PATTERN.split(parameter); if (methods != null && methods.length > 0) { for (String method : methods) { - if (method != null && method.length() > 0 - && ! Constants.ANY_VALUE.equals(method)) { + if (method != null && method.length() > 0 + && !Constants.ANY_VALUE.equals(method)) { List> methodInvokers = newMethodInvokerMap.get(method); if (methodInvokers == null) { methodInvokers = new ArrayList>(); @@ -517,7 +502,7 @@ private Map>> toMethodInvokers(Map> i */ private void destroyAllInvokers() { Map> localUrlInvokerMap = this.urlInvokerMap; // local reference - if(localUrlInvokerMap != null) { + if (localUrlInvokerMap != null) { for (Invoker invoker : new ArrayList>(localUrlInvokerMap.values())) { try { invoker.destroy(); @@ -529,11 +514,11 @@ private void destroyAllInvokers() { } methodInvokerMap = null; } - + /** * 检查缓存中的invoker是否需要被destroy * 如果url中指定refer.autodestroy=false,则只增加不减少,可能会有refer泄漏, - * + * * @param invokers */ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map> newUrlInvokerMap) { @@ -545,8 +530,8 @@ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map List deleted = null; if (oldUrlInvokerMap != null) { Collection> newInvokers = newUrlInvokerMap.values(); - for (Map.Entry> entry : oldUrlInvokerMap.entrySet()){ - if (! newInvokers.contains(entry.getValue())) { + for (Map.Entry> entry : oldUrlInvokerMap.entrySet()) { + if (!newInvokers.contains(entry.getValue())) { if (deleted == null) { deleted = new ArrayList(); } @@ -554,19 +539,19 @@ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map } } } - + if (deleted != null) { - for (String url : deleted){ - if (url != null ) { + for (String url : deleted) { + if (url != null) { Invoker invoker = oldUrlInvokerMap.remove(url); if (invoker != null) { try { invoker.destroy(); - if(logger.isDebugEnabled()){ - logger.debug("destory invoker["+invoker.getUrl()+"] success. "); + if (logger.isDebugEnabled()) { + logger.debug("destory invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { - logger.warn("destory invoker["+invoker.getUrl()+"] faild. " + e.getMessage(), e); + logger.warn("destory invoker[" + invoker.getUrl() + "] faild. " + e.getMessage(), e); } } } @@ -576,24 +561,24 @@ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map public List> doList(Invocation invocation) { if (forbidden) { - throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "Forbid consumer " + NetUtils.getLocalHost() + " access service " + getInterface().getName() + " from registry " + getUrl().getAddress() + " use dubbo version " + Version.getVersion() + ", Please check registry access list (whitelist/blacklist)."); + throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "Forbid consumer " + NetUtils.getLocalHost() + " access service " + getInterface().getName() + " from registry " + getUrl().getAddress() + " use dubbo version " + Version.getVersion() + ", Please check registry access list (whitelist/blacklist)."); } List> invokers = null; Map>> localMethodInvokerMap = this.methodInvokerMap; // local reference if (localMethodInvokerMap != null && localMethodInvokerMap.size() > 0) { String methodName = RpcUtils.getMethodName(invocation); Object[] args = RpcUtils.getArguments(invocation); - if(args != null && args.length > 0 && args[0] != null + if (args != null && args.length > 0 && args[0] != null && (args[0] instanceof String || args[0].getClass().isEnum())) { invokers = localMethodInvokerMap.get(methodName + "." + args[0]); // 可根据第一个参数枚举路由 } - if(invokers == null) { + if (invokers == null) { invokers = localMethodInvokerMap.get(methodName); } - if(invokers == null) { + if (invokers == null) { invokers = localMethodInvokerMap.get(Constants.ANY_VALUE); } - if(invokers == null) { + if (invokers == null) { Iterator>> iterator = localMethodInvokerMap.values().iterator(); if (iterator.hasNext()) { invokers = iterator.next(); @@ -602,13 +587,13 @@ public List> doList(Invocation invocation) { } return invokers == null ? new ArrayList>(0) : invokers; } - + public Class getInterface() { return serviceType; } public URL getUrl() { - return this.overrideDirectoryUrl; + return this.overrideDirectoryUrl; } public boolean isAvailable() { @@ -625,50 +610,52 @@ public boolean isAvailable() { } return false; } - + /** * Haomin: added for test purpose */ - public Map> getUrlInvokerMap(){ + public Map> getUrlInvokerMap() { return urlInvokerMap; } - + /** * Haomin: added for test purpose */ - public Map>> getMethodInvokerMap(){ + public Map>> getMethodInvokerMap() { return methodInvokerMap; - } - + } + private static class InvokerComparator implements Comparator> { - + private static final InvokerComparator comparator = new InvokerComparator(); - + public static InvokerComparator getComparator() { return comparator; } - - private InvokerComparator() {} + + private InvokerComparator() { + } public int compare(Invoker o1, Invoker o2) { return o1.getUrl().toString().compareTo(o2.getUrl().toString()); } } - + /** * 代理类,主要用于存储注册中心下发的url地址,用于重新重新refer时能够根据providerURL queryMap overrideMap重新组装 - * - * @author chao.liuc * * @param + * @author chao.liuc */ - private static class InvokerDelegete extends InvokerWrapper{ + private static class InvokerDelegete extends InvokerWrapper { private URL providerUrl; + public InvokerDelegete(Invoker invoker, URL url, URL providerUrl) { super(invoker, url); this.providerUrl = providerUrl; } + public URL getProviderUrl() { return providerUrl; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java index 5f908b3de6a..891bf144eb0 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java @@ -15,11 +15,6 @@ */ package com.alibaba.dubbo.registry.integration; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; @@ -32,43 +27,44 @@ import com.alibaba.dubbo.registry.Registry; import com.alibaba.dubbo.registry.RegistryFactory; import com.alibaba.dubbo.registry.RegistryService; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.ProxyFactory; -import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.cluster.Configurator; import com.alibaba.dubbo.rpc.protocol.InvokerWrapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** * RegistryProtocol - * + * * @author william.liangf * @author chao.liuc */ public class RegistryProtocol implements Protocol { private Cluster cluster; - + public void setCluster(Cluster cluster) { this.cluster = cluster; } - + private Protocol protocol; - + public void setProtocol(Protocol protocol) { this.protocol = protocol; } private RegistryFactory registryFactory; - + public void setRegistryFactory(RegistryFactory registryFactory) { this.registryFactory = registryFactory; } private ProxyFactory proxyFactory; - + public void setProxyFactory(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } @@ -76,32 +72,32 @@ public void setProxyFactory(ProxyFactory proxyFactory) { public int getDefaultPort() { return 9090; } - + private static RegistryProtocol INSTANCE; public RegistryProtocol() { INSTANCE = this; } - + public static RegistryProtocol getRegistryProtocol() { if (INSTANCE == null) { ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(Constants.REGISTRY_PROTOCOL); // load } return INSTANCE; } - + private final Map overrideListeners = new ConcurrentHashMap(); - + public Map getOverrideListeners() { - return overrideListeners; - } + return overrideListeners; + } - //用于解决rmi重复暴露端口冲突的问题,已经暴露过的服务不再重新暴露 + //用于解决rmi重复暴露端口冲突的问题,已经暴露过的服务不再重新暴露 //providerurl <--> exporter private final Map> bounds = new ConcurrentHashMap>(); - + private final static Logger logger = LoggerFactory.getLogger(RegistryProtocol.class); - + public Exporter export(final Invoker originInvoker) throws RpcException { //export invoker final ExporterChangeableWrapper exporter = doLocalExport(originInvoker); @@ -120,29 +116,30 @@ public Exporter export(final Invoker originInvoker) throws RpcExceptio public Invoker getInvoker() { return exporter.getInvoker(); } + public void unexport() { - try { - exporter.unexport(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); + try { + exporter.unexport(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); } try { - registry.unregister(registedProviderUrl); + registry.unregister(registedProviderUrl); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(t.getMessage(), t); } try { - overrideListeners.remove(overrideSubscribeUrl); - registry.unsubscribe(overrideSubscribeUrl, overrideSubscribeListener); + overrideListeners.remove(overrideSubscribeUrl); + registry.unsubscribe(overrideSubscribeUrl, overrideSubscribeListener); } catch (Throwable t) { - logger.warn(t.getMessage(), t); + logger.warn(t.getMessage(), t); } } }; } - + @SuppressWarnings("unchecked") - private ExporterChangeableWrapper doLocalExport(final Invoker originInvoker){ + private ExporterChangeableWrapper doLocalExport(final Invoker originInvoker) { String key = getCacheKey(originInvoker); ExporterChangeableWrapper exporter = (ExporterChangeableWrapper) bounds.get(key); if (exporter == null) { @@ -150,26 +147,27 @@ private ExporterChangeableWrapper doLocalExport(final Invoker originI exporter = (ExporterChangeableWrapper) bounds.get(key); if (exporter == null) { final Invoker invokerDelegete = new InvokerDelegete(originInvoker, getProviderUrl(originInvoker)); - exporter = new ExporterChangeableWrapper((Exporter)protocol.export(invokerDelegete), originInvoker); + exporter = new ExporterChangeableWrapper((Exporter) protocol.export(invokerDelegete), originInvoker); bounds.put(key, exporter); } } } return (ExporterChangeableWrapper) exporter; } - + /** * 对修改了url的invoker重新export + * * @param originInvoker * @param newInvokerUrl */ @SuppressWarnings("unchecked") - private void doChangeLocalExport(final Invoker originInvoker, URL newInvokerUrl){ + private void doChangeLocalExport(final Invoker originInvoker, URL newInvokerUrl) { String key = getCacheKey(originInvoker); final ExporterChangeableWrapper exporter = (ExporterChangeableWrapper) bounds.get(key); - if (exporter == null){ + if (exporter == null) { logger.warn(new IllegalStateException("error state, exporter should not be null")); - return ;//不存在是异常场景 直接返回 + return;//不存在是异常场景 直接返回 } else { final Invoker invokerDelegete = new InvokerDelegete(originInvoker, newInvokerUrl); exporter.setExporter(protocol.export(invokerDelegete)); @@ -178,10 +176,11 @@ private void doChangeLocalExport(final Invoker originInvoker, URL newInvo /** * 根据invoker的地址获取registry实例 + * * @param originInvoker * @return */ - private Registry getRegistry(final Invoker originInvoker){ + private Registry getRegistry(final Invoker originInvoker) { URL registryUrl = originInvoker.getUrl(); if (Constants.REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) { String protocol = registryUrl.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_DIRECTORY); @@ -192,86 +191,87 @@ private Registry getRegistry(final Invoker originInvoker){ /** * 返回注册到注册中心的URL,对URL参数进行一次过滤 + * * @param originInvoker * @return */ - private URL getRegistedProviderUrl(final Invoker originInvoker){ + private URL getRegistedProviderUrl(final Invoker originInvoker) { URL providerUrl = getProviderUrl(originInvoker); //注册中心看到的地址 final URL registedProviderUrl = providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameter(Constants.MONITOR_KEY); return registedProviderUrl; } - - private URL getSubscribedOverrideUrl(URL registedProviderUrl){ - return registedProviderUrl.setProtocol(Constants.PROVIDER_PROTOCOL) - .addParameters(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY, + + private URL getSubscribedOverrideUrl(URL registedProviderUrl) { + return registedProviderUrl.setProtocol(Constants.PROVIDER_PROTOCOL) + .addParameters(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY, Constants.CHECK_KEY, String.valueOf(false)); } /** * 通过invoker的url 获取 providerUrl的地址 + * * @param origininvoker * @return */ - private URL getProviderUrl(final Invoker origininvoker){ + private URL getProviderUrl(final Invoker origininvoker) { String export = origininvoker.getUrl().getParameterAndDecoded(Constants.EXPORT_KEY); if (export == null || export.length() == 0) { throw new IllegalArgumentException("The registry export url is null! registry: " + origininvoker.getUrl()); } - - URL providerUrl = URL.valueOf(export); - return providerUrl; + + return URL.valueOf(export); } /** * 获取invoker在bounds中缓存的key + * * @param originInvoker * @return */ - private String getCacheKey(final Invoker originInvoker){ + private String getCacheKey(final Invoker originInvoker) { URL providerUrl = getProviderUrl(originInvoker); - String key = providerUrl.removeParameters("dynamic", "enabled").toFullString(); - return key; + return providerUrl.removeParameters("dynamic", "enabled").toFullString(); } - + @SuppressWarnings("unchecked") - public Invoker refer(Class type, URL url) throws RpcException { + public Invoker refer(Class type, URL url) throws RpcException { url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { - return proxyFactory.getInvoker((T) registry, type, url); + 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 ); + 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); } - + private Cluster getMergeableCluster() { return ExtensionLoader.getExtensionLoader(Cluster.class).getExtension("mergeable"); } - + private Invoker doRefer(Cluster cluster, Registry registry, Class type, URL url) { RegistryDirectory directory = new RegistryDirectory(type, url); directory.setRegistry(registry); directory.setProtocol(protocol); URL subscribeUrl = new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, type.getName(), directory.getUrl().getParameters()); - if (! Constants.ANY_VALUE.equals(url.getServiceInterface()) + 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))); } - directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY, - Constants.PROVIDERS_CATEGORY - + "," + Constants.CONFIGURATORS_CATEGORY - + "," + Constants.ROUTERS_CATEGORY)); + directory.subscribe(subscribeUrl.addParameter(Constants.CATEGORY_KEY, + Constants.PROVIDERS_CATEGORY + + "," + Constants.CONFIGURATORS_CATEGORY + + "," + Constants.ROUTERS_CATEGORY)); return cluster.join(directory); } @@ -287,81 +287,81 @@ private static String[] getFilteredKeys(URL url) { } return filteredKeys.toArray(new String[filteredKeys.size()]); } else { - return new String[] {}; + return new String[]{}; } } - + public void destroy() { List> exporters = new ArrayList>(bounds.values()); - for(Exporter exporter :exporters){ + for (Exporter exporter : exporters) { exporter.unexport(); } bounds.clear(); } - - + + /*重新export 1.protocol中的exporter destory问题 *1.要求registryprotocol返回的exporter可以正常destroy *2.notify后不需要重新向注册中心注册 *3.export 方法传入的invoker最好能一直作为exporter的invoker. */ private class OverrideListener implements NotifyListener { - - private volatile List configurators; - - private final URL subscribeUrl; - public OverrideListener(URL subscribeUrl) { - this.subscribeUrl = subscribeUrl; - } + private volatile List configurators; + + private final URL subscribeUrl; + + public OverrideListener(URL subscribeUrl) { + this.subscribeUrl = subscribeUrl; + } - /* + /* * provider 端可识别的override url只有这两种. * override://0.0.0.0/serviceName?timeout=10 * override://0.0.0.0/?timeout=10 */ public void notify(List urls) { - List result = null; - for (URL url : urls) { - URL overrideUrl = url; - if (url.getParameter(Constants.CATEGORY_KEY) == null - && Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) { - // 兼容旧版本 - overrideUrl = url.addParameter(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY); - } - if (! UrlUtils.isMatch(subscribeUrl, overrideUrl)) { - if (result == null) { - result = new ArrayList(urls); - } - result.remove(url); - logger.warn("Subsribe category=configurator, but notifed non-configurator urls. may be registry bug. unexcepted url: " + url); - } - } - if (result != null) { - urls = result; - } - this.configurators = RegistryDirectory.toConfigurators(urls); + List result = null; + for (URL url : urls) { + URL overrideUrl = url; + if (url.getParameter(Constants.CATEGORY_KEY) == null + && Constants.OVERRIDE_PROTOCOL.equals(url.getProtocol())) { + // 兼容旧版本 + overrideUrl = url.addParameter(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY); + } + if (!UrlUtils.isMatch(subscribeUrl, overrideUrl)) { + if (result == null) { + result = new ArrayList(urls); + } + result.remove(url); + logger.warn("Subsribe category=configurator, but notifed non-configurator urls. may be registry bug. unexcepted url: " + url); + } + } + if (result != null) { + urls = result; + } + this.configurators = RegistryDirectory.toConfigurators(urls); List> exporters = new ArrayList>(bounds.values()); - for (ExporterChangeableWrapper exporter : exporters){ + for (ExporterChangeableWrapper exporter : exporters) { Invoker invoker = exporter.getOriginInvoker(); - final Invoker originInvoker ; - if (invoker instanceof InvokerDelegete){ - originInvoker = ((InvokerDelegete)invoker).getInvoker(); - }else { + final Invoker originInvoker; + if (invoker instanceof InvokerDelegete) { + originInvoker = ((InvokerDelegete) invoker).getInvoker(); + } else { originInvoker = invoker; } - + URL originUrl = RegistryProtocol.this.getProviderUrl(originInvoker); URL newUrl = getNewInvokerUrl(originUrl, urls); - - if (! originUrl.equals(newUrl)){ + + if (!originUrl.equals(newUrl)) { RegistryProtocol.this.doChangeLocalExport(originInvoker, newUrl); } } } - - private URL getNewInvokerUrl(URL url, List urls){ - List localConfigurators = this.configurators; // local reference + + private URL getNewInvokerUrl(URL url, List urls) { + List localConfigurators = this.configurators; // local reference // 合并override参数 if (localConfigurators != null && localConfigurators.size() > 0) { for (Configurator configurator : localConfigurators) { @@ -371,44 +371,45 @@ private URL getNewInvokerUrl(URL url, List urls){ return url; } } - - public static class InvokerDelegete extends InvokerWrapper{ + + public static class InvokerDelegete extends InvokerWrapper { private final Invoker invoker; + /** - * @param invoker - * @param url invoker.getUrl返回此值 + * @param invoker + * @param url invoker.getUrl返回此值 */ - public InvokerDelegete(Invoker invoker, URL url){ + public InvokerDelegete(Invoker invoker, URL url) { super(invoker, url); this.invoker = invoker; } - public Invoker getInvoker(){ - if (invoker instanceof InvokerDelegete){ - return ((InvokerDelegete)invoker).getInvoker(); + + public Invoker getInvoker() { + if (invoker instanceof InvokerDelegete) { + return ((InvokerDelegete) invoker).getInvoker(); } else { return invoker; } } } - + /** * exporter代理,建立返回的exporter与protocol export出的exporter的对应关系,在override时可以进行关系修改. - * - * @author chao.liuc * * @param + * @author chao.liuc */ - private class ExporterChangeableWrapper implements Exporter{ - + private class ExporterChangeableWrapper implements Exporter { + private Exporter exporter; - + private final Invoker originInvoker; - public ExporterChangeableWrapper(Exporter exporter, Invoker originInvoker){ + public ExporterChangeableWrapper(Exporter exporter, Invoker originInvoker) { this.exporter = exporter; this.originInvoker = originInvoker; } - + public Invoker getOriginInvoker() { return originInvoker; } @@ -416,8 +417,8 @@ public Invoker getOriginInvoker() { public Invoker getInvoker() { return exporter.getInvoker(); } - - public void setExporter(Exporter exporter){ + + public void setExporter(Exporter exporter) { this.exporter = exporter; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java index 7930ae71d95..755b06b2b39 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java @@ -15,28 +15,18 @@ */ package com.alibaba.dubbo.registry.support; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.ConcurrentHashSet; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.registry.NotifyListener; +import java.util.*; +import java.util.concurrent.*; + /** * FailbackRegistry. (SPI, Prototype, ThreadSafe) - * + * * @author william.liangf */ public abstract class FailbackRegistry extends AbstractRegistry { @@ -134,10 +124,10 @@ public void register(URL url) { // 如果开启了启动时检测,则直接抛出异常 boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) - && ! Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); + && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { - if(skipFailback) { + if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); @@ -164,10 +154,10 @@ public void unregister(URL url) { // 如果开启了启动时检测,则直接抛出异常 boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) - && ! Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); + && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { - if(skipFailback) { + if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); @@ -200,7 +190,7 @@ public void subscribe(URL url, NotifyListener listener) { && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { - if(skipFailback) { + if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); @@ -229,7 +219,7 @@ public void unsubscribe(URL url, NotifyListener listener) { && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { - if(skipFailback) { + if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); @@ -256,7 +246,7 @@ protected void notify(URL url, NotifyListener listener, List urls) { throw new IllegalArgumentException("notify listener == null"); } try { - doNotify(url, listener, urls); + doNotify(url, listener, urls); } catch (Exception t) { // 将失败的通知请求记录到失败列表,定时重试 Map> listeners = failedNotified.get(url); @@ -268,16 +258,16 @@ protected void notify(URL url, NotifyListener listener, List urls) { logger.error("Failed to notify for subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } - + protected void doNotify(URL url, NotifyListener listener, List urls) { - super.notify(url, listener, urls); + super.notify(url, listener, urls); } - + @Override protected void recover() throws Exception { // register Set recoverRegistered = new HashSet(getRegistered()); - if (! recoverRegistered.isEmpty()) { + if (!recoverRegistered.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover register url " + recoverRegistered); } @@ -287,7 +277,7 @@ protected void recover() throws Exception { } // subscribe Map> recoverSubscribed = new HashMap>(getSubscribed()); - if (! recoverSubscribed.isEmpty()) { + if (!recoverSubscribed.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover subscribe url " + recoverSubscribed.keySet()); } @@ -302,7 +292,7 @@ protected void recover() throws Exception { // 重试失败的动作 protected void retry() { - if (! failedRegistered.isEmpty()) { + if (!failedRegistered.isEmpty()) { Set failed = new HashSet(failedRegistered); if (failed.size() > 0) { if (logger.isInfoEnabled()) { @@ -322,7 +312,7 @@ protected void retry() { } } } - if(! failedUnregistered.isEmpty()) { + if (!failedUnregistered.isEmpty()) { Set failed = new HashSet(failedUnregistered); if (failed.size() > 0) { if (logger.isInfoEnabled()) { @@ -342,7 +332,7 @@ protected void retry() { } } } - if (! failedSubscribed.isEmpty()) { + if (!failedSubscribed.isEmpty()) { Map> failed = new HashMap>(failedSubscribed); for (Map.Entry> entry : new HashMap>(failed).entrySet()) { if (entry.getValue() == null || entry.getValue().size() == 0) { @@ -371,7 +361,7 @@ protected void retry() { } } } - if (! failedUnsubscribed.isEmpty()) { + if (!failedUnsubscribed.isEmpty()) { Map> failed = new HashMap>(failedUnsubscribed); for (Map.Entry> entry : new HashMap>(failed).entrySet()) { if (entry.getValue() == null || entry.getValue().size() == 0) { @@ -400,7 +390,7 @@ protected void retry() { } } } - if (! failedNotified.isEmpty()) { + if (!failedNotified.isEmpty()) { Map>> failed = new HashMap>>(failedNotified); for (Map.Entry>> entry : new HashMap>>(failed).entrySet()) { if (entry.getValue() == null || entry.getValue().size() == 0) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java index 37a1b9dad78..fdd1c54ae13 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java @@ -17,5 +17,7 @@ interface Chain { Response proceed(Request request, int timeout) throws RemotingException; + Response proceed(Request request) throws RemotingException; + } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java index 45050cb8183..09f73382f78 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java @@ -177,6 +177,11 @@ public Response proceed(Request request, int timeout) throws RemotingException { } return channel.request(request, timeout); } + + @Override + public Response proceed(Request request) { + throw new UnsupportedOperationException("This is server side method"); + } } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java index 67825e74926..fccca848247 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java @@ -10,14 +10,13 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; /** * @author Xs @@ -30,6 +29,8 @@ public class HeaderExchangeHandlerV2 implements ChannelHandlerDelegate { public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; + private final List interceptors = new ArrayList(); + private final ExchangeHandler handler; public HeaderExchangeHandlerV2(ExchangeHandler handler) { @@ -77,11 +78,11 @@ private void handleResponse(Response response) throws RemotingException { public void connected(Channel channel) throws RemotingException { channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); try { handler.connected(exchangeChannel); } finally { - HeaderExchangeChannel.removeChannelIfDisconnected(channel); + HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); } } @@ -100,11 +101,11 @@ public void sent(Channel channel, Object message) throws RemotingException { Throwable exception = null; try { channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); try { handler.sent(exchangeChannel, message); } finally { - HeaderExchangeChannel.removeChannelIfDisconnected(channel); + HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); } } catch (Throwable t) { exception = t; @@ -135,7 +136,7 @@ private static boolean isClientSide(Channel channel) { public void received(Channel channel, Object message) throws RemotingException { channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); try { if (message instanceof Request) { Request request = (Request) message; @@ -143,7 +144,8 @@ public void received(Channel channel, Object message) throws RemotingException { handlerEvent(channel, request); } else { if (request.isTwoWay()) { - Response response = handleRequest(exchangeChannel, request); + Interceptor.Chain chain = new ExchangeHandlerChain(0, exchangeChannel, request); + Response response = chain.proceed(request); channel.send(response); } else { handler.received(exchangeChannel, request.getData()); @@ -166,7 +168,48 @@ public void received(Channel channel, Object message) throws RemotingException { handler.received(exchangeChannel, message); } } finally { - HeaderExchangeChannel.removeChannelIfDisconnected(channel); + HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); + } + } + + class ExchangeHandlerChain implements Interceptor.Chain { + private final int index; + private final ExchangeChannel exchangeChannel; + private final Request request; + + public ExchangeHandlerChain(int index, ExchangeChannel exchangeChannel, Request request) { + this.index = index; + this.exchangeChannel = exchangeChannel; + this.request = request; + } + + @Override + public Request request() { + return request; + } + + @Override + public int timeout() { + return 0; + } + + @Override + public Response proceed(Request request, int timeout) throws RemotingException { + throw new UnsupportedOperationException("This is client side method"); + } + + @Override + public Response proceed(Request request) throws RemotingException { + if (index < interceptors.size()) { + Interceptor.Chain chain = new ExchangeHandlerChain(index + 1, exchangeChannel, request); + Interceptor interceptor = interceptors.get(index); + Response response = interceptor.intercept(chain); + if (response == null) { + throw new NullPointerException("interceptor " + interceptor + " returned null"); + } + return response; + } + return handleRequest(exchangeChannel, request); } } @@ -184,11 +227,11 @@ public void caught(Channel channel, Throwable exception) throws RemotingExceptio } } } - ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); + ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); try { handler.caught(exchangeChannel, exception); } finally { - HeaderExchangeChannel.removeChannelIfDisconnected(channel); + HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); } } @@ -199,4 +242,8 @@ public ChannelHandler getHandler() { return handler; } } + + public void addInterceptor(Interceptor interceptor) { + interceptors.add(interceptor); + } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index 453ff408dc1..3035cb0f359 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -19,8 +19,8 @@ public DubboResponse(Response response) { } } - public boolean returnSuccessfully() { - return !result.hasException(); + public boolean returnOK() { + return response.getStatus() == Response.OK && !result.hasException(); } public boolean isTraceable() { @@ -28,8 +28,8 @@ public boolean isTraceable() { } public String exceptionMessage() { - if (returnSuccessfully()) { - return "result OK"; + if (returnOK()) { + return "response OK"; } Throwable throwable = result.getException(); if (throwable instanceof NullPointerException) { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java deleted file mode 100644 index 62aba5573f4..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/HttpTrackerComponent.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.alibaba.dubbo.tracker; - -/** - * @author Xs - */ -public class HttpTrackerComponent { - -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java index 4c22fc1377a..c181d4b18ed 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java @@ -1,5 +1,10 @@ package com.alibaba.dubbo.tracker; +/** + * RpcTracker引擎 + * + * @author Xs + */ public interface RpcTrackerEngine { Object clientRequestInterceptor(); diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java similarity index 98% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java index 9742866dde8..20bebc4ac46 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java @@ -9,7 +9,7 @@ /** * @author Xs */ -public class TrackerManager { +public class RpcTrackerManager { private static RpcTrackerFactory rpcTrackerFactory; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java deleted file mode 100644 index cd476505cfc..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ClientRpcTrackerFilter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.alibaba.dubbo.tracker.filter; - -import com.alibaba.dubbo.rpc.Filter; - -/** - * @author Xs - */ -public interface ClientRpcTrackerFilter extends Filter { -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java deleted file mode 100644 index 86e6f643618..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServerRpcTrackerFilter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.alibaba.dubbo.tracker.filter; - -import com.alibaba.dubbo.rpc.Filter; - -/** - * @author Xs - */ -public interface ServerRpcTrackerFilter extends Filter { -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java index ebacf191c6e..26d13df012d 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java @@ -2,8 +2,13 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.github.kristofa.brave.Brave; +import com.github.kristofa.brave.*; +/** + * 基于Zipkin的RpcTracker引擎 + * + * @author Xs + */ public class BraveRpcTrackerEngine implements RpcTrackerEngine { private final Brave brave; @@ -20,22 +25,22 @@ public static BraveRpcTrackerEngine create(URL url) { } @Override - public Object clientRequestInterceptor() { + public ClientRequestInterceptor clientRequestInterceptor() { return brave.clientRequestInterceptor(); } @Override - public Object clientResponseInterceptor() { + public ClientResponseInterceptor clientResponseInterceptor() { return brave.clientResponseInterceptor(); } @Override - public Object serverRequestInterceptor() { + public ServerRequestInterceptor serverRequestInterceptor() { return brave.serverRequestInterceptor(); } @Override - public Object serverResponseInterceptor() { + public ServerResponseInterceptor serverResponseInterceptor() { return brave.serverResponseInterceptor(); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index bff3430bb92..ddaf5a6f4e0 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -3,7 +3,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.RpcTrackerFactory; -import com.alibaba.dubbo.tracker.TrackerManager; +import com.alibaba.dubbo.tracker.RpcTrackerManager; import com.alibaba.dubbo.tracker.zipkin.http.HttpRpcTracker; /** @@ -16,7 +16,7 @@ public RpcTracker createRpcTracker(URL url) { String protocol = url.getProtocol(); RpcTracker rpcTracker = null; if (protocol.equals("dubbo")) { - rpcTracker = new DubboRpcTracker((BraveRpcTrackerEngine) TrackerManager.getRpcTrackerEngine()); + rpcTracker = new DubboRpcTracker((BraveRpcTrackerEngine) RpcTrackerManager.getRpcTrackerEngine()); } else if (protocol.equals("http") || protocol.equals("hessian")) { rpcTracker = new HttpRpcTracker(); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java similarity index 76% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java index 5973bdcc5ab..ecc647be7d1 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java @@ -8,15 +8,15 @@ import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.DubboResponse; -public class DubboRequestResponseInterceptor implements Interceptor { +public class DubboClientRequestResponseInterceptor implements Interceptor { private final DubboClientRequestInterceptor clientRequestInterceptor; private final DubboClientResponseInterceptor clientResponseInterceptor; private final DubboRequestSpanNameProvider spanNameProvider; - public DubboRequestResponseInterceptor(DubboClientRequestInterceptor clientRequestInterceptor, - DubboClientResponseInterceptor clientResponseInterceptor, - DubboRequestSpanNameProvider spanNameProvider) { + public DubboClientRequestResponseInterceptor(DubboClientRequestInterceptor clientRequestInterceptor, + DubboClientResponseInterceptor clientResponseInterceptor, + DubboRequestSpanNameProvider spanNameProvider) { this.clientRequestInterceptor = clientRequestInterceptor; this.clientResponseInterceptor = clientResponseInterceptor; this.spanNameProvider = spanNameProvider; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java index ce71582566e..51f02e261a4 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java @@ -2,6 +2,11 @@ import com.alibaba.dubbo.tracker.*; +/** + * 追踪dubbo协议同步调用 + * + * @author Xs + */ public class DubboRpcTracker implements RpcTracker { private final ClientRequestInterceptor clientRequestInterceptor; @@ -17,13 +22,13 @@ public class DubboRpcTracker implements RpcTracker { public DubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { this.trackerEngine = trackerEngine; this.clientRequestInterceptor = new BraveDubboClientRequestInterceptor( - (com.github.kristofa.brave.ClientRequestInterceptor) trackerEngine.clientRequestInterceptor()); + trackerEngine.clientRequestInterceptor()); this.clientResponseInterceptor = new BraveDubboClientResponseInterceptor( - (com.github.kristofa.brave.ClientResponseInterceptor) trackerEngine.clientResponseInterceptor()); + trackerEngine.clientResponseInterceptor()); this.serverRequestInterceptor = new BraveDubboServerRequestInterceptor( - (com.github.kristofa.brave.ServerRequestInterceptor) trackerEngine.serverRequestInterceptor()); + trackerEngine.serverRequestInterceptor()); this.serverResponseInterceptor = new BraveDubboServerResponseInterceptor( - (com.github.kristofa.brave.ServerResponseInterceptor) trackerEngine.serverResponseInterceptor()); + trackerEngine.serverResponseInterceptor()); } @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java new file mode 100644 index 00000000000..e09539d2705 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java @@ -0,0 +1,35 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.Interceptor; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.DubboResponse; + +public class DubboServerRequestResponseInterceptor implements Interceptor { + + private final DubboServerRequestInterceptor serverRequestInterceptor; + + private final DubboServerResponseInterceptor serverResponseInterceptor; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public DubboServerRequestResponseInterceptor(DubboServerRequestInterceptor serverRequestInterceptor, + DubboServerResponseInterceptor serverResponseInterceptor, + DubboRequestSpanNameProvider spanNameProvider) { + this.serverRequestInterceptor = serverRequestInterceptor; + this.serverResponseInterceptor = serverResponseInterceptor; + this.spanNameProvider = spanNameProvider; + } + + @Override + public Response intercept(Chain chain) throws RemotingException { + Request request = chain.request(); + serverRequestInterceptor.handle(new DubboServerRequestAdapter(new DubboRequest(request), spanNameProvider)); + Response response = chain.proceed(request); + serverResponseInterceptor.handle(new DubboServerResponseAdapter(new DubboResponse(response))); + return response; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java index 7e42bad16f1..953737540af 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java @@ -26,7 +26,7 @@ public boolean isTraceable() { @Override public Collection responseAnnotations() { KeyValueAnnotation statusAnnotation; - if (response.returnSuccessfully()) { + if (response.returnOK()) { statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); } else { statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java index 4e4a9fbaf9b..0707e62b3a5 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java @@ -11,6 +11,9 @@ import java.util.Collection; import java.util.Collections; +/** + * @author Xs + */ public class HttpClientRequestAdapter implements ClientRequestAdapter { private final HttpClientRequest request; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java index 77aaa1dc0d6..c3c42712c71 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java @@ -2,5 +2,8 @@ import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +/** + * @author Xs + */ public interface HttpClientResponseInterceptor extends ClientResponseInterceptor { } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java index c10c288127e..f006f94d0b6 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java @@ -2,6 +2,9 @@ import com.alibaba.dubbo.tracker.*; +/** + * @author Xs + */ public class HttpRpcTracker implements RpcTracker { @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java index ecdbde28e9f..635d323f313 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java @@ -4,7 +4,7 @@ import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.RpcTrackerEngine; import com.alibaba.dubbo.tracker.RpcTrackerFactory; -import com.alibaba.dubbo.tracker.TrackerManager; +import com.alibaba.dubbo.tracker.RpcTrackerManager; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -16,27 +16,27 @@ public class ExtensionTest { @BeforeClass public static void before(){ URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - trackerEngine = TrackerManager.createRpcTrackerEngine(url); + trackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); } @Test public void test_rpc_factory() { - RpcTrackerFactory factory = TrackerManager.getTrackerFactory(); - RpcTrackerFactory factory1 = TrackerManager.getTrackerFactory(); + RpcTrackerFactory factory = RpcTrackerManager.getTrackerFactory(); + RpcTrackerFactory factory1 = RpcTrackerManager.getTrackerFactory(); Assert.assertEquals(factory, factory1); } @Test public void test_create_tracker() { URL url = URL.valueOf("dubbo://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - RpcTracker rpcTracker = TrackerManager.createRpcTracker(url); - RpcTracker rpcTracker1 = TrackerManager.createRpcTracker(url); + RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); + RpcTracker rpcTracker1 = RpcTrackerManager.createRpcTracker(url); Assert.assertEquals(rpcTracker, rpcTracker1); } @Test public void test_create_engine(){ URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - RpcTrackerEngine trackerEngine = TrackerManager.getRpcTrackerEngine(); + RpcTrackerEngine trackerEngine = RpcTrackerManager.getRpcTrackerEngine(); } } From 663c0be8d4476b511829370bcf55bf3d2cc56238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Fri, 20 Jan 2017 20:06:32 +0800 Subject: [PATCH 15/69] GroupingCluster --- .../support/AbstractClusterInvoker.java | 21 +++---- .../rpc/cluster/support/GroupingCluster.java | 16 +++++ .../support/GroupingClusterInvoker.java | 22 +++++++ .../com.alibaba.dubbo.rpc.cluster.Cluster | 3 +- .../dubbo/common/utils/StringUtils.java | 7 +-- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 4 +- .../integration/RegistryDirectory.java | 13 ++--- .../integration/RegistryProtocol.java | 15 +++-- .../header/HeaderExchangeHandlerV2.java | 12 ++-- .../tracker/RpcContextMethodNameProvider.java | 10 ++++ .../zipkin/BraveRpcTrackerFactory.java | 2 +- .../zipkin/DubboClientResponseAdapter.java | 2 +- .../http/AttachMethodNameInterceptor.java | 20 +++++++ .../zipkin/http/FacadeHttpRpcTracker.java | 31 ++++++++++ .../zipkin/http/HttpClientRequestAdapter.java | 58 ------------------- .../http/HttpClientRequestInterceptor.java | 6 -- .../http/HttpClientResponseInterceptor.java | 9 --- .../http/HttpRequestResponseInterceptor.java | 31 ---------- .../tracker/zipkin/http/HttpRpcTracker.java | 27 +++------ .../zipkin/http/HttpSpanNameProvider.java | 30 ++++++++++ 21 files changed, 171 insertions(+), 170 deletions(-) create mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java create mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcContextMethodNameProvider.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index c19806f7340..d5772944286 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -98,16 +98,14 @@ protected Invoker select(LoadBalance loadbalance, Invocation invocation, List String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); - { - //ignore overloaded method - if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { - stickyInvoker = null; - } - //ignore cucurrent problem - if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { - if (availablecheck && stickyInvoker.isAvailable()) { - return stickyInvoker; - } + //ignore overloaded method + if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { + stickyInvoker = null; + } + //ignore cucurrent problem + if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { + if (availablecheck && stickyInvoker.isAvailable()) { + return stickyInvoker; } } Invoker invoker = doSelect(loadbalance, invocation, invokers, selected); @@ -210,11 +208,8 @@ private Invoker reselect(LoadBalance loadbalance, Invocation invocation, } public Result invoke(final Invocation invocation) throws RpcException { - checkWheatherDestoried(); - LoadBalance loadbalance; - List> invokers = list(invocation); if (invokers != null && invokers.size() > 0) { loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl() diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java new file mode 100644 index 00000000000..0c697c7f64c --- /dev/null +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java @@ -0,0 +1,16 @@ +package com.alibaba.dubbo.rpc.cluster.support; + +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.cluster.Cluster; +import com.alibaba.dubbo.rpc.cluster.Directory; + +public class GroupingCluster implements Cluster { + + public final static String NAME = "grouping"; + + @Override + public Invoker join(Directory directory) throws RpcException { + return new GroupingClusterInvoker(directory); + } +} diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java new file mode 100644 index 00000000000..f9767187cb4 --- /dev/null +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.rpc.cluster.support; + +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.cluster.Directory; +import com.alibaba.dubbo.rpc.cluster.LoadBalance; + +import java.util.List; + +public class GroupingClusterInvoker extends AbstractClusterInvoker { + + public GroupingClusterInvoker(Directory directory) { + super(directory); + } + + @Override + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + return null; + } +} diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster index 54e85ed763b..300fc79063c 100644 --- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster +++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster @@ -6,4 +6,5 @@ failback=com.alibaba.dubbo.rpc.cluster.support.FailbackCluster forking=com.alibaba.dubbo.rpc.cluster.support.ForkingCluster available=com.alibaba.dubbo.rpc.cluster.support.AvailableCluster mergeable=com.alibaba.dubbo.rpc.cluster.support.MergeableCluster -broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster \ No newline at end of file +broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster +grouping=com.alibaba.dubbo.rpc.cluster.support.GroupingCluster \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java index 01186b9cf3c..ead6a8adfea 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java @@ -345,10 +345,9 @@ private static Map parseKeyValuePair(String str, String itemSepa { String[] tmp = str.split(itemSeparator); Map map = new HashMap(tmp.length); - for(int i=0;i - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 21968c0754a..e49483c0032 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -58,11 +58,11 @@ - + - + diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java index 7334b127881..d23028553a4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java @@ -98,7 +98,7 @@ public RegistryDirectory(Class serviceType, URL url) { this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = url.setPath(url.getServiceInterface()).clearParameters().addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); String group = directoryUrl.getParameter(Constants.GROUP_KEY, ""); - this.multiGroup = group != null && ("*".equals(group) || group.contains(",")); + this.multiGroup = group != null && ("*".equals(group) || group.contains(",") || group.equals("grouping")); String methods = queryMap.get(Constants.METHODS_KEY); this.serviceMethods = methods == null ? null : Constants.COMMA_SPLIT_PATTERN.split(methods); } @@ -323,8 +323,6 @@ private List toRouters(List urls) { * 将urls转成invokers,如果url已经被refer过,不再重新引用。 * * @param urls - * @param overrides - * @param query * @return invokers */ private Map> toInvokers(List urls) { @@ -376,7 +374,7 @@ private Map> toInvokers(List urls) { enabled = url.getParameter(Constants.ENABLED_KEY, true); } if (enabled) { - invoker = new InvokerDelegete(protocol.refer(serviceType, url), url, providerUrl); + invoker = new InvokerDelegate(protocol.refer(serviceType, url), url, providerUrl); } } catch (Throwable t) { logger.error("Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t); @@ -396,7 +394,6 @@ private Map> toInvokers(List urls) { * 合并url参数 顺序为override > -D >Consumer > Provider * * @param providerUrl - * @param overrides * @return */ private URL mergeUrl(URL providerUrl) { @@ -518,8 +515,6 @@ private void destroyAllInvokers() { /** * 检查缓存中的invoker是否需要被destroy * 如果url中指定refer.autodestroy=false,则只增加不减少,可能会有refer泄漏, - * - * @param invokers */ private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map> newUrlInvokerMap) { if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) { @@ -648,10 +643,10 @@ public int compare(Invoker o1, Invoker o2) { * @param * @author chao.liuc */ - private static class InvokerDelegete extends InvokerWrapper { + private static class InvokerDelegate extends InvokerWrapper { private URL providerUrl; - public InvokerDelegete(Invoker invoker, URL url, URL providerUrl) { + public InvokerDelegate(Invoker invoker, URL url, URL providerUrl) { super(invoker, url); this.providerUrl = providerUrl; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java index 891bf144eb0..23a6b1f2e9e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java @@ -167,7 +167,6 @@ private void doChangeLocalExport(final Invoker originInvoker, URL newInvo final ExporterChangeableWrapper exporter = (ExporterChangeableWrapper) bounds.get(key); if (exporter == null) { logger.warn(new IllegalStateException("error state, exporter should not be null")); - return;//不存在是异常场景 直接返回 } else { final Invoker invokerDelegete = new InvokerDelegete(originInvoker, newInvokerUrl); exporter.setExporter(protocol.export(invokerDelegete)); @@ -198,8 +197,7 @@ private Registry getRegistry(final Invoker originInvoker) { private URL getRegistedProviderUrl(final Invoker originInvoker) { URL providerUrl = getProviderUrl(originInvoker); //注册中心看到的地址 - final URL registedProviderUrl = providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameter(Constants.MONITOR_KEY); - return registedProviderUrl; + return providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameter(Constants.MONITOR_KEY); } private URL getSubscribedOverrideUrl(URL registedProviderUrl) { @@ -246,16 +244,17 @@ public Invoker refer(Class type, URL url) throws RpcException { 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); + if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1) { + return doRefer(getCluster("mergeable"), registry, type, url); + } else if ("*".equals(group)) { + return doRefer(getCluster("grouping"), registry, type, url); } } return doRefer(cluster, registry, type, url); } - private Cluster getMergeableCluster() { - return ExtensionLoader.getExtensionLoader(Cluster.class).getExtension("mergeable"); + private Cluster getCluster(String cluster) { + return ExtensionLoader.getExtensionLoader(Cluster.class).getExtension(cluster); } private Invoker doRefer(Cluster cluster, Registry registry, Class type, URL url) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java index fccca848247..37f6f8a6f92 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java @@ -46,11 +46,11 @@ private void handlerEvent(Channel channel, Request req) throws RemotingException } } - private Response handleRequest(ExchangeChannel channel, Request req) throws RemotingException { - Response.Builder builder = new Response.Builder(req.getId()); - builder.version(req.getVersion()); - if (req.isBroken()) { - Object data = req.getData(); + private Response handleRequest(ExchangeChannel channel, Request request) throws RemotingException { + Response.Builder builder = new Response.Builder(request.getId()); + builder.version(request.getVersion()); + if (request.isBroken()) { + Object data = request.getData(); String msg; if (data == null) msg = null; else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data); @@ -59,7 +59,7 @@ private Response handleRequest(ExchangeChannel channel, Request req) throws Remo builder.status(Response.BAD_REQUEST); return builder.build(); } - Object msg = req.getData(); + Object msg = request.getData(); try { Object result = handler.reply(channel, msg); builder.status(Response.OK).result(result); diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcContextMethodNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcContextMethodNameProvider.java new file mode 100644 index 00000000000..9760c4ed8ab --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcContextMethodNameProvider.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.rpc.RpcContext; + +public abstract class RpcContextMethodNameProvider { + + public String getMethodNameFromContext() { + return RpcContext.getContext().getMethodName(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index ddaf5a6f4e0..38867a2c2ad 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -18,7 +18,7 @@ public RpcTracker createRpcTracker(URL url) { if (protocol.equals("dubbo")) { rpcTracker = new DubboRpcTracker((BraveRpcTrackerEngine) RpcTrackerManager.getRpcTrackerEngine()); } else if (protocol.equals("http") || protocol.equals("hessian")) { - rpcTracker = new HttpRpcTracker(); + rpcTracker = new HttpRpcTracker((BraveRpcTrackerEngine) RpcTrackerManager.getRpcTrackerEngine()); } return rpcTracker; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java index 5ad7174423f..2e982e65f22 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java @@ -22,7 +22,7 @@ public boolean isTraceable() { @Override public Collection responseAnnotations() { - if (!response.returnSuccessfully()) { + if (!response.returnOK()) { KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); return Collections.singletonList(statusAnnotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java new file mode 100644 index 00000000000..718dc98c791 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java @@ -0,0 +1,20 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.rpc.RpcContext; +import com.alibaba.dubbo.tracker.RpcAttachment; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; + +public class AttachMethodNameInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + Request.Builder builder = request.newBuilder(); + builder.addHeader(RpcAttachment.Method.getName(), RpcContext.getContext().getMethodName()); + return chain.proceed(builder.build()); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java new file mode 100644 index 00000000000..864f7708dc2 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java @@ -0,0 +1,31 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.*; + +public class FacadeHttpRpcTracker implements RpcTracker { + + @Override + public ClientRequestInterceptor clientRequestInterceptor() { + return null; + } + + @Override + public ClientResponseInterceptor clientResponseInterceptor() { + return null; + } + + @Override + public ServerRequestInterceptor serverRequestInterceptor() { + return null; + } + + @Override + public ServerResponseInterceptor serverResponseInterceptor() { + return null; + } + + @Override + public RpcTrackerEngine trackerEngine() { + return null; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java deleted file mode 100644 index 0707e62b3a5..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestAdapter.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.github.kristofa.brave.*; -import com.github.kristofa.brave.http.HttpClientRequest; -import com.github.kristofa.brave.internal.Nullable; -import com.twitter.zipkin.gen.Endpoint; - -import java.net.URI; -import java.util.Collection; -import java.util.Collections; - -/** - * @author Xs - */ -public class HttpClientRequestAdapter implements ClientRequestAdapter { - - private final HttpClientRequest request; - private final DubboRequestSpanNameProvider spanNameProvider; - - public HttpClientRequestAdapter(HttpClientRequest request, DubboRequestSpanNameProvider spanNameProvider) { - this.request = request; - this.spanNameProvider = spanNameProvider; - } - - @Override - public String getSpanName() { - return spanNameProvider.spanName(); - } - - @Override - public void addSpanIdToRequest(@Nullable SpanId spanId) { - if (spanId == null) { - request.addHeader(RpcAttachment.Sampled.getName(), "0"); - } else { - request.addHeader(RpcAttachment.Sampled.getName(), "1"); - request.addHeader(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); - request.addHeader(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); - if (spanId.nullableParentId() != null) { - request.addHeader(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); - } - request.addHeader(RpcAttachment.Method.getName(), getSpanName()); - } - } - - @Override - public Collection requestAnnotations() { - URI uri = request.getUri(); - KeyValueAnnotation annotation = KeyValueAnnotation.create(TraceKeys.HTTP_URL, uri.toString()); - return Collections.singletonList(annotation); - } - - @Override - public Endpoint serverAddress() { - return null; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java deleted file mode 100644 index 845f0386dcb..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientRequestInterceptor.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; - -public interface HttpClientRequestInterceptor extends ClientRequestInterceptor { -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java deleted file mode 100644 index c3c42712c71..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpClientResponseInterceptor.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; - -/** - * @author Xs - */ -public interface HttpClientResponseInterceptor extends ClientResponseInterceptor { -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java deleted file mode 100644 index 47759e6534f..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRequestResponseInterceptor.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.github.kristofa.brave.ClientRequestInterceptor; -import com.github.kristofa.brave.ClientResponseInterceptor; -import com.github.kristofa.brave.http.SpanNameProvider; -import okhttp3.Interceptor; -import okhttp3.Response; - -import java.io.IOException; - -public class HttpRequestResponseInterceptor implements Interceptor { - - private final ClientRequestInterceptor clientRequestInterceptor; - private final ClientResponseInterceptor clientResponseInterceptor; - - public HttpRequestResponseInterceptor(ClientRequestInterceptor clientRequestInterceptor, - ClientResponseInterceptor clientResponseInterceptor, - SpanNameProvider spanNameProvider) { - this.clientRequestInterceptor = clientRequestInterceptor; - this.clientResponseInterceptor = clientResponseInterceptor; - this.spanNameProvider = spanNameProvider; - } - - private final SpanNameProvider spanNameProvider; - - @Override - public Response intercept(Chain chain) throws IOException { - return null; - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java index f006f94d0b6..3a942fc1e6b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java @@ -1,34 +1,21 @@ package com.alibaba.dubbo.tracker.zipkin.http; -import com.alibaba.dubbo.tracker.*; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngine; /** * @author Xs */ -public class HttpRpcTracker implements RpcTracker { +public class HttpRpcTracker extends FacadeHttpRpcTracker { - @Override - public ClientRequestInterceptor clientRequestInterceptor() { - return null; - } - - @Override - public ClientResponseInterceptor clientResponseInterceptor() { - return null; - } + private final BraveRpcTrackerEngine trackerEngine; - @Override - public ServerRequestInterceptor serverRequestInterceptor() { - return null; - } - - @Override - public ServerResponseInterceptor serverResponseInterceptor() { - return null; + public HttpRpcTracker(BraveRpcTrackerEngine trackerEngine) { + this.trackerEngine = trackerEngine; } @Override public RpcTrackerEngine trackerEngine() { - return null; + return trackerEngine; } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java new file mode 100644 index 00000000000..e5a555bdb55 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.RpcContextMethodNameProvider; +import com.github.kristofa.brave.http.HttpClientRequest; +import com.github.kristofa.brave.http.HttpRequest; +import com.github.kristofa.brave.http.HttpServerRequest; +import com.github.kristofa.brave.http.SpanNameProvider; + +public class HttpSpanNameProvider extends RpcContextMethodNameProvider implements SpanNameProvider { + + @Override + public String spanName(HttpRequest request) { + String spanName; + if (request instanceof HttpClientRequest) { + spanName = getMethodNameFromContext(); + } else if (request instanceof HttpServerRequest) { + spanName = getSpanNameFromHeader((HttpServerRequest) request); + } else { + throw new IllegalArgumentException("wrong type http request, " + request); + } + return spanName; + } + + + private String getSpanNameFromHeader(HttpServerRequest httpServerRequest) { + return httpServerRequest.getHttpHeaderValue(RpcAttachment.Method.getName()); + } + +} From f2eb26069b847a12340569c37a1ad388ca47dbef Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 22 Jan 2017 22:51:35 +0800 Subject: [PATCH 16/69] add execute request --- .../rpc/cluster/support/GroupingCluster.java | 16 - .../support/GroupingClusterInvoker.java | 22 - .../com.alibaba.dubbo.rpc.cluster.Cluster | 3 +- .../com/alibaba/dubbo/common/Constants.java | 7 +- .../common/extension/ExtensionLoader.java | 418 +++++++++--------- .../support/hessian/Hessian2ObjectInput.java | 167 ++++--- .../alibaba/dubbo/common/utils/UrlUtils.java | 75 ++-- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 4 +- .../integration/RegistryDirectory.java | 2 +- .../integration/RegistryProtocol.java | 7 +- .../dubbo/registry/dubbo/MockChannel.java | 44 +- .../dubbo/registry/dubbo/MockedClient.java | 101 +++-- .../remoting/exchange/ExchangeChannel.java | 29 +- .../remoting/exchange/ExchangeClient.java | 1 + .../dubbo/remoting/exchange/Message.java | 7 + .../dubbo/remoting/exchange/Request.java | 2 +- .../dubbo/remoting/exchange/Response.java | 2 +- .../exchange/codec/ExchangeCodec.java | 3 +- .../exchange/support/SimpleFuture.java | 100 ++--- .../support/header/HeaderExchangeChannel.java | 67 +++ .../header/HeaderExchangeChannelV2.java | 236 ---------- .../support/header/HeaderExchangeClient.java | 65 ++- .../header/HeaderExchangeClientV2.java | 191 -------- .../support/header/HeaderExchangeHandler.java | 63 ++- .../header/HeaderExchangeHandlerV2.java | 249 ----------- .../remoting/telnet/codec/TelnetCodec.java | 74 ++-- .../AbstractChannelHandlerDelegate.java | 2 +- .../transport/ChannelHandlerDelegate.java | 20 +- .../remoting/transport/DecodeHandler.java | 23 +- .../transport/codec/TransportCodec.java | 4 - .../dispatcher/ChannelEventRunnable.java | 57 ++- .../dispatcher/WrappedChannelHandler.java | 4 +- .../protocol/dubbo/DecodeableRpcResult.java | 1 - .../rpc/protocol/dubbo/DubboInvoker.java | 9 +- .../rpc/protocol/dubbo/DubboProtocol.java | 5 - .../dubbo/LazyConnectExchangeClient.java | 14 + .../dubbo/ReferenceCountExchangeClient.java | 22 +- .../alibaba/dubbo/tracker/TrackerKeys.java | 1 - 39 files changed, 808 insertions(+), 1311 deletions(-) delete mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java delete mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java deleted file mode 100644 index 0c697c7f64c..00000000000 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingCluster.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.alibaba.dubbo.rpc.cluster.support; - -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.cluster.Cluster; -import com.alibaba.dubbo.rpc.cluster.Directory; - -public class GroupingCluster implements Cluster { - - public final static String NAME = "grouping"; - - @Override - public Invoker join(Directory directory) throws RpcException { - return new GroupingClusterInvoker(directory); - } -} diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java deleted file mode 100644 index f9767187cb4..00000000000 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/GroupingClusterInvoker.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.alibaba.dubbo.rpc.cluster.support; - -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.cluster.Directory; -import com.alibaba.dubbo.rpc.cluster.LoadBalance; - -import java.util.List; - -public class GroupingClusterInvoker extends AbstractClusterInvoker { - - public GroupingClusterInvoker(Directory directory) { - super(directory); - } - - @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { - return null; - } -} diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster index 300fc79063c..54e85ed763b 100644 --- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster +++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster @@ -6,5 +6,4 @@ failback=com.alibaba.dubbo.rpc.cluster.support.FailbackCluster forking=com.alibaba.dubbo.rpc.cluster.support.ForkingCluster available=com.alibaba.dubbo.rpc.cluster.support.AvailableCluster mergeable=com.alibaba.dubbo.rpc.cluster.support.MergeableCluster -broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster -grouping=com.alibaba.dubbo.rpc.cluster.support.GroupingCluster \ No newline at end of file +broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 4ce3a7a4de9..09c28db60e1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -145,7 +145,7 @@ public class Constants { public static final int MAX_BUFFER_SIZE = 16 * 1024; - public static final int MIN_BUFFER_SIZE = 1 * 1024; + public static final int MIN_BUFFER_SIZE = 1024; public static final String REMOVE_VALUE_PREFIX = "-"; @@ -597,9 +597,4 @@ public class Constants { public static final String ENABLE_TRACE_KEY = "enableTrace"; - - /* - * private Constants(){ } - */ - } diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java index b3eaf68f2e1..2f69cd31207 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java @@ -15,23 +15,6 @@ */ package com.alibaba.dubbo.common.extension; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.regex.Pattern; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.support.ActivateComparator; @@ -42,6 +25,15 @@ import com.alibaba.dubbo.common.utils.Holder; import com.alibaba.dubbo.common.utils.StringUtils; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Pattern; + /** * Dubbo使用的扩展点获取。

*

    @@ -49,12 +41,10 @@ *
  • 自动Wrap上扩展点的Wrap类。
  • *
  • 缺省获得的的扩展点是一个Adaptive Instance。 *
- * - * @see JDK5.0的自动发现机制实现 - * + * * @author william.liangf * @author ding.lid - * + * @see JDK5.0的自动发现机制实现 * @see com.alibaba.dubbo.common.extension.SPI * @see com.alibaba.dubbo.common.extension.Adaptive * @see com.alibaba.dubbo.common.extension.Activate @@ -62,28 +52,26 @@ public class ExtensionLoader { private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class); - + private static final String SERVICES_DIRECTORY = "META-INF/services/"; private static final String DUBBO_DIRECTORY = "META-INF/dubbo/"; - + private static final String DUBBO_INTERNAL_DIRECTORY = DUBBO_DIRECTORY + "internal/"; private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); - + private static final ConcurrentMap, ExtensionLoader> EXTENSION_LOADERS = new ConcurrentHashMap, ExtensionLoader>(); private static final ConcurrentMap, Object> EXTENSION_INSTANCES = new ConcurrentHashMap, Object>(); - // ============================== - private final Class type; private final ExtensionFactory objectFactory; private final ConcurrentMap, String> cachedNames = new ConcurrentHashMap, String>(); - - private final Holder>> cachedClasses = new Holder>>(); + + private final Holder>> cachedClasses = new Holder>>(); private final Map cachedActivates = new ConcurrentHashMap(); @@ -97,25 +85,25 @@ public class ExtensionLoader { private volatile Throwable createAdaptiveInstanceError; private Set> cachedWrapperClasses; - + private Map exceptions = new ConcurrentHashMap(); - + private static boolean withExtensionAnnotation(Class type) { return type.isAnnotationPresent(SPI.class); } - + @SuppressWarnings("unchecked") public static ExtensionLoader getExtensionLoader(Class type) { if (type == null) throw new IllegalArgumentException("Extension type == null"); - if(!type.isInterface()) { + if (!type.isInterface()) { throw new IllegalArgumentException("Extension type(" + type + ") is not interface!"); } - if(!withExtensionAnnotation(type)) { - throw new IllegalArgumentException("Extension type(" + type + + if (!withExtensionAnnotation(type)) { + throw new IllegalArgumentException("Extension type(" + type + ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!"); } - + ExtensionLoader loader = (ExtensionLoader) EXTENSION_LOADERS.get(type); if (loader == null) { EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type)); @@ -128,7 +116,7 @@ private ExtensionLoader(Class type) { this.type = type; objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension()); } - + public String getExtensionName(T extensionInstance) { return getExtensionName(extensionInstance.getClass()); } @@ -156,10 +144,10 @@ public List getActivateExtension(URL url, String key) { * getActivateExtension(url, values, null); * * - * @see #getActivateExtension(com.alibaba.dubbo.common.URL, String[], String) - * @param url url + * @param url url * @param values extension point names * @return extension list which are activated + * @see #getActivateExtension(com.alibaba.dubbo.common.URL, String[], String) */ public List getActivateExtension(URL url, String[] values) { return getActivateExtension(url, values, null); @@ -170,11 +158,11 @@ public List getActivateExtension(URL url, String[] values) { * getActivateExtension(url, url.getParameter(key).split(","), null); * * - * @see #getActivateExtension(com.alibaba.dubbo.common.URL, String[], String) - * @param url url - * @param key url parameter key which used to get extension point names + * @param url url + * @param key url parameter key which used to get extension point names * @param group group * @return extension list which are activated. + * @see #getActivateExtension(com.alibaba.dubbo.common.URL, String[], String) */ public List getActivateExtension(URL url, String key, String group) { String value = url.getParameter(key); @@ -184,24 +172,24 @@ public List getActivateExtension(URL url, String key, String group) { /** * Get activate extensions. * - * @see com.alibaba.dubbo.common.extension.Activate - * @param url url + * @param url url * @param values extension point names - * @param group group + * @param group group * @return extension list which are activated + * @see com.alibaba.dubbo.common.extension.Activate */ public List getActivateExtension(URL url, String[] values, String group) { List exts = new ArrayList(); List names = values == null ? new ArrayList(0) : Arrays.asList(values); - if (! names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { + if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { getExtensionClasses(); for (Map.Entry entry : cachedActivates.entrySet()) { String name = entry.getKey(); Activate activate = entry.getValue(); if (isMatchGroup(group, activate.group())) { T ext = getExtension(name); - if (! names.contains(name) - && ! names.contains(Constants.REMOVE_VALUE_PREFIX + name) + if (!names.contains(name) + && !names.contains(Constants.REMOVE_VALUE_PREFIX + name) && isActive(activate, url)) { exts.add(ext); } @@ -210,27 +198,27 @@ && isActive(activate, url)) { Collections.sort(exts, ActivateComparator.COMPARATOR); } List usrs = new ArrayList(); - for (int i = 0; i < names.size(); i ++) { - String name = names.get(i); - if (! name.startsWith(Constants.REMOVE_VALUE_PREFIX) - && ! names.contains(Constants.REMOVE_VALUE_PREFIX + name)) { - if (Constants.DEFAULT_KEY.equals(name)) { - if (usrs.size() > 0) { - exts.addAll(0, usrs); - usrs.clear(); - } - } else { - T ext = getExtension(name); - usrs.add(ext); - } + for (int i = 0; i < names.size(); i++) { + String name = names.get(i); + if (!name.startsWith(Constants.REMOVE_VALUE_PREFIX) + && !names.contains(Constants.REMOVE_VALUE_PREFIX + name)) { + if (Constants.DEFAULT_KEY.equals(name)) { + if (usrs.size() > 0) { + exts.addAll(0, usrs); + usrs.clear(); + } + } else { + T ext = getExtension(name); + usrs.add(ext); + } } } if (usrs.size() > 0) { - exts.addAll(usrs); + exts.addAll(usrs); } return exts; } - + private boolean isMatchGroup(String group, String[] groups) { if (group == null || group.length() == 0) { return true; @@ -244,7 +232,7 @@ private boolean isMatchGroup(String group, String[] groups) { } return false; } - + private boolean isActive(Activate activate, URL url) { String[] keys = activate.value(); if (keys == null || keys.length == 0) { @@ -265,7 +253,7 @@ private boolean isActive(Activate activate, URL url) { /** * 返回扩展点实例,如果没有指定的扩展点或是还没加载(即实例化)则返回null。注意:此方法不会触发扩展点的加载。 - *

+ *

* 一般应该调用{@link #getExtension(String)}方法获得扩展,这个方法会触发扩展点加载。 * * @see #getExtension(String) @@ -284,7 +272,7 @@ public T getLoadedExtension(String name) { /** * 返回已经加载的扩展点的名字。 - *

+ *

* 一般应该调用{@link #getSupportedExtensions()}方法获得扩展,这个方法会返回所有的扩展点。 * * @see #getSupportedExtensions() @@ -299,99 +287,98 @@ public Set getLoadedExtensions() { * @param name * @return */ - @SuppressWarnings("unchecked") - public T getExtension(String name) { - if (name == null || name.length() == 0) - throw new IllegalArgumentException("Extension name == null"); - if ("true".equals(name)) { - return getDefaultExtension(); - } - Holder holder = cachedInstances.get(name); - if (holder == null) { - cachedInstances.putIfAbsent(name, new Holder()); - holder = cachedInstances.get(name); - } - Object instance = holder.get(); - if (instance == null) { - synchronized (holder) { - instance = holder.get(); - if (instance == null) { - instance = createExtension(name); - holder.set(instance); - } - } - } - return (T) instance; - } - - /** - * 返回缺省的扩展,如果没有设置则返回null。 - */ - public T getDefaultExtension() { - getExtensionClasses(); - if(null == cachedDefaultName || cachedDefaultName.length() == 0 + @SuppressWarnings("unchecked") + public T getExtension(String name) { + if (name == null || name.length() == 0) + throw new IllegalArgumentException("Extension name == null"); + if ("true".equals(name)) { + return getDefaultExtension(); + } + Holder holder = cachedInstances.get(name); + if (holder == null) { + cachedInstances.putIfAbsent(name, new Holder()); + holder = cachedInstances.get(name); + } + Object instance = holder.get(); + if (instance == null) { + synchronized (cachedInstances) { + instance = holder.get(); + if (instance == null) { + instance = createExtension(name); + holder.set(instance); + } + } + } + return (T) instance; + } + + /** + * 返回缺省的扩展,如果没有设置则返回null。 + */ + public T getDefaultExtension() { + getExtensionClasses(); + if (null == cachedDefaultName || cachedDefaultName.length() == 0 || "true".equals(cachedDefaultName)) { return null; } return getExtension(cachedDefaultName); - } - - public boolean hasExtension(String name) { - if (name == null || name.length() == 0) - throw new IllegalArgumentException("Extension name == null"); - try { - return getExtensionClass(name) != null; - } catch (Throwable t) { - return false; - } - } - - public Set getSupportedExtensions() { + } + + public boolean hasExtension(String name) { + if (name == null || name.length() == 0) + throw new IllegalArgumentException("Extension name == null"); + try { + return getExtensionClass(name) != null; + } catch (Throwable t) { + return false; + } + } + + public Set getSupportedExtensions() { Map> clazzes = getExtensionClasses(); return Collections.unmodifiableSet(new TreeSet(clazzes.keySet())); } - - /** - * 返回缺省的扩展点名,如果没有设置缺省则返回null。 - */ - public String getDefaultExtensionName() { - getExtensionClasses(); - return cachedDefaultName; - } + + /** + * 返回缺省的扩展点名,如果没有设置缺省则返回null。 + */ + public String getDefaultExtensionName() { + getExtensionClasses(); + return cachedDefaultName; + } /** * 编程方式添加新扩展点。 * - * @param name 扩展点名 + * @param name 扩展点名 * @param clazz 扩展点类 * @throws IllegalStateException 要添加扩展点名已经存在。 */ public void addExtension(String name, Class clazz) { getExtensionClasses(); // load classes - if(!type.isAssignableFrom(clazz)) { + if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + "not implement Extension " + type); } - if(clazz.isInterface()) { + if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + "can not be interface!"); } - if(!clazz.isAnnotationPresent(Adaptive.class)) { - if(StringUtils.isBlank(name)) { + if (!clazz.isAnnotationPresent(Adaptive.class)) { + if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } - if(cachedClasses.get().containsKey(name)) { + if (cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " already existed(Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); - } - else { - if(cachedAdaptiveClass != null) { + } else { + if (cachedAdaptiveClass != null) { throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!"); } @@ -402,7 +389,7 @@ public void addExtension(String name, Class clazz) { /** * 编程方式添加替换已有扩展点。 * - * @param name 扩展点名 + * @param name 扩展点名 * @param clazz 扩展点类 * @throws IllegalStateException 要添加扩展点名已经存在。 * @deprecated 不推荐应用使用,一般只在测试时可以使用 @@ -411,20 +398,20 @@ public void addExtension(String name, Class clazz) { public void replaceExtension(String name, Class clazz) { getExtensionClasses(); // load classes - if(!type.isAssignableFrom(clazz)) { + if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + "not implement Extension " + type); } - if(clazz.isInterface()) { + if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + "can not be interface!"); } - if(!clazz.isAnnotationPresent(Adaptive.class)) { - if(StringUtils.isBlank(name)) { + if (!clazz.isAnnotationPresent(Adaptive.class)) { + if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } - if(!cachedClasses.get().containsKey(name)) { + if (!cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " not existed(Extension " + type + ")!"); } @@ -432,9 +419,8 @@ public void replaceExtension(String name, Class clazz) { cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); cachedInstances.remove(name); - } - else { - if(cachedAdaptiveClass == null) { + } else { + if (cachedAdaptiveClass == null) { throw new IllegalStateException("Adaptive Extension not existed(Extension " + type + ")!"); } @@ -447,7 +433,7 @@ public void replaceExtension(String name, Class clazz) { public T getAdaptiveExtension() { Object instance = cachedAdaptiveInstance.get(); if (instance == null) { - if(createAdaptiveInstanceError == null) { + if (createAdaptiveInstanceError == null) { synchronized (cachedAdaptiveInstance) { instance = cachedAdaptiveInstance.get(); if (instance == null) { @@ -460,8 +446,7 @@ public T getAdaptiveExtension() { } } } - } - else { + } else { throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError); } } @@ -480,12 +465,12 @@ private IllegalStateException findException(String name) { int i = 1; for (Map.Entry entry : exceptions.entrySet()) { - if(i == 1) { + if (i == 1) { buf.append(", possible causes: "); } buf.append("\r\n("); - buf.append(i ++); + buf.append(i++); buf.append(") "); buf.append(entry.getKey()); buf.append(":\r\n"); @@ -519,7 +504,7 @@ private T createExtension(String name) { type + ") could not be instantiated: " + t.getMessage(), t); } } - + private T injectExtension(T instance) { try { if (objectFactory != null) { @@ -546,19 +531,19 @@ private T injectExtension(T instance) { } return instance; } - - private Class getExtensionClass(String name) { - if (type == null) - throw new IllegalArgumentException("Extension type == null"); - if (name == null) - throw new IllegalArgumentException("Extension name == null"); - Class clazz = getExtensionClasses().get(name); - if (clazz == null) - throw new IllegalStateException("No such extension \"" + name + "\" for " + type.getName() + "!"); - return clazz; - } - - private Map> getExtensionClasses() { + + private Class getExtensionClass(String name) { + if (type == null) + throw new IllegalArgumentException("Extension type == null"); + if (name == null) + throw new IllegalArgumentException("Extension name == null"); + Class clazz = getExtensionClasses().get(name); + if (clazz == null) + throw new IllegalStateException("No such extension \"" + name + "\" for " + type.getName() + "!"); + return clazz; + } + + private Map> getExtensionClasses() { Map> classes = cachedClasses.get(); if (classes == null) { synchronized (cachedClasses) { @@ -570,30 +555,30 @@ private Map> getExtensionClasses() { } } return classes; - } + } // 此方法已经getExtensionClasses方法同步过。 private Map> loadExtensionClasses() { final SPI defaultAnnotation = type.getAnnotation(SPI.class); - if(defaultAnnotation != null) { + if (defaultAnnotation != null) { String value = defaultAnnotation.value(); - if(value != null && (value = value.trim()).length() > 0) { + if (value != null && (value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); - if(names.length > 1) { + if (names.length > 1) { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } - if(names.length == 1) cachedDefaultName = names[0]; + if (names.length == 1) cachedDefaultName = names[0]; } } - + Map> extensionClasses = new HashMap>(); loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY); loadFile(extensionClasses, DUBBO_DIRECTORY); loadFile(extensionClasses, SERVICES_DIRECTORY); return extensionClasses; } - + private void loadFile(Map> extensionClasses, String dir) { String fileName = dir + type.getName(); try { @@ -625,15 +610,15 @@ private void loadFile(Map> extensionClasses, String dir) { } if (line.length() > 0) { Class clazz = Class.forName(line, true, classLoader); - if (! type.isAssignableFrom(clazz)) { + if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error when load extension class(interface: " + - type + ", class line: " + clazz.getName() + "), class " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface."); } if (clazz.isAnnotationPresent(Adaptive.class)) { - if(cachedAdaptiveClass == null) { + if (cachedAdaptiveClass == null) { cachedAdaptiveClass = clazz; - } else if (! cachedAdaptiveClass.equals(clazz)) { + } else if (!cachedAdaptiveClass.equals(clazz)) { throw new IllegalStateException("More than 1 adaptive class found: " + cachedAdaptiveClass.getClass().getName() + ", " + clazz.getClass().getName()); @@ -667,7 +652,7 @@ private void loadFile(Map> extensionClasses, String dir) { cachedActivates.put(names[0], activate); } for (String n : names) { - if (! cachedNames.containsKey(clazz)) { + if (!cachedNames.containsKey(clazz)) { cachedNames.put(clazz, n); } Class c = extensionClasses.get(n); @@ -692,7 +677,7 @@ private void loadFile(Map> extensionClasses, String dir) { } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + - type + ", class file: " + url + ") in " + url, t); + type + ", class file: " + url + ") in " + url, t); } } // end of while urls } @@ -701,7 +686,7 @@ private void loadFile(Map> extensionClasses, String dir) { type + ", description file: " + fileName + ").", t); } } - + @SuppressWarnings("deprecation") private String findAnnotationName(Class clazz) { com.alibaba.dubbo.common.Extension extension = clazz.getAnnotation(com.alibaba.dubbo.common.Extension.class); @@ -714,7 +699,7 @@ private String findAnnotationName(Class clazz) { } return extension.value(); } - + @SuppressWarnings("unchecked") private T createAdaptiveExtension() { try { @@ -723,7 +708,7 @@ private T createAdaptiveExtension() { throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e); } } - + private Class getAdaptiveExtensionClass() { getExtensionClasses(); if (cachedAdaptiveClass != null) { @@ -731,32 +716,32 @@ private Class getAdaptiveExtensionClass() { } return cachedAdaptiveClass = createAdaptiveExtensionClass(); } - + private Class createAdaptiveExtensionClass() { String code = createAdaptiveExtensionClassCode(); ClassLoader classLoader = findClassLoader(); com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension(); return compiler.compile(code, classLoader); } - + private String createAdaptiveExtensionClassCode() { StringBuilder codeBuilder = new StringBuilder(); Method[] methods = type.getMethods(); boolean hasAdaptiveAnnotation = false; - for(Method m : methods) { - if(m.isAnnotationPresent(Adaptive.class)) { + for (Method m : methods) { + if (m.isAnnotationPresent(Adaptive.class)) { hasAdaptiveAnnotation = true; break; } } // 完全没有Adaptive方法,则不需要生成Adaptive类 - if(! hasAdaptiveAnnotation) + if (!hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); - + codeBuilder.append("package " + type.getPackage().getName() + ";"); codeBuilder.append("\nimport " + ExtensionLoader.class.getName() + ";"); codeBuilder.append("\npublic class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {"); - + for (Method method : methods) { Class rt = method.getReturnType(); Class[] pts = method.getParameterTypes(); @@ -780,16 +765,16 @@ private String createAdaptiveExtensionClassCode() { if (urlTypeIndex != -1) { // Null Point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");", - urlTypeIndex); + urlTypeIndex); code.append(s); - - s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex); + + s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex); code.append(s); } // 参数没有URL类型 else { String attribMethod = null; - + // 找到参数的URL属性 LBL_PTS: for (int i = 0; i < pts.length; ++i) { @@ -807,81 +792,78 @@ private String createAdaptiveExtensionClassCode() { } } } - if(attribMethod == null) { + if (attribMethod == null) { throw new IllegalStateException("fail to create adative class for interface " + type.getName() - + ": not found url parameter or url attribute in parameters of method " + method.getName()); + + ": not found url parameter or url attribute in parameters of method " + method.getName()); } - + // Null point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");", - urlTypeIndex, pts[urlTypeIndex].getName()); + urlTypeIndex, pts[urlTypeIndex].getName()); code.append(s); s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");", - urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod); + urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod); code.append(s); - s = String.format("%s url = arg%d.%s();",URL.class.getName(), urlTypeIndex, attribMethod); + s = String.format("%s url = arg%d.%s();", URL.class.getName(), urlTypeIndex, attribMethod); code.append(s); } - + String[] value = adaptiveAnnotation.value(); // 没有设置Key,则使用“扩展点接口名的点分隔 作为Key - if(value.length == 0) { + if (value.length == 0) { char[] charArray = type.getSimpleName().toCharArray(); StringBuilder sb = new StringBuilder(128); for (int i = 0; i < charArray.length; i++) { - if(Character.isUpperCase(charArray[i])) { - if(i != 0) { + if (Character.isUpperCase(charArray[i])) { + if (i != 0) { sb.append("."); } sb.append(Character.toLowerCase(charArray[i])); - } - else { + } else { sb.append(charArray[i]); } } - value = new String[] {sb.toString()}; + value = new String[]{sb.toString()}; } - + boolean hasInvocation = false; for (int i = 0; i < pts.length; ++i) { if (pts[i].getName().equals("com.alibaba.dubbo.rpc.Invocation")) { // Null Point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i); code.append(s); - s = String.format("\nString methodName = arg%d.getMethodName();", i); + s = String.format("\nString methodName = arg%d.getMethodName();", i); code.append(s); hasInvocation = true; break; } } - + String defaultExtName = cachedDefaultName; String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { - if(i == value.length - 1) { - if(null != defaultExtName) { - if(!"protocol".equals(value[i])) - if (hasInvocation) + if (i == value.length - 1) { + if (null != defaultExtName) { + if (!"protocol".equals(value[i])) + if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); - } - else { - if(!"protocol".equals(value[i])) - if (hasInvocation) + } else { + if (!"protocol".equals(value[i])) + if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\")", value[i]); else getNameCode = "url.getProtocol()"; } - } - else { - if(!"protocol".equals(value[i])) - if (hasInvocation) + } else { + if (!"protocol".equals(value[i])) + if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); @@ -892,14 +874,14 @@ private String createAdaptiveExtensionClassCode() { code.append("\nString extName = ").append(getNameCode).append(";"); // check extName == null? String s = String.format("\nif(extName == null) " + - "throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");", + "throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");", type.getName(), Arrays.toString(value)); code.append(s); - + s = String.format("\n%s extension = (% 0) { codeBuilder.append(", "); } @@ -927,7 +909,7 @@ private String createAdaptiveExtensionClassCode() { codeBuilder.append(")"); if (ets.length > 0) { codeBuilder.append(" throws "); - for (int i = 0; i < ets.length; i ++) { + for (int i = 0; i < ets.length; i++) { if (i > 0) { codeBuilder.append(", "); } @@ -946,12 +928,12 @@ private String createAdaptiveExtensionClassCode() { } private static ClassLoader findClassLoader() { - return ExtensionLoader.class.getClassLoader(); + return ExtensionLoader.class.getClassLoader(); } - + @Override public String toString() { return this.getClass().getName() + "[" + type.getName() + "]"; } - + } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/hessian/Hessian2ObjectInput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/hessian/Hessian2ObjectInput.java index c3db30038af..534a8859099 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/hessian/Hessian2ObjectInput.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/hessian/Hessian2ObjectInput.java @@ -1,102 +1,89 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.common.serialize.support.hessian; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; - import com.alibaba.com.caucho.hessian.io.Hessian2Input; import com.alibaba.dubbo.common.serialize.ObjectInput; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; + /** * Hessian2 Object input. - * + * * @author qian.lei */ -public class Hessian2ObjectInput implements ObjectInput -{ - private final Hessian2Input mH2i; - - public Hessian2ObjectInput(InputStream is) - { - mH2i = new Hessian2Input(is); - mH2i.setSerializerFactory(Hessian2SerializerFactory.SERIALIZER_FACTORY); - } - - public boolean readBool() throws IOException - { - return mH2i.readBoolean(); - } - - public byte readByte() throws IOException - { - return (byte)mH2i.readInt(); - } - - public short readShort() throws IOException - { - return (short)mH2i.readInt(); - } - - public int readInt() throws IOException - { - return mH2i.readInt(); - } - - public long readLong() throws IOException - { - return mH2i.readLong(); - } - - public float readFloat() throws IOException - { - return (float)mH2i.readDouble(); - } - - public double readDouble() throws IOException - { - return mH2i.readDouble(); - } - - public byte[] readBytes() throws IOException - { - return mH2i.readBytes(); - } - - public String readUTF() throws IOException - { - return mH2i.readString(); - } - - public Object readObject() throws IOException - { - return mH2i.readObject(); - } - - @SuppressWarnings("unchecked") - public T readObject(Class cls) throws IOException, - ClassNotFoundException { - return (T) mH2i.readObject(cls); - } - - public T readObject(Class cls, Type type) throws IOException,ClassNotFoundException - { - return readObject(cls); - } +public class Hessian2ObjectInput implements ObjectInput { + private final Hessian2Input mH2i; + + public Hessian2ObjectInput(InputStream is) { + mH2i = new Hessian2Input(is); + mH2i.setSerializerFactory(Hessian2SerializerFactory.SERIALIZER_FACTORY); + } + + public boolean readBool() throws IOException { + return mH2i.readBoolean(); + } + + public byte readByte() throws IOException { + return (byte) mH2i.readInt(); + } + + public short readShort() throws IOException { + return (short) mH2i.readInt(); + } + + public int readInt() throws IOException { + return mH2i.readInt(); + } + + public long readLong() throws IOException { + return mH2i.readLong(); + } + + public float readFloat() throws IOException { + return (float) mH2i.readDouble(); + } + + public double readDouble() throws IOException { + return mH2i.readDouble(); + } + + public byte[] readBytes() throws IOException { + return mH2i.readBytes(); + } + + public String readUTF() throws IOException { + return mH2i.readString(); + } + + public Object readObject() throws IOException { + return mH2i.readObject(); + } + + @SuppressWarnings("unchecked") + public T readObject(Class cls) throws IOException, + ClassNotFoundException { + return (T) mH2i.readObject(cls); + } + + public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { + return readObject(cls); + } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java index 8466ebb973f..7712530c1c1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -15,15 +15,11 @@ */ package com.alibaba.dubbo.common.utils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import java.util.*; + public class UrlUtils { public static URL parseURL(String address, Map defaults) { @@ -305,7 +301,7 @@ public static List revertForbid(List forbid, Set subscribed if (forbid != null && forbid.size() > 0) { List newForbid = new ArrayList(); for (String serviceName : forbid) { - if (! serviceName.contains(":") && ! serviceName.contains("/")) { + if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); @@ -334,10 +330,10 @@ public static URL getEmptyUrl(String service, String category) { version = service.substring(i + 1); service = service.substring(0, i); } - return URL.valueOf(Constants.EMPTY_PROTOCOL + "://0.0.0.0/" + service + "?" - + Constants.CATEGORY_KEY + "=" + category - + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group) - + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version)); + return URL.valueOf(Constants.EMPTY_PROTOCOL + "://0.0.0.0/" + service + "?" + + Constants.CATEGORY_KEY + "=" + category + + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group) + + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version)); } public static boolean isMatchCategory(String category, String categories) { @@ -346,7 +342,7 @@ public static boolean isMatchCategory(String category, String categories) { } else if (categories.contains(Constants.ANY_VALUE)) { return true; } else if (categories.contains(Constants.REMOVE_VALUE_PREFIX)) { - return ! categories.contains(Constants.REMOVE_VALUE_PREFIX + category); + return !categories.contains(Constants.REMOVE_VALUE_PREFIX + category); } else { return categories.contains(category); } @@ -355,49 +351,54 @@ public static boolean isMatchCategory(String category, String categories) { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); - if( ! (Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface)) ) return false; - - if (! isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), + if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) + return false; + + if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } - if (! providerUrl.getParameter(Constants.ENABLED_KEY, true) - && ! Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { + if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) + && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } - + String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); - + String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); - return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) - && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) - && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); + return (Constants.ANY_VALUE.equals(consumerGroup) || + StringUtils.isEquals(consumerGroup, providerGroup) || + StringUtils.isContains(consumerGroup, providerGroup)) && + (Constants.ANY_VALUE.equals(consumerVersion) || + StringUtils.isEquals(consumerVersion, providerVersion)) && + (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || + StringUtils.isEquals(consumerClassifier, providerClassifier)); } - + public static boolean isMatchGlobPattern(String pattern, String value, URL param) { if (param != null && pattern.startsWith("$")) { pattern = param.getRawParameter(pattern.substring(1)); } return isMatchGlobPattern(pattern, value); } - + public static boolean isMatchGlobPattern(String pattern, String value) { if ("*".equals(pattern)) return true; - if((pattern == null || pattern.length() == 0) - && (value == null || value.length() == 0)) + if ((pattern == null || pattern.length() == 0) + && (value == null || value.length() == 0)) return true; - if((pattern == null || pattern.length() == 0) - || (value == null || value.length() == 0)) + if ((pattern == null || pattern.length() == 0) + || (value == null || value.length() == 0)) return false; - + int i = pattern.lastIndexOf('*'); // 没有找到星号 - if(i == -1) { + if (i == -1) { return value.equals(pattern); } // 星号在末尾 @@ -417,12 +418,12 @@ else if (i == 0) { } public static boolean isServiceKeyMatch(URL pattern, URL value) { - return pattern.getParameter(Constants.INTERFACE_KEY).equals( - value.getParameter(Constants.INTERFACE_KEY)) - && isItemMatch(pattern.getParameter(Constants.GROUP_KEY), - value.getParameter(Constants.GROUP_KEY)) - && isItemMatch(pattern.getParameter(Constants.VERSION_KEY), - value.getParameter(Constants.VERSION_KEY)); + return pattern.getParameter(Constants.INTERFACE_KEY).equals( + value.getParameter(Constants.INTERFACE_KEY)) + && isItemMatch(pattern.getParameter(Constants.GROUP_KEY), + value.getParameter(Constants.GROUP_KEY)) + && isItemMatch(pattern.getParameter(Constants.VERSION_KEY), + value.getParameter(Constants.VERSION_KEY)); } /** @@ -430,7 +431,7 @@ && isItemMatch(pattern.getParameter(Constants.VERSION_KEY), * * @param pattern pattern * @param value value - * @return true if match otherwise false + * @return true if match otherwise false */ static boolean isItemMatch(String pattern, String value) { if (pattern == null) { diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index b369bc867fc..494aff3c824 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -12,7 +12,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index e49483c0032..4830404ef2b 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -58,11 +58,11 @@ - + - + diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java index d23028553a4..23c5a1fe7ac 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryDirectory.java @@ -98,7 +98,7 @@ public RegistryDirectory(Class serviceType, URL url) { this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = url.setPath(url.getServiceInterface()).clearParameters().addParameters(queryMap).removeParameter(Constants.MONITOR_KEY); String group = directoryUrl.getParameter(Constants.GROUP_KEY, ""); - this.multiGroup = group != null && ("*".equals(group) || group.contains(",") || group.equals("grouping")); + this.multiGroup = group != null && (group.contains(",")); String methods = queryMap.get(Constants.METHODS_KEY); this.serviceMethods = methods == null ? null : Constants.COMMA_SPLIT_PATTERN.split(methods); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java index 23a6b1f2e9e..a1426464e5d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java @@ -244,11 +244,12 @@ public Invoker refer(Class type, URL url) throws RpcException { 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) { + if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1 || Constants.ANY_VALUE.equals(group)) { return doRefer(getCluster("mergeable"), registry, type, url); - } else if ("*".equals(group)) { - return doRefer(getCluster("grouping"), registry, type, url); } +// else if (Constants.GROUPING.equals(group)) { +// return doRefer(getCluster("grouping"), registry, type, url); +// } } return doRefer(cluster, registry, type, url); } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java index 19e1b5bdcb9..e9e3e931711 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.registry.dubbo; import java.net.InetSocketAddress; @@ -20,9 +20,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.exchange.*; public class MockChannel implements ExchangeChannel { @@ -80,6 +78,16 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept return null; } + @Override + public Response execute(Request request) throws RemotingException { + return null; + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + return null; + } + public ExchangeHandler getExchangeHandler() { return null; } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java index 3f24b30c458..ee819a0abcd 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java @@ -15,9 +15,6 @@ */ package com.alibaba.dubbo.registry.dubbo; -import java.net.InetSocketAddress; -import java.util.Map; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -26,39 +23,42 @@ import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.Replier; +import java.net.InetSocketAddress; +import java.util.Map; + /** * MockedClient - * + * * @author william.liangf */ public class MockedClient implements ExchangeClient { - + //private String host; //private int port; - + private boolean connected; - + private Object received; private Object sent; - + private Object invoked; - + private Replier handler; - + private InetSocketAddress address; - + private boolean closed = false; //private ChannelListener listener; - + public MockedClient(String host, int port, boolean connected) { - this(host, port, connected, null); + this(host, port, connected, null); } public MockedClient(String host, int port, boolean connected, Object received) { - this.address = new InetSocketAddress(host, port); + this.address = new InetSocketAddress(host, port); this.connected = connected; this.received = received; } @@ -84,17 +84,30 @@ public ResponseFuture request(Object msg, int timeout) throws RemotingException public Object get() throws RemotingException { return received; } + public Object get(int timeoutInMillis) throws RemotingException { return received; } + public boolean isDone() { return true; } + public void setCallback(ResponseCallback callback) { } }; } + @Override + public Response execute(Request request) throws RemotingException { + return null; + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + return null; + } + public void registerHandler(Replier handler) { this.handler = handler; } @@ -127,39 +140,39 @@ public Object getInvoked() { return invoked; } - public InetSocketAddress getRemoteAddress() { - return address; - } + public InetSocketAddress getRemoteAddress() { + return address; + } - public String getName() { - return "mocked"; - } + public String getName() { + return "mocked"; + } - public InetSocketAddress getLocalAddress() { - return null; - } + public InetSocketAddress getLocalAddress() { + return null; + } - public void setTimeout(int timeout) { - } + public void setTimeout(int timeout) { + } - public int getTimeout() { - return 0; - } + public int getTimeout() { + return 0; + } - public void close(int timeout) { - close(); - } + public void close(int timeout) { + close(); + } - public boolean isOpen() { - return closed; - } + public boolean isOpen() { + return closed; + } - public Codec getCodec() { - return null; - } + public Codec getCodec() { + return null; + } - public void setCodec(Codec codec) { - } + public void setCodec(Codec codec) { + } public void setHost(String host) { } @@ -213,7 +226,7 @@ public Object getAttribute(String key) { } public void setAttribute(String key, Object value) { - + } public boolean hasAttribute(String key) { @@ -225,8 +238,9 @@ public boolean isClosed() { } public void removeAttribute(String key) { - + } + /** * @return the received */ @@ -257,4 +271,9 @@ public void reset(URL url) { @Deprecated public void reset(com.alibaba.dubbo.common.Parameters parameters) { } + + @Override + public void addInterceptor(Interceptor interceptor) { + // NOP + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java index b62cb2c7633..9a63c4c823f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java @@ -20,14 +20,14 @@ /** * ExchangeChannel. (API/SPI, Prototype, ThreadSafe) - * + * * @author william.liangf */ public interface ExchangeChannel extends Channel { /** * send request. - * + * * @param request * @return response future * @throws RemotingException @@ -36,7 +36,7 @@ public interface ExchangeChannel extends Channel { /** * send request. - * + * * @param request * @param timeout * @return response future @@ -44,16 +44,35 @@ public interface ExchangeChannel extends Channel { */ ResponseFuture request(Object request, int timeout) throws RemotingException; + /** + * send and receive + * + * @param request + * @return + * @throws RemotingException + */ + Response execute(Request request) throws RemotingException; + + /** + * send and receive + * + * @param request + * @param timeout + * @return + * @throws RemotingException + */ + Response execute(Request request, int timeout) throws RemotingException; + /** * get message handler. - * + * * @return message handler */ ExchangeHandler getExchangeHandler(); /** * graceful close. - * + * * @param timeout */ void close(int timeout); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java index 73f80e8507f..67c8b54e4b8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java @@ -24,4 +24,5 @@ */ public interface ExchangeClient extends Client, ExchangeChannel { + void addInterceptor(Interceptor interceptor); } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java new file mode 100644 index 00000000000..2a802eaf83a --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.remoting.exchange; + +/** + * @author Xs. + */ +public class Message { +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java index 29bd640b4f9..fe48baf16d8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java @@ -25,7 +25,7 @@ * @author qian.lei * @author william.liangf */ -public class Request { +public class Request extends Message { public static final String HEARTBEAT_EVENT = null; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java index 3c6f838e7d2..ae812670aab 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java @@ -21,7 +21,7 @@ * @author qian.lei * @author william.liangf */ -public class Response { +public class Response extends Message { public static final String HEARTBEAT_EVENT = null; public static final String READONLY_EVENT = "R"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index dd3ab8c1454..517ada17c95 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -92,8 +92,7 @@ public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. - if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { + if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java index c09a0f04c7a..d62ef998e50 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java @@ -1,51 +1,51 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.exchange.support; - -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; - -/** - * SimpleFuture - * - * @author william.liangf - */ -public class SimpleFuture implements ResponseFuture { - - private final Object value; - - public SimpleFuture(Object value){ - this.value = value; - } - - public Object get() throws RemotingException { - return value; - } - - public Object get(int timeoutInMillis) throws RemotingException { - return value; - } - - public void setCallback(ResponseCallback callback) { - callback.done(value); - } - - public boolean isDone() { - return true; - } - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.exchange.support; + +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.ResponseCallback; +import com.alibaba.dubbo.remoting.exchange.ResponseFuture; + +/** + * SimpleFuture + * + * @author william.liangf + */ +public class SimpleFuture implements ResponseFuture { + + private final Object value; + + public SimpleFuture(Object value){ + this.value = value; + } + + public Object get() throws RemotingException { + return value; + } + + public Object get(int timeoutInMillis) throws RemotingException { + return value; + } + + public void setCallback(ResponseCallback callback) { + callback.done(value); + } + + public boolean isDone() { + return true; + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index d8d5903dd29..f309bad0936 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -23,10 +23,14 @@ import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; import java.net.InetSocketAddress; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; /** * ExchangeReceiver @@ -39,6 +43,8 @@ final class HeaderExchangeChannel implements ExchangeChannel { private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; + private static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); + private final Channel channel; private volatile boolean closed = false; @@ -114,6 +120,67 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept return future; } + @Override + public Response execute(Request request) throws RemotingException { + return execute(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + if (closed) { + throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + + ", cause: The channel " + this + " is closed!"); + } + PendingReply pendingReply = new PendingReply(request.getId()); + addPendingReply(pendingReply); + long startTimeMs = System.currentTimeMillis(); + try { + channel.send(request); + } catch (RemotingException e) { + removePendingReply(pendingReply); + throw e; + } + LinkedBlockingQueue reply = pendingReply.getQueue(); + Response response = null; + try { + response = (timeout < 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + throw new RemotingException(this, e); + } finally { + removePendingReply(pendingReply); + } + // timeout + if (response == null) { + throw new TimeoutException(channel, getTimeoutMessage(request, timeout, startTimeMs)); + } + return response; + } + + public String getTimeoutMessage(Request request, int timeout, long startTimeMs) { + long nowTimestamp = System.currentTimeMillis(); + return "elapsed: " + (nowTimestamp - startTimeMs) + " ms, timeout: " + + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress(); + } + + private static void addPendingReply(PendingReply pendingReply) { + REPLY_HOLDER.putIfAbsent(pendingReply.getSavedReplyTo(), pendingReply); + } + + private static void removePendingReply(PendingReply pendingReply) { + REPLY_HOLDER.remove(pendingReply.getSavedReplyTo()); + } + + public static void handleResponse(Response response) { + PendingReply pendingReply = REPLY_HOLDER.get(response.getId()); + if (pendingReply == null) { + logger.warn("Response received after timeout for " + response); + return; + } + LinkedBlockingQueue replyHandoff = pendingReply.getQueue(); + replyHandoff.add(response); + } + public boolean isClosed() { return closed; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java deleted file mode 100644 index 5eb0605beb2..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannelV2.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.alibaba.dubbo.remoting.exchange.support.header; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannelV2; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; - -import java.net.InetSocketAddress; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -public class HeaderExchangeChannelV2 implements ExchangeChannelV2 { - - private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeChannel.class); - - private static final String CHANNEL_KEY = HeaderExchangeChannelV2.class.getName() + ".CHANNEL"; - - private static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); - - private final Channel channel; - - private volatile boolean closed = false; - - - HeaderExchangeChannelV2(Channel channel) { - if (channel == null) { - throw new IllegalArgumentException("channel == null"); - } - this.channel = channel; - } - - static HeaderExchangeChannel getOrAddChannel(Channel ch) { - if (ch == null) { - return null; - } - HeaderExchangeChannel ret = (HeaderExchangeChannel) ch.getAttribute(CHANNEL_KEY); - if (ret == null) { - ret = new HeaderExchangeChannel(ch); - if (ch.isConnected()) { - ch.setAttribute(CHANNEL_KEY, ret); - } - } - return ret; - } - - static void removeChannelIfDisconnected(Channel ch) { - if (ch != null && !ch.isConnected()) { - ch.removeAttribute(CHANNEL_KEY); - } - } - - public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(Constants.SENT_KEY, false)); - } - - public void send(Object message, boolean sent) throws RemotingException { - if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + - ", cause: The channel " + this + " is closed!"); - } - if (message instanceof Request - || message instanceof Response - || message instanceof String) { - channel.send(message, sent); - } else { - Request.Builder builder = new Request.Builder(); - builder.newId().version(Version.getVersion()).twoWay(false).data(message); - Request request = builder.build(); - channel.send(request, sent); - } - } - - public Response request(Request request) throws RemotingException { - return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - } - - public Response request(Request request, int timeout) throws RemotingException { - if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + - ", cause: The channel " + this + " is closed!"); - } - PendingReply pendingReply = new PendingReply(request.getId()); - addPendingReply(pendingReply); - long startTimeMs = System.currentTimeMillis(); - try { - channel.send(request); - } catch (RemotingException e) { - removePendingReply(pendingReply); - throw e; - } - LinkedBlockingQueue reply = pendingReply.getQueue(); - Response response = null; - try { - response = (timeout < 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - throw new RemotingException(this, e); - } finally { - removePendingReply(pendingReply); - } - // timeout - if (response == null) { - throw new TimeoutException(channel, getTimeoutMessage(request, timeout, startTimeMs)); - } - return response; - } - - public String getTimeoutMessage(Request request, int timeout, long startTimeMs) { - long nowTimestamp = System.currentTimeMillis(); - return "elapsed: " + (nowTimestamp - startTimeMs) + " ms, timeout: " - + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress(); - } - - private static void addPendingReply(PendingReply pendingReply) { - REPLY_HOLDER.putIfAbsent(pendingReply.getSavedReplyTo(), pendingReply); - } - - private static void removePendingReply(PendingReply pendingReply) { - REPLY_HOLDER.remove(pendingReply.getSavedReplyTo()); - } - - public static void handleResponse(Response response) { - PendingReply pendingReply = REPLY_HOLDER.get(response.getId()); - if (pendingReply == null) { - logger.warn("Response received after timeout for " + response); - return; - } - LinkedBlockingQueue replyHandoff = pendingReply.getQueue(); - replyHandoff.add(response); - } - - - public boolean isClosed() { - return closed; - } - - public void close() { - try { - channel.close(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - - // graceful close - public void close(int timeout) { - if (closed) { - return; - } - closed = true; - if (timeout > 0) { - long start = System.currentTimeMillis(); -// while (DefaultFuture.hasFuture(HeaderExchangeChannelV2.this) -// && System.currentTimeMillis() - start < timeout) { -// try { -// Thread.sleep(10); -// } catch (InterruptedException e) { -// logger.warn(e.getMessage(), e); -// } -// } - } - close(); - } - - public InetSocketAddress getLocalAddress() { - return channel.getLocalAddress(); - } - - public InetSocketAddress getRemoteAddress() { - return channel.getRemoteAddress(); - } - - public URL getUrl() { - return channel.getUrl(); - } - - public boolean isConnected() { - return channel.isConnected(); - } - - public ChannelHandler getChannelHandler() { - return channel.getChannelHandler(); - } - - public ExchangeHandler getExchangeHandler() { - return (ExchangeHandler) channel.getChannelHandler(); - } - - public Object getAttribute(String key) { - return channel.getAttribute(key); - } - - public void setAttribute(String key, Object value) { - channel.setAttribute(key, value); - } - - public void removeAttribute(String key) { - channel.removeAttribute(key); - } - - public boolean hasAttribute(String key) { - return channel.hasAttribute(key); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (channel.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - HeaderExchangeChannelV2 other = (HeaderExchangeChannelV2) obj; - return channel.equals(other.channel); - } - - @Override - public String toString() { - return channel.toString(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 97f0f97e35a..15b617a6a85 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -17,6 +17,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; @@ -47,7 +48,6 @@ public class HeaderExchangeClient implements ExchangeClient { private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); - // 心跳定时器 private ScheduledFuture heartbeatTimer; @@ -187,6 +187,69 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept return channel.request(request, timeout); } + @Override + public Response execute(Request request) throws RemotingException { + return execute(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, request, timeout); + return chain.proceed(request, timeout); + } + + public void addInterceptor(Interceptor interceptor) { + this.interceptors.add(interceptor); + } + + /** + * @author Xs request interceptor + */ + class ExchangeClientInterceptorChain implements Interceptor.Chain { + + private final int index; + + private final Request request; + + private final int timeout; + + ExchangeClientInterceptorChain(int index, Request request, int timeout) { + this.index = index; + this.request = request; + this.timeout = timeout; + } + + @Override + public Request request() { + return request; + } + + @Override + public int timeout() { + return timeout; + } + + @Override + public Response proceed(Request request, int timeout) throws RemotingException { + if (index < interceptors.size()) { + Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request, timeout); + Interceptor interceptor = interceptors.get(index); + Response response = interceptor.intercept(chain); + if (response == null) { + throw new NullPointerException("interceptor " + interceptor + + " returned null"); + } + return response; + } + return channel.execute(request, timeout); + } + + @Override + public Response proceed(Request request) { + throw new UnsupportedOperationException("This is server side method"); + } + } + private void doClose() { stopHeartbeatTimer(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java deleted file mode 100644 index 09f73382f78..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClientV2.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.alibaba.dubbo.remoting.exchange.support.header; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; - -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; - -/** - * @author yanss - */ -public class HeaderExchangeClientV2 implements ExchangeClientV2 { - - private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeClient.class); - - private final Client client; - - private final HeaderExchangeChannelV2 channel; - - private final List interceptors = new ArrayList(); - - public HeaderExchangeClientV2(Client client) { - if (client == null) { - throw new IllegalArgumentException("client == null"); - } - this.client = client; - this.channel = new HeaderExchangeChannelV2(client); - String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); - } - - public URL getUrl() { - return channel.getUrl(); - } - - public InetSocketAddress getRemoteAddress() { - return channel.getRemoteAddress(); - } - - public ChannelHandler getChannelHandler() { - return channel.getChannelHandler(); - } - - public boolean isConnected() { - return channel.isConnected(); - } - - public InetSocketAddress getLocalAddress() { - return channel.getLocalAddress(); - } - - @Override - public Response request(Request request) throws RemotingException { - return null; - } - - @Override - public Response request(Request request, int timeout) throws RemotingException { - return null; - } - - public ExchangeHandler getExchangeHandler() { - return channel.getExchangeHandler(); - } - - public void send(Object message) throws RemotingException { - channel.send(message); - } - - public void send(Object message, boolean sent) throws RemotingException { - channel.send(message, sent); - } - - public boolean isClosed() { - return channel.isClosed(); - } - - public void close() { - channel.close(); - } - - public void close(int timeout) { - channel.close(timeout); - } - - public void reset(URL url) { - client.reset(url); - } - - @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters) { - reset(getUrl().addParameters(parameters.getParameters())); - } - - public void reconnect() throws RemotingException { - client.reconnect(); - } - - public Object getAttribute(String key) { - return channel.getAttribute(key); - } - - public void setAttribute(String key, Object value) { - channel.setAttribute(key, value); - } - - public void removeAttribute(String key) { - channel.removeAttribute(key); - } - - public boolean hasAttribute(String key) { - return channel.hasAttribute(key); - } - - - public Response request(Object request) throws RemotingException { - return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - } - - public Response request(Object request, int timeout) throws RemotingException { - Request.Builder builder = new Request.Builder(); - builder.newId().version(Version.getVersion()).twoWay(true).data(request); - Request req = builder.build(); - Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, req, timeout); - return chain.proceed(req, timeout); - } - - public void addInterceptor(Interceptor interceptor) { - interceptors.add(interceptor); - } - - /** - * @author Xs request interceptor - */ - class ExchangeClientInterceptorChain implements Interceptor.Chain { - - private final int index; - - private final Request request; - - private final int timeout; - - ExchangeClientInterceptorChain(int index, Request request, int timeout) { - this.index = index; - this.request = request; - this.timeout = timeout; - } - - @Override - public Request request() { - return request; - } - - @Override - public int timeout() { - return timeout; - } - - @Override - public Response proceed(Request request, int timeout) throws RemotingException { - if (index < interceptors.size()) { - Interceptor.Chain chain = new ExchangeClientInterceptorChain(index + 1, request, timeout); - Interceptor interceptor = interceptors.get(index); - Response response = interceptor.intercept(chain); - if (response == null) { - throw new NullPointerException("interceptor " + interceptor - + " returned null"); - } - return response; - } - return channel.request(request, timeout); - } - - @Override - public Response proceed(Request request) { - throw new UnsupportedOperationException("This is server side method"); - } - } - - @Override - public String toString() { - return "HeaderExchangeClient [channel=" + channel + "]"; - } -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 4e2802aff97..09dbfa03998 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -25,14 +25,13 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; /** * ExchangeReceiver @@ -48,6 +47,8 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; + private final List interceptors = new ArrayList(); + private final ExchangeHandler handler; public HeaderExchangeHandler(ExchangeHandler handler) { @@ -88,9 +89,9 @@ private Response handleRequest(ExchangeChannel channel, Request req) throws Remo return builder.build(); } - private void handleResponse(Channel channel, Response response) throws RemotingException { + private void handleResponse(Response response) throws RemotingException { if (response != null && !response.isHeartbeat()) { - DefaultFuture.received(channel, response); + HeaderExchangeChannel.handleResponse(response); } } @@ -163,14 +164,15 @@ public void received(Channel channel, Object message) throws RemotingException { handlerEvent(channel, request); } else { if (request.isTwoWay()) { - Response response = handleRequest(exchangeChannel, request); + Interceptor.Chain chain = new ExchangeHandlerChain(0, exchangeChannel, request); + Response response = chain.proceed(request); channel.send(response); } else { handler.received(exchangeChannel, request.getData()); } } } else if (message instanceof Response) { - handleResponse(channel, (Response) message); + handleResponse((Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { Exception e = new Exception("Dubbo client can not supported string message: " + @@ -190,6 +192,51 @@ public void received(Channel channel, Object message) throws RemotingException { } } + public void addInterceptor(Interceptor interceptor) { + interceptors.add(interceptor); + } + + class ExchangeHandlerChain implements Interceptor.Chain { + private final int index; + private final ExchangeChannel exchangeChannel; + private final Request request; + + public ExchangeHandlerChain(int index, ExchangeChannel exchangeChannel, Request request) { + this.index = index; + this.exchangeChannel = exchangeChannel; + this.request = request; + } + + @Override + public Request request() { + return request; + } + + @Override + public int timeout() { + return 0; + } + + @Override + public Response proceed(Request request, int timeout) throws RemotingException { + throw new UnsupportedOperationException("This is client side method"); + } + + @Override + public Response proceed(Request request) throws RemotingException { + if (index < interceptors.size()) { + Interceptor.Chain chain = new ExchangeHandlerChain(index + 1, exchangeChannel, request); + Interceptor interceptor = interceptors.get(index); + Response response = interceptor.intercept(chain); + if (response == null) { + throw new NullPointerException("interceptor " + interceptor + " returned null"); + } + return response; + } + return handleRequest(exchangeChannel, request); + } + } + public void caught(Channel channel, Throwable exception) throws RemotingException { if (exception instanceof ExecutionException) { ExecutionException e = (ExecutionException) exception; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java deleted file mode 100644 index 37f6f8a6f92..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandlerV2.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.alibaba.dubbo.remoting.exchange.support.header; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; -import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; - -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Xs - */ -public class HeaderExchangeHandlerV2 implements ChannelHandlerDelegate { - - protected static final Logger logger = LoggerFactory.getLogger(HeaderExchangeHandler.class); - - public static String KEY_READ_TIMESTAMP = HeartbeatHandler.KEY_READ_TIMESTAMP; - - public static String KEY_WRITE_TIMESTAMP = HeartbeatHandler.KEY_WRITE_TIMESTAMP; - - private final List interceptors = new ArrayList(); - - private final ExchangeHandler handler; - - public HeaderExchangeHandlerV2(ExchangeHandler handler) { - if (handler == null) { - throw new IllegalArgumentException("handler == null"); - } - this.handler = handler; - } - - private void handlerEvent(Channel channel, Request req) throws RemotingException { - if (req.getData() != null && req.getData().equals(Request.READONLY_EVENT)) { - channel.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); - } - } - - private Response handleRequest(ExchangeChannel channel, Request request) throws RemotingException { - Response.Builder builder = new Response.Builder(request.getId()); - builder.version(request.getVersion()); - if (request.isBroken()) { - Object data = request.getData(); - String msg; - if (data == null) msg = null; - else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data); - else msg = data.toString(); - builder.errorMsg("Fail to decode request due to: " + msg); - builder.status(Response.BAD_REQUEST); - return builder.build(); - } - Object msg = request.getData(); - try { - Object result = handler.reply(channel, msg); - builder.status(Response.OK).result(result); - } catch (Throwable e) { - builder.status(Response.SERVICE_ERROR).errorMsg(StringUtils.toString(e)); - } - return builder.build(); - } - - private void handleResponse(Response response) throws RemotingException { - if (response != null && !response.isHeartbeat()) { - HeaderExchangeChannelV2.handleResponse(response); - } - } - - public void connected(Channel channel) throws RemotingException { - channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); - try { - handler.connected(exchangeChannel); - } finally { - HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); - } - } - - public void disconnected(Channel channel) throws RemotingException { - channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); - try { - handler.disconnected(exchangeChannel); - } finally { - HeaderExchangeChannel.removeChannelIfDisconnected(channel); - } - } - - public void sent(Channel channel, Object message) throws RemotingException { - Throwable exception = null; - try { - channel.setAttribute(KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); - try { - handler.sent(exchangeChannel, message); - } finally { - HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); - } - } catch (Throwable t) { - exception = t; - } - if (message instanceof Request) { - Request request = (Request) message; - DefaultFuture.sent(channel, request); - } - if (exception != null) { - if (exception instanceof RuntimeException) { - throw (RuntimeException) exception; - } else if (exception instanceof RemotingException) { - throw (RemotingException) exception; - } else { - throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), - exception.getMessage(), exception); - } - } - } - - private static boolean isClientSide(Channel channel) { - InetSocketAddress address = channel.getRemoteAddress(); - URL url = channel.getUrl(); - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(url.getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); - } - - public void received(Channel channel, Object message) throws RemotingException { - channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); - try { - if (message instanceof Request) { - Request request = (Request) message; - if (request.isEvent()) { - handlerEvent(channel, request); - } else { - if (request.isTwoWay()) { - Interceptor.Chain chain = new ExchangeHandlerChain(0, exchangeChannel, request); - Response response = chain.proceed(request); - channel.send(response); - } else { - handler.received(exchangeChannel, request.getData()); - } - } - } else if (message instanceof Response) { - handleResponse((Response) message); - } else if (message instanceof String) { - if (isClientSide(channel)) { - Exception e = new Exception("Dubbo client can not supported string message: " + - message + " in channel: " + channel + ", url: " + channel.getUrl()); - logger.error(e.getMessage(), e); - } else { - String echo = handler.telnet(channel, (String) message); - if (echo != null && echo.length() > 0) { - channel.send(echo); - } - } - } else { - handler.received(exchangeChannel, message); - } - } finally { - HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); - } - } - - class ExchangeHandlerChain implements Interceptor.Chain { - private final int index; - private final ExchangeChannel exchangeChannel; - private final Request request; - - public ExchangeHandlerChain(int index, ExchangeChannel exchangeChannel, Request request) { - this.index = index; - this.exchangeChannel = exchangeChannel; - this.request = request; - } - - @Override - public Request request() { - return request; - } - - @Override - public int timeout() { - return 0; - } - - @Override - public Response proceed(Request request, int timeout) throws RemotingException { - throw new UnsupportedOperationException("This is client side method"); - } - - @Override - public Response proceed(Request request) throws RemotingException { - if (index < interceptors.size()) { - Interceptor.Chain chain = new ExchangeHandlerChain(index + 1, exchangeChannel, request); - Interceptor interceptor = interceptors.get(index); - Response response = interceptor.intercept(chain); - if (response == null) { - throw new NullPointerException("interceptor " + interceptor + " returned null"); - } - return response; - } - return handleRequest(exchangeChannel, request); - } - } - - public void caught(Channel channel, Throwable exception) throws RemotingException { - if (exception instanceof ExecutionException) { - ExecutionException e = (ExecutionException) exception; - Object msg = e.getRequest(); - if (msg instanceof Request) { - Request req = (Request) msg; - if (req.isTwoWay() && !req.isHeartbeat()) { - Response.Builder builder = new Response.Builder(req.getId()); - builder.version(req.getVersion()).status(Response.SERVER_ERROR).errorMsg(StringUtils.toString(e)); - channel.send(builder.build()); - return; - } - } - } - ExchangeChannel exchangeChannel = HeaderExchangeChannelV2.getOrAddChannel(channel); - try { - handler.caught(exchangeChannel, exception); - } finally { - HeaderExchangeChannelV2.removeChannelIfDisconnected(channel); - } - } - - public ChannelHandler getHandler() { - if (handler instanceof ChannelHandlerDelegate) { - return ((ChannelHandlerDelegate) handler).getHandler(); - } else { - return handler; - } - } - - public void addInterceptor(Interceptor interceptor) { - interceptors.add(interceptor); - } -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java index 3cb8ca064d3..8725aa3df1d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -15,13 +15,6 @@ */ package com.alibaba.dubbo.remoting.telnet.codec; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -32,28 +25,35 @@ import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.transport.codec.TransportCodec; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + /** * TelnetCodec - * + * * @author heyman * @author william.liangf * @author chao.liuc */ public class TelnetCodec extends TransportCodec { - private static final Logger logger = LoggerFactory.getLogger(TelnetCodec.class); - + private static final Logger logger = LoggerFactory.getLogger(TelnetCodec.class); + private static final String HISTORY_LIST_KEY = "telnet.history.list"; private static final String HISTORY_INDEX_KEY = "telnet.history.index"; - - private static final byte[] UP = new byte[] {27, 91, 65}; - - private static final byte[] DOWN = new byte[] {27, 91, 66}; - private static final List ENTER = Arrays.asList(new Object[] { new byte[] { '\r', '\n' } /* Windows Enter */, new byte[] { '\n' } /* Linux Enter */ }); + private static final byte[] UP = new byte[]{27, 91, 65}; + + private static final byte[] DOWN = new byte[]{27, 91, 66}; + + private static final List ENTER = Arrays.asList(new byte[]{'\r', '\n'} /* Windows Enter */, new byte[]{'\n'} /* Linux Enter */); - private static final List EXIT = Arrays.asList(new Object[] { new byte[] { 3 } /* Windows Ctrl+C */, new byte[] { -1, -12, -1, -3, 6 } /* Linux Ctrl+C */, new byte[] { -1, -19, -1, -3, 6 } /* Linux Pause */ }); + private static final List EXIT = Arrays.asList(new byte[]{3} /* Windows Ctrl+C */, new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */); public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { if (message instanceof String) { @@ -66,7 +66,7 @@ public void encode(Channel channel, ChannelBuffer buffer, Object message) throws super.encode(channel, buffer, message); } } - + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int readable = buffer.readableBytes(); byte[] message = new byte[readable]; @@ -83,27 +83,27 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt if (message == null || message.length == 0) { return DecodeResult.NEED_MORE_INPUT; } - + if (message[message.length - 1] == '\b') { // Windows backspace echo try { boolean doublechar = message.length >= 3 && message[message.length - 3] < 0; // double byte char - channel.send(new String(doublechar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8}, getCharset(channel).name())); + channel.send(new String(doublechar ? new byte[]{32, 32, 8, 8} : new byte[]{32, 8}, getCharset(channel).name())); } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } return DecodeResult.NEED_MORE_INPUT; } - + for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { if (logger.isInfoEnabled()) { - logger.info(new Exception("Close channel " + channel + " on exit command: " + Arrays.toString((byte[])command))); + logger.info(new Exception("Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); } channel.close(); return null; } } - + boolean up = endsWith(message, UP); boolean down = endsWith(message, DOWN); if (up || down) { @@ -128,19 +128,19 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt } } } - if (old == null || ! old.equals(index)) { + if (old == null || !old.equals(index)) { channel.setAttribute(HISTORY_INDEX_KEY, index); String value = history.get(index); if (old != null && old >= 0 && old < history.size()) { String ov = history.get(old); StringBuilder buf = new StringBuilder(); - for (int i = 0; i < ov.length(); i ++) { + for (int i = 0; i < ov.length(); i++) { buf.append("\b"); } - for (int i = 0; i < ov.length(); i ++) { + for (int i = 0; i < ov.length(); i++) { buf.append(" "); } - for (int i = 0; i < ov.length(); i ++) { + for (int i = 0; i < ov.length(); i++) { buf.append("\b"); } value = buf.toString() + value; @@ -179,7 +179,7 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt String value = history.get(index); if (value != null) { byte[] b1 = value.getBytes(); - if (message != null && message.length > 0) { + if (message.length > 0) { byte[] b2 = new byte[b1.length + message.length]; System.arraycopy(b1, 0, b2, 0, b1.length); System.arraycopy(message, 0, b2, b1.length, message.length); @@ -190,14 +190,14 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt } } String result = toString(message, getCharset(channel)); - if (result != null && result.trim().length() > 0) { + if (result.trim().length() > 0) { if (history == null) { history = new LinkedList(); channel.setAttribute(HISTORY_LIST_KEY, history); } if (history.size() == 0) { history.addLast(result); - } else if (! result.equals(history.getLast())) { + } else if (!result.equals(history.getLast())) { history.remove(result); history.addLast(result); if (history.size() > 10) { @@ -207,7 +207,7 @@ protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byt } return result; } - + private static Charset getCharset(Channel channel) { if (channel != null) { Object attribute = channel.getAttribute(Constants.CHARSET_KEY); @@ -243,15 +243,15 @@ private static Charset getCharset(Channel channel) { private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException { byte[] copy = new byte[message.length]; int index = 0; - for (int i = 0; i < message.length; i ++) { - byte b = message[i] ; + for (int i = 0; i < message.length; i++) { + byte b = message[i]; if (b == '\b') { // backspace if (index > 0) { - index --; + index--; } if (i > 2 && message[i - 2] < 0) { // double byte char if (index > 0) { - index --; + index--; } } } else if (b == 27) { // escape @@ -262,11 +262,11 @@ private static String toString(byte[] message, Charset charset) throws Unsupport } else if (i < message.length - 2) { i = i + 2; } - } else if (b == -1 && i < message.length - 2 + } else if (b == -1 && i < message.length - 2 && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake i = i + 2; } else { - copy[index ++] = message[i]; + copy[index++] = message[i]; } } if (index == 0) { @@ -284,7 +284,7 @@ private static boolean endsWith(byte[] message, byte[] command) throws IOExcepti return false; } int offset = message.length - command.length; - for (int i = command.length - 1; i >= 0 ; i --) { + for (int i = command.length - 1; i >= 0; i--) { if (message[offset + i] != command[i]) { return false; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java index ae0abfbf7a5..2429af2b622 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java @@ -19,7 +19,7 @@ protected AbstractChannelHandlerDelegate(ChannelHandler handler) { public ChannelHandler getHandler() { if (handler instanceof ChannelHandlerDelegate) { - return ((ChannelHandlerDelegate)handler).getHandler(); + return ((ChannelHandlerDelegate) handler).getHandler(); } return handler; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java index b618761b36e..6c90fdf6d58 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport; - -import com.alibaba.dubbo.remoting.ChannelHandler; - -/** - * @author chao.liuc - */ -public interface ChannelHandlerDelegate extends ChannelHandler { - public ChannelHandler getHandler(); +package com.alibaba.dubbo.remoting.transport; + +import com.alibaba.dubbo.remoting.ChannelHandler; + +/** + * @author chao.liuc + */ +public interface ChannelHandlerDelegate extends ChannelHandler { + + ChannelHandler getHandler(); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java index 69c99a56c26..4c298ca290b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java @@ -42,11 +42,11 @@ public void received(Channel channel, Object message) throws RemotingException { } if (message instanceof Request) { - decode(((Request)message).getData()); + decode(((Request) message).getData()); } if (message instanceof Response) { - decode( ((Response)message).getResult()); + decode(((Response) message).getResult()); } handler.received(channel, message); @@ -55,21 +55,20 @@ public void received(Channel channel, Object message) throws RemotingException { private void decode(Object message) { if (message != null && message instanceof Decodeable) { try { - ((Decodeable)message).decode(); + ((Decodeable) message).decode(); if (log.isDebugEnabled()) { log.debug(new StringBuilder(32).append("Decode decodeable message ") - .append(message.getClass().getName()).toString()); + .append(message.getClass().getName()).toString()); } } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn( - new StringBuilder(32) - .append("Call Decodeable.decode failed: ") - .append(e.getMessage()).toString(), - e); + new StringBuilder(32) + .append("Call Decodeable.decode failed: ") + .append(e.getMessage()).toString(), + e); } - } // ~ end of catch - } // ~ end of if - } // ~ end of method decode - + } + } + } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java index 1c57885f009..90629c74c36 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java @@ -49,10 +49,6 @@ public void encode(Channel channel, ChannelBuffer buffer, Object message) throws } public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { -// InputStream input = new ChannelBufferInputStream(buffer); -// return decodeData(channel, getSerialization(channel).deserialize(channel.getUrl(), input)); - - // modified by lishen InputStream input = new ChannelBufferInputStream(buffer); ObjectInput objectInput = getSerialization(channel).deserialize(channel.getUrl(), input); Object object = decodeData(channel, objectInput); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java index f0976d34f63..2586e0ab0ba 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java @@ -22,27 +22,26 @@ /** * @author chao.liuc - * */ public class ChannelEventRunnable implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(ChannelEventRunnable.class); + private static final Logger logger = LoggerFactory.getLogger(ChannelEventRunnable.class); private final ChannelHandler handler; private final Channel channel; private final ChannelState state; private final Throwable exception; private final Object message; - + public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state) { this(channel, handler, state, null); } - + public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message) { this(channel, handler, state, message, null); } - + public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Throwable t) { - this(channel, handler, state, null , t); + this(channel, handler, state, null, t); } public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) { @@ -52,45 +51,45 @@ public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelStat this.message = message; this.exception = exception; } - + public void run() { switch (state) { case CONNECTED: - try{ + try { handler.connected(channel); - }catch (Exception e) { + } catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case DISCONNECTED: - try{ + try { handler.disconnected(channel); - }catch (Exception e) { + } catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); } break; case SENT: - try{ - handler.sent(channel,message); - }catch (Exception e) { + try { + handler.sent(channel, message); + } catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is "+ message,e); + + ", message is " + message, e); } break; case RECEIVED: - try{ + try { handler.received(channel, message); - }catch (Exception e) { + } catch (Exception e) { logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is "+ message,e); + + ", message is " + message, e); } break; case CAUGHT: - try{ + try { handler.caught(channel, exception); - }catch (Exception e) { - logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is "+ channel - + ", message is: " + message + ", exception is " + exception,e); + } catch (Exception e) { + logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel + + ", message is: " + message + ", exception is " + exception, e); } break; default: @@ -100,31 +99,31 @@ public void run() { /** * ChannelState - * + * * @author william.liangf */ - public enum ChannelState{ - + public enum ChannelState { + /** * CONNECTED */ CONNECTED, - + /** * DISCONNECTED */ DISCONNECTED, - + /** * SENT */ SENT, - + /** * RECEIVED */ RECEIVED, - + /** * CAUGHT */ diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index 4ba418f9c50..dae2156bfa3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -58,8 +58,8 @@ public WrappedChannelHandler(ChannelHandler handler, URL url) { public void close() { try { - if (executor instanceof ExecutorService) { - ((ExecutorService)executor).shutdown(); + if (executor != null) { + executor.shutdown(); } } catch (Throwable t) { logger.warn("fail to destroy thread pool of server: " + t.getMessage(), t); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index c6aa975bc2f..5ce30db7a63 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -104,7 +104,6 @@ public Object decode(Channel channel, InputStream input) throws IOException { } return this; } finally { - // modified by lishen if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 558cdf49e66..d98ef286b87 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -17,10 +17,13 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; @@ -87,8 +90,9 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { return new RpcResult(); } else { RpcContext.getContext().setFuture(null); - Result result = (Result) currentClient.request(inv, timeout).get(); - return result; + Request request = new Request.Builder().newId().version(Version.getVersion()).data(inv).build(); + Response response = currentClient.execute(request, timeout); + return (Result) response.getResult(); } } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); @@ -103,7 +107,6 @@ public boolean isAvailable() { return false; for (ExchangeClient client : clients) { if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { - //cannot write == not Available ? return true; } } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index c36b5ce7d0a..cf7c8139b02 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -220,12 +220,10 @@ public int getDefaultPort() { public Exporter export(Invoker invoker) throws RpcException { URL url = invoker.getUrl(); - // export service. String key = serviceKey(url); DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); exporterMap.put(key, exporter); - //export an stub service for dispaching event Boolean isStubSupportEvent = url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT); Boolean isCallbackService = url.getParameter(Constants.IS_CALLBACK_SERVICE, false); @@ -240,12 +238,9 @@ public Exporter export(Invoker invoker) throws RpcException { stubServiceMethodsMap.put(url.getServiceKey(), stubServiceMethods); } } - openServer(url); - // modified by lishen optimizeSerialization(url); - return exporter; } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 496c17eed24..65ee7fba14e 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -103,6 +103,16 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept return client.request(request, timeout); } + @Override + public Response execute(Request request) throws RemotingException { + return client.execute(request); + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + return client.execute(request, timeout); + } + /** * 如果配置了调用warning,则每调用5000次warning一次. * @@ -217,4 +227,8 @@ private void checkClient() { } } + @Override + public void addInterceptor(Interceptor interceptor) { + client.addInterceptor(interceptor); + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index d81695390d7..d3de82b9057 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -20,9 +20,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.exchange.*; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentMap; @@ -40,13 +38,10 @@ final class ReferenceCountExchangeClient implements ExchangeClient { private final URL url; -// private final ExchangeHandler handler; - private final AtomicInteger refenceCount = new AtomicInteger(0); private final ConcurrentMap ghostClientMap; - public ReferenceCountExchangeClient(ExchangeClient client, ConcurrentMap ghostClientMap) { this.client = client; refenceCount.incrementAndGet(); @@ -81,6 +76,16 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept return client.request(request, timeout); } + @Override + public Response execute(Request request) throws RemotingException { + return client.execute(request); + } + + @Override + public Response execute(Request request, int timeout) throws RemotingException { + return client.execute(request, timeout); + } + public boolean isConnected() { return client.isConnected(); } @@ -170,4 +175,9 @@ public boolean isClosed() { public void incrementAndGetCount() { refenceCount.incrementAndGet(); } + + @Override + public void addInterceptor(Interceptor interceptor) { + client.addInterceptor(interceptor); + } } \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java index a8b8b3cf080..a53a64c80bf 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java @@ -9,5 +9,4 @@ public class TrackerKeys { public static final String RETURN_STATUS = "return.status"; - } From 437a26988f9c0b8da4491526fde2e840d6ced43b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Mon, 23 Jan 2017 17:23:34 +0800 Subject: [PATCH 17/69] move package --- .../alibaba/dubbo/config/ProtocolConfig.java | 2 +- .../alibaba/dubbo/config/ProviderConfig.java | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../dubbo/registry/dubbo/MockChannel.java | 6 +- .../dubbo/registry/dubbo/MockedClient.java | 14 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 15 ++ .../com/alibaba/dubbo/remoting/Codec.java | 1 + .../com/alibaba/dubbo/remoting/Codec2.java | 1 + .../alibaba/dubbo/remoting/Decodeable.java | 2 +- .../alibaba/dubbo/remoting/Dispatcher.java | 1 + .../alibaba/dubbo/remoting/Transporters.java | 5 + .../remoting/exchange/ExchangeChannel.java | 14 +- .../remoting/exchange/ExchangeChannelV2.java | 40 --- .../remoting/exchange/ExchangeClient.java | 3 +- .../remoting/exchange/ExchangeClientV2.java | 9 - .../remoting/exchange/ExchangeHandler.java | 4 +- .../remoting/exchange/ExchangeServer.java | 2 +- .../dubbo/remoting/exchange/Exchanger.java | 2 +- .../dubbo/remoting/exchange/Exchangers.java | 4 +- .../remoting/exchange/ResponseFuture.java | 4 +- .../exchange/codec/ExchangeCodec.java | 26 +- .../exchange/support/DefaultFuture.java | 18 +- .../support/ExchangeHandlerAdapter.java | 2 +- .../support/ExchangeHandlerDispatcher.java | 6 +- .../support/ExchangeServerDelegate.java | 6 +- .../remoting/exchange/support/Replier.java | 2 +- .../exchange/support/ReplierDispatcher.java | 2 +- .../exchange/support/SimpleFuture.java | 7 +- .../support/header/HeaderExchangeChannel.java | 24 +- .../support/header/HeaderExchangeClient.java | 12 +- .../support/header/HeaderExchangeHandler.java | 11 +- .../support/header/HeaderExchangeServer.java | 10 +- .../support/header/HeaderExchanger.java | 35 ++- .../support/header/HeartBeatTask.java | 6 +- .../support/header/HeartbeatHandler.java | 10 +- .../exchange/support/header/PendingReply.java | 3 +- .../dubbo/remoting/telnet/TelnetHandler.java | 4 +- .../remoting/telnet/codec/TelnetCodec.java | 4 +- .../telnet/support/TelnetHandlerAdapter.java | 4 +- .../support/command/ClearTelnetHandler.java | 2 +- .../support/command/ExitTelnetHandler.java | 2 +- .../support/command/HelpTelnetHandler.java | 2 +- .../support/command/LogTelnetHandler.java | 76 +++--- .../support/command/StatusTelnetHandler.java | 2 +- .../remoting/transport/AbstractChannel.java | 4 +- .../AbstractChannelHandlerDelegate.java | 4 +- .../remoting/transport/AbstractClient.java | 5 +- .../remoting/transport/AbstractCodec.java | 1 - .../remoting/transport/AbstractEndpoint.java | 1 - .../remoting/transport/AbstractPeer.java | 5 +- .../remoting/transport/AbstractServer.java | 5 +- .../remoting/transport/ChannelDelegate.java | 4 +- .../transport/ChannelHandlerAdapter.java | 34 ++- .../transport/ChannelHandlerDelegate.java | 2 - .../transport/ChannelHandlerDispatcher.java | 2 - .../remoting/transport/ClientDelegate.java | 4 +- .../remoting/transport/DecodeHandler.java | 9 +- .../transport/MultiMessageHandler.java | 5 +- .../remoting/transport/ServerDelegate.java | 5 +- .../transport/codec/CodecAdapter.java | 2 +- .../transport/codec/TransportCodec.java | 2 +- .../dispatcher/ChannelEventRunnable.java | 4 +- .../transport/dispatcher/ChannelHandlers.java | 2 +- .../dispatcher/WrappedChannelHandler.java | 6 +- .../dispatcher/all/AllChannelHandler.java | 8 +- .../dispatcher/all/AllDispatcher.java | 2 +- .../ConnectionOrderedChannelHandler.java | 8 +- .../ConnectionOrderedDispatcher.java | 2 +- .../dispatcher/direct/DirectDispatcher.java | 2 +- .../execution/ExecutionChannelHandler.java | 6 +- .../execution/ExecutionDispatcher.java | 2 +- .../message/MessageOnlyChannelHandler.java | 8 +- .../message/MessageOnlyDispatcher.java | 2 +- .../dubbo/remoting/ChanelHandlerTest.java | 32 +-- .../java/com/alibaba/dubbo/remoting/Main.java | 247 +++++++++--------- .../dubbo/remoting/PerformanceClientTest.java | 2 + .../dubbo/remoting/PerformanceServerTest.java | 2 + .../dubbo/remoting/RpcMessageHandler.java | 1 + .../alibaba/dubbo/remoting/TelnetServer.java | 2 + .../remoting/codec/AbstractMockChannel.java | 36 +-- .../remoting/codec/ExchangeCodecTest.java | 6 +- .../dubbo/remoting/codec/TelnetCodecTest.java | 2 +- .../support/header/HeartBeatTaskTest.java | 4 +- .../exchange/support/header/MockChannel.java | 6 +- .../handler/ConnectChannelHandlerTest.java | 8 +- .../handler/HeaderExchangeHandlerTest.java | 8 +- .../dubbo/remoting/handler/MockedChannel.java | 48 ++-- .../handler/MockedChannelHandler.java | 36 +-- .../handler/WrappedChannelHandlerTest.java | 36 +-- .../remoting/transport/AbstractCodecTest.java | 1 - .../transport/codec/CodecAdapterTest.java | 12 - .../codec/DeprecatedExchangeCodec.java | 8 +- .../codec/DeprecatedTelnetCodec.java | 5 +- dubbo-remoting/dubbo-remoting-common/pom.xml | 22 ++ .../exception}/ExecutionException.java | 136 +++++----- .../exception}/RemotingException.java | 31 +-- .../remoting/exception}/TimeoutException.java | 4 +- .../dubbo/remoting/message}/Interceptor.java | 5 +- .../dubbo/remoting/message}/Message.java | 2 +- .../dubbo/remoting/message}/Request.java | 5 +- .../dubbo/remoting/message}/Response.java | 2 +- .../dubbo/remoting/transport}/Channel.java | 25 +- .../remoting/transport}/ChannelHandler.java | 3 +- .../dubbo/remoting/transport}/Client.java | 75 +++--- .../dubbo/remoting/transport}/Endpoint.java | 169 ++++++------ .../dubbo/remoting/transport}/Server.java | 114 ++++---- .../remoting/transport}/Transporter.java | 24 +- .../transport/grizzly/GrizzlyChannel.java | 4 +- .../transport/grizzly/GrizzlyClient.java | 6 +- .../grizzly/GrizzlyCodecAdapter.java | 4 +- .../transport/grizzly/GrizzlyHandler.java | 4 +- .../transport/grizzly/GrizzlyServer.java | 6 +- .../transport/grizzly/GrizzlyTransporter.java | 10 +- ...baba.dubbo.remoting.transport.Transporter} | 0 .../remoting/transport/mina/MinaChannel.java | 34 +-- .../remoting/transport/mina/MinaClient.java | 90 +++---- .../transport/mina/MinaCodecAdapter.java | 4 +- .../remoting/transport/mina/MinaHandler.java | 32 +-- .../remoting/transport/mina/MinaServer.java | 6 +- .../transport/mina/MinaTransporter.java | 46 ++-- ...baba.dubbo.remoting.transport.Transporter} | 0 .../transport/mina/ClientToServerTest.java | 32 +-- .../remoting/transport/mina/ClientsTest.java | 2 +- .../mina/MinaClientToServerTest.java | 32 +-- .../remoting/transport/mina/WorldHandler.java | 32 +-- dubbo-remoting/dubbo-remoting-netty/pom.xml | 7 + .../transport/netty/NettyChannel.java | 46 ++-- .../remoting/transport/netty/NettyClient.java | 6 +- .../transport/netty/NettyCodecAdapter.java | 4 +- .../transport/netty/NettyHandler.java | 36 +-- .../remoting/transport/netty/NettyServer.java | 12 +- .../transport/netty/NettyTransporter.java | 46 ++-- ...baba.dubbo.remoting.transport.Transporter} | 0 .../support/header/HeartbeatHandlerTest.java | 4 +- .../dispatcher/FakeChannelHandlers.java | 2 +- .../transport/netty/ClientReconnectTest.java | 116 ++++---- .../transport/netty/ClientToServerTest.java | 32 +-- .../remoting/transport/netty/ClientsTest.java | 2 +- .../transport/netty/NettyClientTest.java | 44 ++-- .../netty/NettyClientToServerTest.java | 32 +-- .../transport/netty/TelnetClientHandler.java | 32 +-- .../transport/netty/TelnetServerHandler.java | 32 +-- .../transport/netty/ThreadNameTest.java | 6 +- .../transport/netty/WorldHandler.java | 32 +-- .../com/alibaba/dubbo/remoting/p2p/Group.java | 4 +- .../alibaba/dubbo/remoting/p2p/Networker.java | 2 +- .../dubbo/remoting/p2p/Networkers.java | 4 +- .../com/alibaba/dubbo/remoting/p2p/Peer.java | 4 +- .../remoting/p2p/exchange/ExchangeGroup.java | 2 +- .../p2p/exchange/ExchangeNetworker.java | 2 +- .../p2p/exchange/ExchangeNetworkers.java | 2 +- .../support/AbstractExchangeGroup.java | 8 +- .../exchange/support/ExchangeServerPeer.java | 6 +- .../exchange/support/FileExchangeGroup.java | 2 +- .../support/FileExchangeNetworker.java | 2 +- .../support/MulticastExchangeGroup.java | 2 +- .../support/MulticastExchangeNetworker.java | 2 +- .../remoting/p2p/support/AbstractGroup.java | 8 +- .../dubbo/remoting/p2p/support/FileGroup.java | 4 +- .../remoting/p2p/support/FileNetworker.java | 2 +- .../remoting/p2p/support/MulticastGroup.java | 4 +- .../p2p/support/MulticastNetworker.java | 2 +- .../remoting/p2p/support/ServerPeer.java | 8 +- .../alibaba/dubbo/remoting/p2p/PeerMain.java | 4 +- dubbo-remoting/pom.xml | 3 +- .../com/alibaba/dubbo/rpc/RpcConstants.java | 31 --- dubbo-rpc/dubbo-rpc-common/pom.xml | 15 ++ .../protocol/dubbo/CallbackServiceCodec.java | 120 ++++----- .../protocol/dubbo/ChannelWrappedInvoker.java | 33 +-- .../dubbo/DecodeableRpcInvocation.java | 9 +- .../protocol/dubbo/DecodeableRpcResult.java | 17 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 19 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 6 +- .../rpc/protocol/dubbo/DubboInvoker.java | 11 +- .../rpc/protocol/dubbo/DubboProtocol.java | 57 ++-- .../rpc/protocol/dubbo/FutureAdapter.java | 4 +- .../dubbo/LazyConnectExchangeClient.java | 7 +- .../dubbo/ReferenceCountExchangeClient.java | 15 +- .../protocol/dubbo/filter/TraceFilter.java | 2 +- .../dubbo/telnet/ChangeTelnetHandler.java | 2 +- .../dubbo/telnet/CountTelnetHandler.java | 4 +- .../dubbo/telnet/CurrentTelnetHandler.java | 2 +- .../dubbo/telnet/InvokeTelnetHandler.java | 2 +- .../dubbo/telnet/ListTelnetHandler.java | 2 +- .../dubbo/telnet/LogTelnetHandler.java | 60 ++--- .../dubbo/telnet/PortTelnetHandler.java | 2 +- .../dubbo/telnet/TraceTelnetHandler.java | 2 +- .../dubbo/telnet/ChangeTelnetHandlerTest.java | 4 +- .../telnet/CurrentTelnetHandlerTest.java | 4 +- .../telnet/InvokerTelnetHandlerTest.java | 4 +- .../dubbo/telnet/ListTelnetHandlerTest.java | 4 +- .../dubbo/telnet/LogTelnetHandlerTest.java | 4 +- .../dubbo/telnet/PortTelnetHandlerTest.java | 5 +- .../rpc/protocol/thrift/ThriftCodec.java | 6 +- .../rpc/protocol/thrift/ThriftInvoker.java | 76 ++---- .../protocol/thrift/ThriftNativeCodec.java | 6 +- .../rpc/protocol/thrift/ThriftProtocol.java | 6 +- .../rpc/protocol/thrift/MockedChannel.java | 6 +- .../rpc/protocol/thrift/ThriftCodecTest.java | 6 +- dubbo-rpc/pom.xml | 1 + .../benchmark/AbstractBenchmarkClient.java | 70 +++-- .../benchmark/AbstractBenchmarkServer.java | 2 +- ...impleProcessorBenchmarkClientRunnable.java | 51 ++-- .../heartbeat/HeartBeatExchangeHandler.java | 4 +- dubbo-tracker/dubbo-tracker-api/pom.xml | 11 +- .../alibaba/dubbo/tracker/DubboRequest.java | 19 +- .../tracker/DubboRequestSpanNameProvider.java | 16 +- .../alibaba/dubbo/tracker/DubboResponse.java | 2 +- .../alibaba/dubbo/tracker/RpcAttachment.java | 2 +- dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 12 - .../zipkin/DubboClientRequestAdapter.java | 5 +- ...DubboClientRequestResponseInterceptor.java | 9 +- .../dubbo/tracker/zipkin/DubboRpcTracker.java | 16 +- .../zipkin/DubboServerRequestAdapter.java | 4 +- ...DubboServerRequestResponseInterceptor.java | 8 +- .../http/AttachMethodNameInterceptor.java | 2 +- .../zipkin/http/HttpSpanNameProvider.java | 2 +- dubbo/pom.xml | 5 +- pom.xml | 1 - 219 files changed, 1653 insertions(+), 1728 deletions(-) delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java create mode 100644 dubbo-remoting/dubbo-remoting-common/pom.xml rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception}/ExecutionException.java (95%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception}/RemotingException.java (69%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception}/TimeoutException.java (92%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message}/Interceptor.java (76%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message}/Message.java (52%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message}/Request.java (96%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message}/Response.java (98%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/Channel.java (80%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/ChannelHandler.java (94%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/Client.java (85%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/Endpoint.java (81%) rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/Server.java (87%) mode change 100755 => 100644 rename dubbo-remoting/{dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting => dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport}/Transporter.java (77%) rename dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Transporter => com.alibaba.dubbo.remoting.transport.Transporter} (100%) rename dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Transporter => com.alibaba.dubbo.remoting.transport.Transporter} (100%) rename dubbo-remoting/dubbo-remoting-netty/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Transporter => com.alibaba.dubbo.remoting.transport.Transporter} (100%) delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcConstants.java create mode 100644 dubbo-rpc/dubbo-rpc-common/pom.xml diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index f1bd9473246..89383559b89 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -23,7 +23,7 @@ import com.alibaba.dubbo.registry.support.AbstractRegistryFactory; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Dispatcher; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.rpc.Protocol; diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index adbb9648498..ce63854e927 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -20,7 +20,7 @@ import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.remoting.Dispatcher; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 4830404ef2b..d46308dad7c 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -62,7 +62,7 @@ - + diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java index e9e3e931711..d2fa33993ab 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java @@ -18,9 +18,11 @@ import java.net.InetSocketAddress; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; public class MockChannel implements ExchangeChannel { diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java index ee819a0abcd..ae43f392f5d 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java @@ -16,12 +16,15 @@ package com.alibaba.dubbo.registry.dubbo; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.Replier; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.net.InetSocketAddress; import java.util.Map; @@ -93,6 +96,11 @@ public boolean isDone() { return true; } + @Override + public void cancel() { + + } + public void setCallback(ResponseCallback callback) { } }; diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index c8fe1460033..3e533158c91 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -34,5 +34,20 @@ dubbo-common ${project.parent.version} + + com.alibaba + dubbo-remoting-common + ${project.parent.version} + + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + + + com.alibaba + dubbo-tracker-zipkin + ${project.parent.version} + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java index 29e7be83eba..9771c8fcb16 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java @@ -22,6 +22,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.transport.Channel; /** * Codec. (SPI, Singleton, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java index bfdc7871d77..7da41bf452c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java @@ -21,6 +21,7 @@ import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.transport.Channel; /** * @author kimi diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Decodeable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Decodeable.java index 7020ee851f2..3f8fc737436 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Decodeable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Decodeable.java @@ -21,6 +21,6 @@ */ public interface Decodeable { - public void decode() throws Exception; + void decode() throws Exception; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index 2699fcb0e12..556d1106848 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -19,6 +19,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporters.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporters.java index 5f1d99c5c74..b6b8ee774de 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporters.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporters.java @@ -18,6 +18,11 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.transport.Server; +import com.alibaba.dubbo.remoting.transport.Transporter; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDispatcher; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java index 9a63c4c823f..7ff157ad0fc 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java @@ -15,8 +15,10 @@ */ package com.alibaba.dubbo.remoting.exchange; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; /** * ExchangeChannel. (API/SPI, Prototype, ThreadSafe) @@ -26,7 +28,7 @@ public interface ExchangeChannel extends Channel { /** - * send request. + * send request and receive response async * * @param request * @return response future @@ -35,7 +37,7 @@ public interface ExchangeChannel extends Channel { ResponseFuture request(Object request) throws RemotingException; /** - * send request. + * send request and receive response async * * @param request * @param timeout @@ -45,7 +47,7 @@ public interface ExchangeChannel extends Channel { ResponseFuture request(Object request, int timeout) throws RemotingException; /** - * send and receive + * send request and receive response sync * * @param request * @return @@ -54,7 +56,7 @@ public interface ExchangeChannel extends Channel { Response execute(Request request) throws RemotingException; /** - * send and receive + * send request and receive response sync * * @param request * @param timeout diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java deleted file mode 100644 index 0cdd8140275..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannelV2.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.alibaba.dubbo.remoting.exchange; - -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; - -public interface ExchangeChannelV2 extends Channel { - /** - * send request. - * - * @param request - * @return response - * @throws RemotingException - */ - Response request(Request request) throws RemotingException; - - /** - * send request. - * - * @param request - * @param timeout - * @return response future - * @throws RemotingException - */ - Response request(Request request, int timeout) throws RemotingException; - - /** - * get message handler. - * - * @return message handler - */ - ExchangeHandler getExchangeHandler(); - - /** - * graceful close. - * - * @param timeout - */ - void close(int timeout); - -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java index 67c8b54e4b8..072a7170287 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClient.java @@ -15,7 +15,8 @@ */ package com.alibaba.dubbo.remoting.exchange; -import com.alibaba.dubbo.remoting.Client; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.message.Interceptor; /** * ExchangeClient. (API/SPI, Prototype, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java deleted file mode 100644 index 3722c7b9a9f..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeClientV2.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.alibaba.dubbo.remoting.exchange; - -import com.alibaba.dubbo.remoting.Client; - -public interface ExchangeClientV2 extends Client, ExchangeChannelV2 { - - void addInterceptor(Interceptor interceptor); - -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeHandler.java index b5e183bf77a..3259c20e933 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeHandler.java @@ -15,8 +15,8 @@ */ package com.alibaba.dubbo.remoting.exchange; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeServer.java index 55ff1ba549b..53db6aeafcf 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeServer.java @@ -18,7 +18,7 @@ import java.net.InetSocketAddress; import java.util.Collection; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.Server; /** * ExchangeServer. (API/SPI, Prototype, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java index c303e420408..942de3035e1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchanger; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchangers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchangers.java index 4f6c21a6e58..3217ed8013a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchangers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchangers.java @@ -19,8 +19,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher; import com.alibaba.dubbo.remoting.exchange.support.Replier; import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java index 69eb691c6cc..7f39ef6721e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java @@ -15,7 +15,7 @@ */ package com.alibaba.dubbo.remoting.exchange; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Future. (API/SPI, Prototype, ThreadSafe) @@ -56,4 +56,6 @@ public interface ResponseFuture { */ boolean isDone(); + void cancel(); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 517ada17c95..063c896c484 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -25,14 +25,13 @@ import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; import com.alibaba.dubbo.remoting.transport.CodecSupport; @@ -163,7 +162,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro if (isEvent) { data = decodeEventData(channel, in); } else { - data = decodeResponseData(channel, in, getRequestData(id)); + data = decodeResponseData(channel, in); } builder.result(data); } catch (Throwable t) { @@ -199,16 +198,6 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } } - protected Object getRequestData(long id) { - DefaultFuture future = DefaultFuture.getFuture(id); - if (future == null) - return null; - Request req = future.getRequest(); - if (req == null) - return null; - return req.getData(); - } - protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException { Serialization serialization = getSerialization(channel); // header. @@ -303,7 +292,6 @@ protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response re // 发送失败信息给Consumer,否则Consumer只能等超时了 if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { try { - // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理? logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); Response.Builder builder = new Response.Builder(res.getId()); builder.version(res.getVersion()).status(Response.BAD_RESPONSE); @@ -387,10 +375,6 @@ protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOEx return decodeResponseData(in); } - protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { - return decodeResponseData(channel, in); - } - @Override protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java index 0bd4378d8a4..cc300159687 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java @@ -18,13 +18,13 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ResponseCallback; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.text.SimpleDateFormat; import java.util.Date; @@ -80,10 +80,18 @@ public DefaultFuture(Channel channel, Request request, int timeout) { CHANNELS.put(id, channel); } + /** + * 同步等待结果 + * + * @return + * @throws RemotingException + */ + @Deprecated public Object get() throws RemotingException { return get(timeout); } + @Deprecated public Object get(int timeout) throws RemotingException { if (timeout <= 0) { timeout = Constants.DEFAULT_TIMEOUT; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java index 378d7fbb6fd..0c9cc135977 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java @@ -15,7 +15,7 @@ */ package com.alibaba.dubbo.remoting.exchange.support; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.telnet.support.TelnetHandlerAdapter; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java index 895b1904a6b..b6b214f6e86 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java @@ -15,9 +15,9 @@ */ package com.alibaba.dubbo.remoting.exchange.support; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeServerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeServerDelegate.java index b15efcd8f32..8893df5407a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeServerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ExchangeServerDelegate.java @@ -19,9 +19,9 @@ import java.util.Collection; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/Replier.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/Replier.java index 01a3c95cd00..995009c3865 100755 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/Replier.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/Replier.java @@ -15,7 +15,7 @@ */ package com.alibaba.dubbo.remoting.exchange.support; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ReplierDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ReplierDispatcher.java index 8a7ff7c521b..68dd9bbf132 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ReplierDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/ReplierDispatcher.java @@ -18,7 +18,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java index d62ef998e50..5a3d7ea619f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java @@ -15,7 +15,7 @@ */ package com.alibaba.dubbo.remoting.exchange.support; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ResponseCallback; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; @@ -48,4 +48,9 @@ public boolean isDone() { return true; } + @Override + public void cancel() { + + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index f309bad0936..a76d81ef74b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -20,12 +20,14 @@ import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; @@ -110,7 +112,7 @@ public ResponseFuture request(Object request, int timeout) throws RemotingExcept Request.Builder builder = new Request.Builder(); builder.newId().version(Version.getVersion()).twoWay(true).data(request); Request req = builder.build(); - DefaultFuture future = new DefaultFuture(channel, req, timeout); + ResponseFuture future = new DefaultFuture(channel, req, timeout); try { channel.send(req); } catch (RemotingException e) { @@ -143,7 +145,7 @@ public Response execute(Request request, int timeout) throws RemotingException { LinkedBlockingQueue reply = pendingReply.getQueue(); Response response = null; try { - response = (timeout < 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); + response = (timeout <= 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RemotingException(this, e); } finally { @@ -193,7 +195,7 @@ public void close() { } } - // graceful close + // gracefully close public void close(int timeout) { if (closed) { return; @@ -201,8 +203,7 @@ public void close(int timeout) { closed = true; if (timeout > 0) { long start = System.currentTimeMillis(); - while (DefaultFuture.hasFuture(HeaderExchangeChannel.this) - && System.currentTimeMillis() - start < timeout) { + while (shouldWait(start, timeout)) { try { Thread.sleep(10); } catch (InterruptedException e) { @@ -213,6 +214,11 @@ public void close(int timeout) { close(); } + private boolean shouldWait(long start, long timeout) { + return (System.currentTimeMillis() - start < timeout) && + (DefaultFuture.hasFuture(HeaderExchangeChannel.this) || !REPLY_HOLDER.isEmpty()); + } + public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 15b617a6a85..8b745f7ab5d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -17,15 +17,17 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.net.InetSocketAddress; import java.util.ArrayList; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 09dbfa03998..a7cd811ca40 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -21,12 +21,15 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.ExecutionException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 750bf2f9560..bdd93fe7e80 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -21,14 +21,14 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.message.Request; import java.net.InetSocketAddress; import java.util.ArrayList; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 786bf2f425b..603f771c096 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -16,29 +16,54 @@ package com.alibaba.dubbo.remoting.exchange.support.header; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.Transporters; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.transport.DecodeHandler; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.zipkin.DubboClientRequestResponseInterceptor; +import com.alibaba.dubbo.tracker.zipkin.DubboRpcTracker; +import com.alibaba.dubbo.tracker.zipkin.DubboServerRequestResponseInterceptor; /** * DefaultMessenger - * + * * @author william.liangf */ public class HeaderExchanger implements Exchanger { - + public static final String NAME = "header"; + // for test + public static RpcTrackerEngine rpcTrackerEngine; + public static DubboRpcTracker rpcTracker; + + static { + URL url = URL.valueOf("zipkin://localhost:9411?application=consumer&collector=http&sampler=counting&rate=1"); + rpcTrackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); + url = URL.valueOf("dubbo://localhost:9411?application=consumer&collector=http&sampler=counting&rate=0.2"); + rpcTracker = (DubboRpcTracker) RpcTrackerManager.createRpcTracker(url); + } + public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { - return new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); + HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); + DubboClientRequestResponseInterceptor interceptor = new DubboClientRequestResponseInterceptor(rpcTracker.clientRequestInterceptor(), + rpcTracker.clientResponseInterceptor(), new DubboRequestSpanNameProvider()); + headerExchangeClient.addInterceptor(interceptor); + return headerExchangeClient; } public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { - return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); + HeaderExchangeHandler exchangeHandler = new HeaderExchangeHandler(handler); + DubboServerRequestResponseInterceptor interceptor = new DubboServerRequestResponseInterceptor(rpcTracker.serverRequestInterceptor(), + rpcTracker.serverResponseInterceptor(), new DubboRequestSpanNameProvider()); + exchangeHandler.addInterceptor(interceptor); + return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(exchangeHandler))); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java index a3197bed9d9..14d7cce5b39 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTask.java @@ -19,9 +19,9 @@ import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.message.Request; import java.util.Collection; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java index 44ec5f90282..0c18f1a21ec 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandler.java @@ -19,11 +19,11 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.AbstractChannelHandlerDelegate; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java index bf13f75372c..1fe75c0d20f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java @@ -1,6 +1,7 @@ package com.alibaba.dubbo.remoting.exchange.support.header; -import com.alibaba.dubbo.remoting.exchange.Response; + +import com.alibaba.dubbo.remoting.message.Response; import java.util.concurrent.LinkedBlockingQueue; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java index da73d398a19..84885e3ef31 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java @@ -16,8 +16,8 @@ package com.alibaba.dubbo.remoting.telnet; import com.alibaba.dubbo.common.extension.SPI; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * TelnetHandler diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java index 8725aa3df1d..a49f671d29c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -20,8 +20,8 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.transport.codec.TransportCodec; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 74b10bb5a6f..9a77de9c5c7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -17,8 +17,8 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java index 13772e44648..00f48b87e69 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java @@ -17,7 +17,7 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java index 7b4d328d353..955acb30e6c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.telnet.support.command; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java index d122792c049..b88f5ad9709 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java @@ -20,7 +20,7 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.remoting.telnet.support.TelnetUtils; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/LogTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/LogTelnetHandler.java index e2e7ab68839..2f587e38702 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/LogTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/LogTelnetHandler.java @@ -1,41 +1,41 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.telnet.support.command; -import java.io.File; -import java.io.FileInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.common.logger.Level; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.telnet.TelnetHandler; -import com.alibaba.dubbo.remoting.telnet.support.Help; +import java.io.File; +import java.io.FileInputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.common.logger.Level; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.telnet.TelnetHandler; +import com.alibaba.dubbo.remoting.telnet.support.Help; /** * LogTelnetHandler * @author chao.liuc * - */ + */ @Activate @Help(parameter = "level", summary = "Change log level or show log ", detail = "Change log level or show log") public class LogTelnetHandler implements TelnetHandler { @@ -57,9 +57,9 @@ public String telnet(Channel channel, String message) { if (file != null && file.exists()) { try{ - FileInputStream fis = new FileInputStream(file); + FileInputStream fis = new FileInputStream(file); try { - FileChannel filechannel = fis.getChannel(); + FileChannel filechannel = fis.getChannel(); try { size = filechannel.size(); ByteBuffer bb; @@ -78,12 +78,12 @@ public String telnet(Channel channel, String message) { buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(file.lastModified())))); - buf.append("\r\nsize:"+size +"\r\n"); - } finally { - filechannel.close(); - } - } finally { - fis.close(); + buf.append("\r\nsize:"+size +"\r\n"); + } finally { + filechannel.close(); + } + } finally { + fis.close(); } }catch (Exception e) { buf.append(e.getMessage()); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java index 7014a6cec94..8c02ecaab3e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java @@ -26,7 +26,7 @@ import com.alibaba.dubbo.common.status.Status; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.common.status.support.StatusUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.remoting.telnet.support.TelnetUtils; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannel.java index 0bd04baa47f..5ca4f025e22 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannel.java @@ -16,9 +16,7 @@ package com.alibaba.dubbo.remoting.transport; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * AbstractChannel diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java index 2429af2b622..422f9c0b1bb 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractChannelHandlerDelegate.java @@ -1,9 +1,7 @@ package com.alibaba.dubbo.remoting.transport; import com.alibaba.dubbo.common.utils.Assert; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author kimi diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java index 7b1d0ee9606..365b480f32a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java @@ -25,10 +25,7 @@ import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; import java.net.InetSocketAddress; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java index 47f997f6e86..1e2d6a85332 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java @@ -24,7 +24,6 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec2; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java index 3aacabe0588..8a179d6bf1b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java @@ -21,7 +21,6 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.transport.codec.CodecAdapter; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractPeer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractPeer.java index 353d54af771..1fa86aaf1e1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractPeer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractPeer.java @@ -17,10 +17,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Endpoint; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * AbstractPeer diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java index 3788994f2cd..789098a07f4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java @@ -28,10 +28,7 @@ import com.alibaba.dubbo.common.store.DataStore; import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * AbstractServer diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelDelegate.java index 639f95fbd29..8f71bae26ac 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelDelegate.java @@ -18,9 +18,7 @@ import java.net.InetSocketAddress; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * ChannelDelegate diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerAdapter.java index f77605e8958..7b1c777d692 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerAdapter.java @@ -1,23 +1,21 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * ChannelHandlerAdapter. diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java index 6c90fdf6d58..d56508978a1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDelegate.java @@ -15,8 +15,6 @@ */ package com.alibaba.dubbo.remoting.transport; -import com.alibaba.dubbo.remoting.ChannelHandler; - /** * @author chao.liuc */ diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDispatcher.java index 76fdd560dbc..2151fdbfc09 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandlerDispatcher.java @@ -21,8 +21,6 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; /** * ChannelListenerDispatcher diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ClientDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ClientDelegate.java index 6bb445df203..5f4be20242b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ClientDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ClientDelegate.java @@ -18,9 +18,7 @@ import java.net.InetSocketAddress; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * ClientDelegate diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java index 4c298ca290b..b101bd00338 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/DecodeHandler.java @@ -18,12 +18,10 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Decodeable; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; /** * @author kimi @@ -48,7 +46,6 @@ public void received(Channel channel, Object message) throws RemotingException { if (message instanceof Response) { decode(((Response) message).getResult()); } - handler.received(channel, message); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java index 032f47c19c4..52d3724f281 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java @@ -1,10 +1,7 @@ package com.alibaba.dubbo.remoting.transport; import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author kimi diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ServerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ServerDelegate.java index e91572e0b25..236c6a2bc99 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ServerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/ServerDelegate.java @@ -19,10 +19,7 @@ import java.util.Collection; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * ServerDelegate diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java index c3ab52c2996..159b1f8ad99 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java @@ -21,7 +21,7 @@ import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.common.utils.Assert; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java index 90629c74c36..aa6c28cf6ae 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java @@ -23,7 +23,7 @@ import com.alibaba.dubbo.common.serialize.ObjectInput; import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java index 2586e0ab0ba..fefa67f2899 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java @@ -17,8 +17,8 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; /** * @author chao.liuc diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java index 5590d7b543b..b08efc7db6e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java @@ -18,7 +18,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.exchange.support.header.HeartbeatHandler; import com.alibaba.dubbo.remoting.transport.MultiMessageHandler; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index dae2156bfa3..076b3ec2d2e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -26,9 +26,9 @@ import com.alibaba.dubbo.common.store.DataStore; import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; public class WrappedChannelHandler implements ChannelHandlerDelegate { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java index 1268cdb1418..f036a0f5872 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java @@ -18,10 +18,10 @@ import java.util.concurrent.ExecutorService; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.ExecutionException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java index 30d5ec6d675..79bd97a3cc3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.all; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index 4dff6d5a3d1..17069a424ba 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -24,10 +24,10 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.threadpool.support.AbortPolicyWithReport; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.ExecutionException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java index ee9fe27e4a1..bf1c4549b2b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.connection; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java index 5eab7be3a82..e9fc8d9c803 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.direct; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java index ffe113a87ac..7214e98b8bf 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java @@ -16,9 +16,9 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.execution; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java index d72f9d6983a..8477a3f7534 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.execution; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java index 19a112970f2..b801b404775 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java @@ -18,10 +18,10 @@ import java.util.concurrent.ExecutorService; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.ExecutionException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java index 4326aaec270..6be3d0dfb3a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.transport.dispatcher.message; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/ChanelHandlerTest.java index 1917fd6cda7..6f3bb9ad3a7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/ChanelHandlerTest.java @@ -1,20 +1,22 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import junit.framework.TestCase; import org.junit.Test; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java index f078531d727..59433cda032 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java @@ -1,25 +1,20 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting; -import java.io.Serializable; -import java.util.Random; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.Exchangers; @@ -27,116 +22,112 @@ import com.alibaba.dubbo.remoting.exchange.support.Replier; import com.alibaba.dubbo.remoting.exchange.support.ReplierDispatcher; +import java.io.Serializable; +import java.util.Random; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + /** * Main */ -public class Main -{ - public static void main(String[] args) throws Exception - { - startServer(9010); - mutliThreadTest(10,9010); - dataPackageTest(9010); - } - - private static void startServer(int port) throws Exception - { - ReplierDispatcher dispatcher = new ReplierDispatcher(); - dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); - dispatcher.addReplier(Object.class, new Replier() { - public Object reply(ExchangeChannel channel, Object msg) - { - for(int i=0;i<10000;i++) - System.currentTimeMillis(); - System.out.println("handle:"+msg+";thread:"+Thread.currentThread().getName()); - return new StringMessage("hello world"); - } - }); - Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); - } - - static void dataPackageTest(int port) throws Exception - { - ExchangeChannel client = Exchangers.connect(URL.valueOf("dubbo://localhost:" + port)); - Random random = new Random(); - for(int i=5;i<100;i++) - { - StringBuilder sb = new StringBuilder(); - for(int j=0;j[]{int.class, int.class},new Object[]{55,25})).get(); - System.out.println("55+25="+result.getResult()); - - for(int i=0;i<100;i++) - client.request(new RpcMessage(DemoService.class.getName(),"sayHello", new Class[]{String.class},new Object[]{"qianlei"+i})); - - for(int i=0;i<100;i++) - client.request(new Main.Data()); - - System.out.println("=====test invoke====="); - for(int i=0;i<100;i++){ - ResponseFuture future = client.request(new Main.Data()); - System.out.println("invoke and get"); - System.out.println("invoke result:" + future.get()); - } - System.out.println("=====the end====="); - } - - static class Data implements Serializable - { - private static final long serialVersionUID = -4666580993978548778L; - - private String mData = ""; - - public Data(){} - - public String getData() - { - return mData; - } - - public void setData(String data) - { - mData = data; - } - } - - static class StringMessage implements Serializable - { - private static final long serialVersionUID = 7193122183120113947L; - - private String mText; - - StringMessage(String msg) - { - mText = msg; - } - - public String toString() - { - return mText; - } - } +public class Main { + public static void main(String[] args) throws Exception { + startServer(9010); + mutliThreadTest(10, 9010); + dataPackageTest(9010); + } + + private static void startServer(int port) throws Exception { + ReplierDispatcher dispatcher = new ReplierDispatcher(); + dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); + dispatcher.addReplier(Object.class, new Replier() { + public Object reply(ExchangeChannel channel, Object msg) { + for (int i = 0; i < 10000; i++) + System.currentTimeMillis(); + System.out.println("handle:" + msg + ";thread:" + Thread.currentThread().getName()); + return new StringMessage("hello world"); + } + }); + Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); + } + + static void dataPackageTest(int port) throws Exception { + ExchangeChannel client = Exchangers.connect(URL.valueOf("dubbo://localhost:" + port)); + Random random = new Random(); + for (int i = 5; i < 100; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < i * 100; j++) + sb.append("(" + random.nextLong() + ")"); + Main.Data d = new Main.Data(); + d.setData(sb.toString()); + client.request(d).get(); + } + System.out.println("send finished."); + } + + static void mutliThreadTest(int tc, final int port) throws Exception { + Executor exec = Executors.newFixedThreadPool(tc); + for (int i = 0; i < tc; i++) + exec.execute(new Runnable() { + public void run() { + try { + test(port); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + private static void test(int port) throws Exception { + ExchangeChannel client = Exchangers.connect(URL.valueOf("dubbo://localhost:" + port)); + MockResult result = (MockResult) client.request(new RpcMessage(DemoService.class.getName(), "plus", new Class[]{int.class, int.class}, new Object[]{55, 25})).get(); + System.out.println("55+25=" + result.getResult()); + + for (int i = 0; i < 100; i++) + client.request(new RpcMessage(DemoService.class.getName(), "sayHello", new Class[]{String.class}, new Object[]{"qianlei" + i})); + + for (int i = 0; i < 100; i++) + client.request(new Main.Data()); + + System.out.println("=====test invoke====="); + for (int i = 0; i < 100; i++) { + ResponseFuture future = client.request(new Main.Data()); + System.out.println("invoke and get"); + System.out.println("invoke result:" + future.get()); + } + System.out.println("=====the end====="); + } + + static class Data implements Serializable { + private static final long serialVersionUID = -4666580993978548778L; + + private String mData = ""; + + public Data() { + } + + public String getData() { + return mData; + } + + public void setData(String data) { + mData = data; + } + } + + static class StringMessage implements Serializable { + private static final long serialVersionUID = 7193122183120113947L; + + private String mText; + + StringMessage(String msg) { + mText = msg; + } + + public String toString() { + return mText; + } + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java index 658de26aaca..442a3ff5fef 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java @@ -23,6 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import junit.framework.TestCase; import org.junit.Test; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java index b829cd1ce64..36fe74c223d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java @@ -18,6 +18,8 @@ import java.util.ArrayList; import java.util.List; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import junit.framework.TestCase; import org.junit.Test; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessageHandler.java index 0a12593856a..788d6ec79c7 100755 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessageHandler.java @@ -19,6 +19,7 @@ import com.alibaba.dubbo.common.bytecode.NoSuchMethodException; import com.alibaba.dubbo.common.bytecode.Wrapper; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.support.Replier; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/TelnetServer.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/TelnetServer.java index 637c9cec374..917de6f567f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/TelnetServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/TelnetServer.java @@ -15,6 +15,8 @@ */ package com.alibaba.dubbo.remoting; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/AbstractMockChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/AbstractMockChannel.java index 325a50c9555..46837a561d1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/AbstractMockChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/AbstractMockChannel.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.codec; import java.net.InetSocketAddress; @@ -21,9 +21,9 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author chao.liuc diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index b0a6da6cd0c..93347bb305f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -23,12 +23,12 @@ import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; import junit.framework.Assert; import org.junit.Before; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java index e3de9d3de87..b2e23a38591 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java @@ -28,7 +28,7 @@ import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index 2c963a1ac0d..744edff5312 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -18,8 +18,8 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.message.Request; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/MockChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/MockChannel.java index 4f00c6b588b..ac335627dd0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/MockChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/MockChannel.java @@ -17,9 +17,9 @@ package com.alibaba.dubbo.remoting.exchange.support.header; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import java.net.InetSocketAddress; import java.util.ArrayList; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java index 83985305d0c..3cc9e6e7b19 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java @@ -16,10 +16,10 @@ package com.alibaba.dubbo.remoting.handler; import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.remoting.ExecutionException; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exception.ExecutionException; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; import junit.framework.Assert; import org.junit.Before; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index 49de50a650d..a009537637d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -18,13 +18,13 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import org.junit.Assert; import org.junit.Test; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannel.java index 512d5757187..aa95581f94b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannel.java @@ -1,28 +1,28 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.handler; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author chao.liuc @@ -31,7 +31,7 @@ public class MockedChannel implements Channel { private boolean isClosed ; private URL url; - private ChannelHandler handler ; + private ChannelHandler handler ; private Map map = new HashMap(); public MockedChannel() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannelHandler.java index 08744da1fc8..b3ad5fa383f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/MockedChannelHandler.java @@ -1,27 +1,27 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.handler; import java.util.Collections; import java.util.Set; import com.alibaba.dubbo.common.utils.ConcurrentHashSet; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author chao.liuc diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java index b086bf35377..54538be4b05 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.handler; @@ -26,9 +26,9 @@ import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; public class WrappedChannelHandlerTest { WrappedChannelHandler handler ; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java index e11070e0c6a..c00c053c89a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java @@ -18,7 +18,6 @@ import java.io.IOException; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; import junit.framework.TestCase; import static org.easymock.EasyMock.createMock; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java index 7852dde02e0..18250bb7579 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java @@ -1,20 +1,8 @@ package com.alibaba.dubbo.remoting.transport.codec; -import java.io.IOException; - import org.junit.Before; -import org.junit.Test; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.codec.ExchangeCodecTest; -import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; - -import junit.framework.Assert; /** * @author kimi diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java index 0fcbb3e6b17..51fc51fbfe2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java @@ -11,12 +11,12 @@ import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.CodecSupport; import java.io.IOException; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java index 74314cd3e18..0078778c83a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -17,10 +17,9 @@ import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.CodecSupport; /** diff --git a/dubbo-remoting/dubbo-remoting-common/pom.xml b/dubbo-remoting/dubbo-remoting-common/pom.xml new file mode 100644 index 00000000000..dbc3d3d9bf2 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-common/pom.xml @@ -0,0 +1,22 @@ + + + + dubbo-remoting + com.alibaba + 2.8.4 + + 4.0.0 + + dubbo-remoting-common + + + + com.alibaba + dubbo-common + 2.8.4 + + + + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ExecutionException.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/ExecutionException.java similarity index 95% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ExecutionException.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/ExecutionException.java index 86963866a9f..379ae928ad4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ExecutionException.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/ExecutionException.java @@ -1,68 +1,70 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import java.net.InetSocketAddress; - -/** - * ReceiveException - * - * @author william.liangf - * @export - */ -public class ExecutionException extends RemotingException { - - private static final long serialVersionUID = -2531085236111056860L; - - private final Object request; - - public ExecutionException(Object request, Channel channel, String message, Throwable cause){ - super(channel, message, cause); - this.request = request; - } - - public ExecutionException(Object request, Channel channel, String msg){ - super(channel, msg); - this.request = request; - } - - public ExecutionException(Object request, Channel channel, Throwable cause){ - super(channel, cause); - this.request = request; - } - - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, - Throwable cause){ - super(localAddress, remoteAddress, message, cause); - this.request = request; - } - - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message){ - super(localAddress, remoteAddress, message); - this.request = request; - } - - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause){ - super(localAddress, remoteAddress, cause); - this.request = request; - } - - - public Object getRequest() { - return request; - } - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.exception; + +import com.alibaba.dubbo.remoting.transport.Channel; + +import java.net.InetSocketAddress; + +/** + * ReceiveException + * + * @author william.liangf + * @export + */ +public class ExecutionException extends RemotingException { + + private static final long serialVersionUID = -2531085236111056860L; + + private final Object request; + + public ExecutionException(Object request, Channel channel, String message, Throwable cause){ + super(channel, message, cause); + this.request = request; + } + + public ExecutionException(Object request, Channel channel, String msg){ + super(channel, msg); + this.request = request; + } + + public ExecutionException(Object request, Channel channel, Throwable cause){ + super(channel, cause); + this.request = request; + } + + public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, + Throwable cause){ + super(localAddress, remoteAddress, message, cause); + this.request = request; + } + + public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message){ + super(localAddress, remoteAddress, message); + this.request = request; + } + + public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause){ + super(localAddress, remoteAddress, cause); + this.request = request; + } + + + public Object getRequest() { + return request; + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/RemotingException.java similarity index 69% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/RemotingException.java index ebdb50f5d87..de0adbfe737 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/RemotingException.java @@ -13,20 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting; +package com.alibaba.dubbo.remoting.exception; + +import com.alibaba.dubbo.remoting.transport.Channel; import java.net.InetSocketAddress; /** * RemotingException. (API, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get() - * @see com.alibaba.dubbo.remoting.exchange.ResponseFuture#get(int) - * @see com.alibaba.dubbo.remoting.Channel#send(Object, boolean) - * @see com.alibaba.dubbo.remoting.exchange.ExchangeChannel#request(Object) - * @see com.alibaba.dubbo.remoting.exchange.ExchangeChannel#request(Object, int) - * @see com.alibaba.dubbo.remoting.Transporter#bind(com.alibaba.dubbo.common.URL, ChannelHandler) - * @see com.alibaba.dubbo.remoting.Transporter#connect(com.alibaba.dubbo.common.URL, ChannelHandler) + * * @author qian.lei * @export */ @@ -38,37 +33,37 @@ public class RemotingException extends Exception { private InetSocketAddress remoteAddress; - public RemotingException(Channel channel, String msg){ + public RemotingException(Channel channel, String msg) { this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), - msg); + msg); } - public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message){ + public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(message); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } - public RemotingException(Channel channel, Throwable cause){ + public RemotingException(Channel channel, Throwable cause) { this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), - cause); + cause); } - public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause){ + public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) { super(cause); this.localAddress = localAddress; this.remoteAddress = remoteAddress; } - public RemotingException(Channel channel, String message, Throwable cause){ + public RemotingException(Channel channel, String message, Throwable cause) { this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), - message, cause); + message, cause); } public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, - Throwable cause){ + Throwable cause) { super(message, cause); this.localAddress = localAddress; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/TimeoutException.java similarity index 92% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/TimeoutException.java index d60d294b84b..054d7ecde33 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/TimeoutException.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/exception/TimeoutException.java @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting; +package com.alibaba.dubbo.remoting.exception; + +import com.alibaba.dubbo.remoting.transport.Channel; import java.net.InetSocketAddress; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Interceptor.java similarity index 76% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Interceptor.java index fdd1c54ae13..eec09cdf2a7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Interceptor.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Interceptor.java @@ -1,6 +1,7 @@ -package com.alibaba.dubbo.remoting.exchange; +package com.alibaba.dubbo.remoting.message; -import com.alibaba.dubbo.remoting.RemotingException; + +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author Xs diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Message.java similarity index 52% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Message.java index 2a802eaf83a..e0e6a9683e7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Message.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Message.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.remoting.exchange; +package com.alibaba.dubbo.remoting.message; /** * @author Xs. diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Request.java similarity index 96% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Request.java index fe48baf16d8..2603fd2f136 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Request.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.exchange; +package com.alibaba.dubbo.remoting.message; +import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.utils.StringUtils; import java.util.concurrent.atomic.AtomicLong; @@ -60,7 +61,7 @@ public Builder newBuilder() { public static class Builder { private long mId; - private String mVersion; + private String mVersion = Version.getVersion(); private boolean mTwoWay = true; private boolean mEvent = false; private boolean mBroken = false; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Response.java similarity index 98% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Response.java index ae812670aab..45cd88b5d28 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Response.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/message/Response.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.exchange; +package com.alibaba.dubbo.remoting.message; /** * Response diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Channel.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Channel.java similarity index 80% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Channel.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Channel.java index 465cadeb4eb..019dcc7f1c3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Channel.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Channel.java @@ -13,16 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting; +package com.alibaba.dubbo.remoting.transport; import java.net.InetSocketAddress; /** * Channel. (API/SPI, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.Client - * @see com.alibaba.dubbo.remoting.Server#getChannels() - * @see com.alibaba.dubbo.remoting.Server#getChannel(InetSocketAddress) + * * @author qian.lei * @author william.liangf */ @@ -30,21 +27,21 @@ public interface Channel extends Endpoint { /** * get remote address. - * + * * @return remote address. */ InetSocketAddress getRemoteAddress(); /** * is connected. - * + * * @return connected */ boolean isConnected(); /** * has attribute. - * + * * @param key key. * @return has or has not. */ @@ -52,7 +49,7 @@ public interface Channel extends Endpoint { /** * get attribute. - * + * * @param key key. * @return value. */ @@ -60,15 +57,15 @@ public interface Channel extends Endpoint { /** * set attribute. - * - * @param key key. + * + * @param key key. * @param value value. */ - void setAttribute(String key,Object value); - + void setAttribute(String key, Object value); + /** * remove attribute. - * + * * @param key key. */ void removeAttribute(String key); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java similarity index 94% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java index 6cc8777dd26..a93d8939e61 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting; +package com.alibaba.dubbo.remoting.transport; import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Client.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Client.java similarity index 85% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Client.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Client.java index f547b8a8d6d..187163f1bad 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Client.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Client.java @@ -1,38 +1,39 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import com.alibaba.dubbo.common.Resetable; - -/** - * Remoting Client. (API/SPI, Prototype, ThreadSafe) - * - * Client/Server - * - * @see com.alibaba.dubbo.remoting.Transporter#connect(com.alibaba.dubbo.common.URL, ChannelHandler) - * @author qian.lei - */ -public interface Client extends Endpoint, Channel, Resetable { - - /** - * reconnect. - */ - void reconnect() throws RemotingException; - - @Deprecated - void reset(com.alibaba.dubbo.common.Parameters parameters); - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport; + +import com.alibaba.dubbo.common.Resetable; +import com.alibaba.dubbo.remoting.exception.RemotingException; + +/** + * Remoting Client. (API/SPI, Prototype, ThreadSafe) + * + * Client/Server + * + * @see Transporter#connect(com.alibaba.dubbo.common.URL, ChannelHandler) + * @author qian.lei + */ +public interface Client extends Endpoint, Channel, Resetable { + + /** + * reconnect. + */ + void reconnect() throws RemotingException; + + @Deprecated + void reset(com.alibaba.dubbo.common.Parameters parameters); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Endpoint.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Endpoint.java similarity index 81% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Endpoint.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Endpoint.java index 267ad3031eb..b1ee26d1241 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Endpoint.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Endpoint.java @@ -1,86 +1,85 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import java.net.InetSocketAddress; - -import com.alibaba.dubbo.common.URL; - -/** - * Endpoint. (API/SPI, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.Channel - * @see com.alibaba.dubbo.remoting.Client - * @see com.alibaba.dubbo.remoting.Server - * @author william.liangf - */ -public interface Endpoint { - - /** - * get url. - * - * @return url - */ - URL getUrl(); - - /** - * get channel handler. - * - * @return channel handler - */ - ChannelHandler getChannelHandler(); - - /** - * get local address. - * - * @return local address. - */ - InetSocketAddress getLocalAddress(); - - /** - * send message. - * - * @param message - * @throws RemotingException - */ - void send(Object message) throws RemotingException; - - /** - * send message. - * - * @param message - * @param sent 是否已发送完成 - */ - void send(Object message, boolean sent) throws RemotingException; - - /** - * close the channel. - */ - void close(); - - /** - * Graceful close the channel. - */ - void close(int timeout); - - /** - * is closed. - * - * @return closed - */ - boolean isClosed(); - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.exception.RemotingException; + +import java.net.InetSocketAddress; + +/** + * Endpoint. (API/SPI, Prototype, ThreadSafe) + * + * @author william.liangf + * @see Channel + */ +public interface Endpoint { + + /** + * get url. + * + * @return url + */ + URL getUrl(); + + /** + * get channel handler. + * + * @return channel handler + */ + ChannelHandler getChannelHandler(); + + /** + * get local address. + * + * @return local address. + */ + InetSocketAddress getLocalAddress(); + + /** + * send message. + * + * @param message + * @throws RemotingException + */ + void send(Object message) throws RemotingException; + + /** + * send message. + * + * @param message + * @param sent 是否已发送完成 + */ + void send(Object message, boolean sent) throws RemotingException; + + /** + * close the channel. + */ + void close(); + + /** + * Graceful close the channel. + */ + void close(int timeout); + + /** + * is closed. + * + * @return closed + */ + boolean isClosed(); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Server.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Server.java old mode 100755 new mode 100644 similarity index 87% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Server.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Server.java index afe655a78a1..0e2e64d3e26 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Server.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Server.java @@ -1,58 +1,58 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import java.net.InetSocketAddress; -import java.util.Collection; - -import com.alibaba.dubbo.common.Resetable; - -/** - * Remoting Server. (API/SPI, Prototype, ThreadSafe) - * - * Client/Server - * - * @see com.alibaba.dubbo.remoting.Transporter#bind(com.alibaba.dubbo.common.URL, ChannelHandler) - * @author qian.lei - */ -public interface Server extends Endpoint, Resetable { - - /** - * is bound. - * - * @return bound - */ - boolean isBound(); - - /** - * get channels. - * - * @return channels - */ - Collection getChannels(); - - /** - * get channel. - * - * @param remoteAddress - * @return channel - */ - Channel getChannel(InetSocketAddress remoteAddress); - - @Deprecated - void reset(com.alibaba.dubbo.common.Parameters parameters); - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport; + +import java.net.InetSocketAddress; +import java.util.Collection; + +import com.alibaba.dubbo.common.Resetable; + +/** + * Remoting Server. (API/SPI, Prototype, ThreadSafe) + * + * Client/Server + * + * @see Transporter#bind(com.alibaba.dubbo.common.URL, ChannelHandler) + * @author qian.lei + */ +public interface Server extends Endpoint, Resetable { + + /** + * is bound. + * + * @return bound + */ + boolean isBound(); + + /** + * get channels. + * + * @return channels + */ + Collection getChannels(); + + /** + * get channel. + * + * @param remoteAddress + * @return channel + */ + Channel getChannel(InetSocketAddress remoteAddress); + + @Deprecated + void reset(com.alibaba.dubbo.common.Parameters parameters); + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporter.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Transporter.java similarity index 77% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporter.java rename to dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Transporter.java index 9408c6590a7..6b54e017708 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Transporter.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/Transporter.java @@ -13,22 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting; - -import javax.sound.midi.Receiver; +package com.alibaba.dubbo.remoting.transport; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Transporter. (SPI, Singleton, ThreadSafe) - * + *

* Transport Layer * Client/Server - * - * @see com.alibaba.dubbo.remoting.Transporters + * * @author ding.lid * @author william.liangf */ @@ -37,24 +35,22 @@ public interface Transporter { /** * Bind a server. - * - * @see com.alibaba.dubbo.remoting.Transporters#bind(URL, Receiver, ChannelHandler) - * @param url server url + * + * @param url server url * @param handler * @return server - * @throws RemotingException + * @throws RemotingException */ @Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY}) Server bind(URL url, ChannelHandler handler) throws RemotingException; /** * Connect to a server. - * - * @see com.alibaba.dubbo.remoting.Transporters#connect(URL, Receiver, ChannelListener) - * @param url server url + * + * @param url server url * @param handler * @return client - * @throws RemotingException + * @throws RemotingException */ @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyChannel.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyChannel.java index 65df0cffb1d..4dd9f33fe0c 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyChannel.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyChannel.java @@ -28,8 +28,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractChannel; /** diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyClient.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyClient.java index 34a60506642..55ca7e3a393 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyClient.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyClient.java @@ -29,9 +29,9 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractClient; /** diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java index f3169e63ffe..caf2d71a1bf 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java @@ -25,9 +25,9 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyHandler.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyHandler.java index f7196cd305b..66b54c1e2ff 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyHandler.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyHandler.java @@ -26,8 +26,8 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * GrizzlyHandler diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyServer.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyServer.java index 67ce00577c3..2a6d00813e5 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyServer.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyServer.java @@ -33,9 +33,9 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractServer; /** diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java index 5f663228056..0f130c60911 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java @@ -16,11 +16,11 @@ package com.alibaba.dubbo.remoting.transport.grizzly; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; +import com.alibaba.dubbo.remoting.transport.Transporter; /** * GrizzlyTransporter diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter b/dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter similarity index 100% rename from dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter rename to dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaChannel.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaChannel.java index 12fd662a7db..1e731006c85 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaChannel.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaChannel.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.mina; import java.net.InetSocketAddress; @@ -24,8 +24,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractChannel; /** diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaClient.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaClient.java index 47cae52af11..693cf237efb 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaClient.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaClient.java @@ -1,47 +1,47 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.mina; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.mina.common.ConnectFuture; -import org.apache.mina.common.IoFuture; -import org.apache.mina.common.IoFutureListener; -import org.apache.mina.common.IoSession; -import org.apache.mina.common.ThreadModel; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.SocketConnector; -import org.apache.mina.transport.socket.nio.SocketConnectorConfig; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.AbstractClient; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.mina.common.ConnectFuture; +import org.apache.mina.common.IoFuture; +import org.apache.mina.common.IoFutureListener; +import org.apache.mina.common.IoSession; +import org.apache.mina.common.ThreadModel; +import org.apache.mina.filter.codec.ProtocolCodecFilter; +import org.apache.mina.transport.socket.nio.SocketConnector; +import org.apache.mina.transport.socket.nio.SocketConnectorConfig; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.Version; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.AbstractClient; /** * Mina client. @@ -49,8 +49,8 @@ * @author qian.lei * @author william.liangf */ -public class MinaClient extends AbstractClient { - +public class MinaClient extends AbstractClient { + private static final Logger logger = LoggerFactory.getLogger(MinaClient.class); private static final Map connectors = new ConcurrentHashMap(); @@ -63,7 +63,7 @@ public class MinaClient extends AbstractClient { public MinaClient(final URL url, final ChannelHandler handler) throws RemotingException { super(url, wrapChannelHandler(url, handler)); - } + } @Override protected void doOpen() throws Throwable { diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java index 8d675af7b65..d77547645e6 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java @@ -25,9 +25,9 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaHandler.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaHandler.java index 75108f56167..8e5a5300119 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaHandler.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaHandler.java @@ -1,25 +1,25 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.mina; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; /** * MinaHandler diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java index b0191c6d50a..46553c68858 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java @@ -33,9 +33,9 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractServer; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaTransporter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaTransporter.java index 534f7f3d243..350b1d35ad2 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaTransporter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaTransporter.java @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.mina; - +package com.alibaba.dubbo.remoting.transport.mina; + import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; -import com.alibaba.dubbo.remoting.Transporter; - -/** - * @author ding.lid - */ -public class MinaTransporter implements Transporter { - - public static final String NAME = "mina"; - - public Server bind(URL url, ChannelHandler handler) throws RemotingException { - return new MinaServer(url, handler); - } - - public Client connect(URL url, ChannelHandler handler) throws RemotingException { - return new MinaClient(url, handler); - } - +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; +import com.alibaba.dubbo.remoting.transport.Transporter; + +/** + * @author ding.lid + */ +public class MinaTransporter implements Transporter { + + public static final String NAME = "mina"; + + public Server bind(URL url, ChannelHandler handler) throws RemotingException { + return new MinaServer(url, handler); + } + + public Client connect(URL url, ChannelHandler handler) throws RemotingException { + return new MinaClient(url, handler); + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter b/dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter similarity index 100% rename from dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter rename to dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java index d2b496f4ee2..13360386458 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.remoting.transport.mina; import junit.framework.Assert; @@ -20,7 +20,7 @@ import org.junit.Test; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientsTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientsTest.java index 98de2ea2b90..573af6ea0b7 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientsTest.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientsTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.remoting.transport.mina.MinaTransporter; /** diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/MinaClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/MinaClientToServerTest.java index b0313cebf5a..2f3a8a945ad 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/MinaClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/MinaClientToServerTest.java @@ -1,22 +1,22 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.remoting.transport.mina; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/WorldHandler.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/WorldHandler.java index 1175ab3e2fe..716b8a1e230 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/WorldHandler.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/WorldHandler.java @@ -1,21 +1,21 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.remoting.transport.mina; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.support.Replier; diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index afe4f789749..cbab97d96ab 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -34,6 +34,13 @@ dubbo-remoting-api ${project.parent.version} + + + com.alibaba + dubbo-remoting-common + ${project.parent.version} + + io.netty netty diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyChannel.java index 7335c17f994..969b6b03855 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyChannel.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; import java.net.InetSocketAddress; @@ -26,8 +26,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractChannel; /** @@ -98,17 +98,17 @@ public void send(Object message, boolean sent) throws RemotingException { ChannelFuture future = channel.write(message); if (sent) { timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - success = future.await(timeout); - } - Throwable cause = future.getCause(); - if (cause != null) { - throw cause; + success = future.await(timeout); + } + Throwable cause = future.getCause(); + if (cause != null) { + throw cause; } } catch (Throwable e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } - if(! success) { + if(! success) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java index 830cfb5e573..800097847a8 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java @@ -34,8 +34,8 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractClient; /** @@ -172,7 +172,7 @@ protected void doClose() throws Throwable { } @Override - protected com.alibaba.dubbo.remoting.Channel getChannel() { + protected com.alibaba.dubbo.remoting.transport.Channel getChannel() { Channel c = channel; if (c == null || ! c.isConnected()) return null; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java index 9173ac370fd..24f31840697 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -51,9 +51,9 @@ final class NettyCodecAdapter { private final int bufferSize; - private final com.alibaba.dubbo.remoting.ChannelHandler handler; + private final com.alibaba.dubbo.remoting.transport.ChannelHandler handler; - public NettyCodecAdapter(Codec2 codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) { + public NettyCodecAdapter(Codec2 codec, URL url, com.alibaba.dubbo.remoting.transport.ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHandler.java index 1a05bd1ec87..c7a6379dba5 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHandler.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; import java.net.InetSocketAddress; @@ -28,8 +28,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; /** * NettyHandler @@ -74,7 +74,7 @@ public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) thr } @Override - public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { + public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress())); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java index bb67ca1c606..f427be2ad64 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java @@ -22,10 +22,10 @@ import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.transport.AbstractServer; import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; import org.jboss.netty.bootstrap.ServerBootstrap; @@ -104,9 +104,9 @@ protected void doClose() throws Throwable { logger.warn(e.getMessage(), e); } try { - Collection channels = getChannels(); + Collection channels = getChannels(); if (channels != null && channels.size() > 0) { - for (com.alibaba.dubbo.remoting.Channel channel : channels) { + for (Channel channel : channels) { try { channel.close(); } catch (Throwable e) { diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyTransporter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyTransporter.java index f899a6f7d2c..1f78fbf8cca 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyTransporter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyTransporter.java @@ -13,28 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.netty; - +package com.alibaba.dubbo.remoting.transport.netty; + import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; -import com.alibaba.dubbo.remoting.Transporter; - -/** - * @author ding.lid - */ -public class NettyTransporter implements Transporter { - - public static final String NAME = "netty"; - - public Server bind(URL url, ChannelHandler listener) throws RemotingException { - return new NettyServer(url, listener); - } - - public Client connect(URL url, ChannelHandler listener) throws RemotingException { - return new NettyClient(url, listener); - } - +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; +import com.alibaba.dubbo.remoting.transport.Transporter; + +/** + * @author ding.lid + */ +public class NettyTransporter implements Transporter { + + public static final String NAME = "netty"; + + public Server bind(URL url, ChannelHandler listener) throws RemotingException { + return new NettyServer(url, listener); + } + + public Client connect(URL url, ChannelHandler listener) throws RemotingException { + return new NettyClient(url, listener); + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter b/dubbo-remoting/dubbo-remoting-netty/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter similarity index 100% rename from dubbo-remoting/dubbo-remoting-netty/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter rename to dubbo-remoting/dubbo-remoting-netty/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index d269b72e593..01d8a075b5d 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -23,8 +23,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java index cc68e644c7a..3aab778d874 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java @@ -18,7 +18,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; /** diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientReconnectTest.java index f6ae87975fd..26865481076 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientReconnectTest.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.netty; - +package com.alibaba.dubbo.remoting.transport.netty; + import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; @@ -23,45 +23,45 @@ import com.alibaba.dubbo.common.utils.DubboAppender; import com.alibaba.dubbo.common.utils.LogUtil; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; - -/** - * 客户端重连测试 - * @author chao.liuc - * - */ -public class ClientReconnectTest { - @Test - public void testReconnect() throws RemotingException, InterruptedException{ - { - int port = NetUtils.getAvailablePort(); - Client client = startClient(port, 200); - Assert.assertEquals(false, client.isConnected()); - Server server = startServer(port); - for (int i = 0; i < 100 && ! client.isConnected(); i++) { - Thread.sleep(10); - } - Assert.assertEquals(true, client.isConnected()); - client.close(2000); - server.close(2000); - } - { - int port = NetUtils.getAvailablePort(); - Client client = startClient(port, 20000); - Assert.assertEquals(false, client.isConnected()); - Server server = startServer(port); - for(int i=0;i<5;i++){ - Thread.sleep(200); - } - Assert.assertEquals(false, client.isConnected()); - client.close(2000); - server.close(2000); - } + +/** + * 客户端重连测试 + * @author chao.liuc + * + */ +public class ClientReconnectTest { + @Test + public void testReconnect() throws RemotingException, InterruptedException{ + { + int port = NetUtils.getAvailablePort(); + Client client = startClient(port, 200); + Assert.assertEquals(false, client.isConnected()); + Server server = startServer(port); + for (int i = 0; i < 100 && ! client.isConnected(); i++) { + Thread.sleep(10); + } + Assert.assertEquals(true, client.isConnected()); + client.close(2000); + server.close(2000); + } + { + int port = NetUtils.getAvailablePort(); + Client client = startClient(port, 20000); + Assert.assertEquals(false, client.isConnected()); + Server server = startServer(port); + for(int i=0;i<5;i++){ + Thread.sleep(200); + } + Assert.assertEquals(false, client.isConnected()); + client.close(2000); + server.close(2000); + } } /** @@ -156,24 +156,24 @@ public void testReconnectWaringLog() throws RemotingException, InterruptedExcept } Assert.assertTrue("warning message count must >= 1, real :"+count, count>= 1); DubboAppender.doStop(); - } - - public Client startClient(int port , int reconnectPeriod) throws RemotingException{ - final String url = "exchange://127.0.0.1:"+port + "/client.reconnect.test?check=false&"+Constants.RECONNECT_KEY+"="+reconnectPeriod; - return Exchangers.connect(url); - } - - public Server startServer(int port) throws RemotingException{ - final String url = "exchange://127.0.0.1:"+port +"/client.reconnect.test"; - return Exchangers.bind(url, new HandlerAdapter()); - } - - static class HandlerAdapter extends ExchangeHandlerAdapter{ - public void connected(Channel channel) throws RemotingException { - } - public void disconnected(Channel channel) throws RemotingException { - } - public void caught(Channel channel, Throwable exception) throws RemotingException { - } + } + + public Client startClient(int port , int reconnectPeriod) throws RemotingException{ + final String url = "exchange://127.0.0.1:"+port + "/client.reconnect.test?check=false&"+Constants.RECONNECT_KEY+"="+reconnectPeriod; + return Exchangers.connect(url); + } + + public Server startServer(int port) throws RemotingException{ + final String url = "exchange://127.0.0.1:"+port +"/client.reconnect.test"; + return Exchangers.bind(url, new HandlerAdapter()); + } + + static class HandlerAdapter extends ExchangeHandlerAdapter{ + public void connected(Channel channel) throws RemotingException { + } + public void disconnected(Channel channel) throws RemotingException { + } + public void caught(Channel channel, Throwable exception) throws RemotingException { + } } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java index 09e66523acd..e3306bdf83f 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; import junit.framework.Assert; @@ -20,7 +20,7 @@ import org.junit.Test; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientsTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientsTest.java index 10aa3d7e9d4..e0696c1ea3a 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientsTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientsTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.Transporter; /** * @author ding.lid diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientTest.java index c1da6d12fcc..81fcf74dfb9 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientTest.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; import java.util.ArrayList; @@ -23,8 +23,8 @@ import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.Exchangers; @@ -70,10 +70,10 @@ public static void tearDown() throws Exception { if (server != null) server.close(); } finally {} - } - - public static void main(String[] args) throws RemotingException, InterruptedException { - ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty&heartbeat=1000")); - Thread.sleep(60*1000*50); + } + + public static void main(String[] args) throws RemotingException, InterruptedException { + ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty&heartbeat=1000")); + Thread.sleep(60*1000*50); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientToServerTest.java index ea428718be7..e29b0625aa8 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/NettyClientToServerTest.java @@ -1,22 +1,22 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetClientHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetClientHandler.java index 9f1aae580fb..8f874627e6d 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetClientHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetClientHandler.java @@ -1,21 +1,21 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.support.Replier; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetServerHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetServerHandler.java index ac5701b2403..92af6a0c048 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/TelnetServerHandler.java @@ -1,21 +1,21 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.support.Replier; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java index 377fbb45015..907e04786ec 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java @@ -21,9 +21,9 @@ import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * @author kimi diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/WorldHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/WorldHandler.java index 4e257bc4dfb..2e3b982ab93 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/WorldHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/WorldHandler.java @@ -1,21 +1,21 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.support.Replier; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Group.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Group.java index 60d003168e0..2a40348a779 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Group.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Group.java @@ -16,8 +16,8 @@ package com.alibaba.dubbo.remoting.p2p; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Group. (SPI, Prototype, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networker.java index 52983482e1b..cdc1192a10b 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networker.java @@ -17,7 +17,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.SPI; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Networker. (SPI, Singleton, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networkers.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networkers.java index 3df97f7b23d..3fa386d0df6 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networkers.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Networkers.java @@ -17,8 +17,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Networkers. (API, Static, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Peer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Peer.java index 5f511746a16..cf00655a56d 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Peer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/Peer.java @@ -15,8 +15,8 @@ */ package com.alibaba.dubbo.remoting.p2p; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; /** * Peer. (SPI, Prototype, ThreadSafe) diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeGroup.java index a72587c5b7b..54f478e64f8 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeGroup.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.exchange; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.p2p.Group; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworker.java index 84371195850..3a7de786faa 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworker.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.exchange; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; /** * Networker diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java index fcb0f3af4bd..8867dc36376 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java @@ -17,7 +17,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; /** diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java index d79ecd01e3c..b3f83432973 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java @@ -22,10 +22,10 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java index 5d59d992704..0c342aa4fb4 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java @@ -24,9 +24,9 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java index 83755345c0d..b2cfa88637f 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java @@ -29,7 +29,7 @@ import com.alibaba.dubbo.common.utils.IOUtils; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangePeer; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java index 85d7a1b0fb5..f0b79008379 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.exchange.support; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeGroup; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeNetworker; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java index 3850261dbb1..e79941a4e38 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java @@ -23,7 +23,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangePeer; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java index f2345cdb773..79508a7d20f 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.exchange.support; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeGroup; import com.alibaba.dubbo.remoting.p2p.exchange.ExchangeNetworker; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/AbstractGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/AbstractGroup.java index 2fff7bac359..ca9f9da448c 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/AbstractGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/AbstractGroup.java @@ -22,10 +22,10 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.Transporters; import com.alibaba.dubbo.remoting.p2p.Group; import com.alibaba.dubbo.remoting.p2p.Peer; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileGroup.java index 1ad645b79b1..6ad85a4adcc 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileGroup.java @@ -29,8 +29,8 @@ import com.alibaba.dubbo.common.utils.IOUtils; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.Peer; /** diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileNetworker.java index 1aa4f8887dc..12e51f41f11 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileNetworker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/FileNetworker.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.support; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.Group; import com.alibaba.dubbo.remoting.p2p.Networker; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java index beca3ba9c96..82e24cc5c3f 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java @@ -23,8 +23,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.Peer; /** diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastNetworker.java index 4699f77ecce..218128787b9 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastNetworker.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastNetworker.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.remoting.p2p.support; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.p2p.Group; import com.alibaba.dubbo.remoting.p2p.Networker; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/ServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/ServerPeer.java index a1ff4da47e2..ba1a49a28dd 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/ServerPeer.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/ServerPeer.java @@ -24,10 +24,10 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Client; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Server; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.Client; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.p2p.Group; import com.alibaba.dubbo.remoting.p2p.Peer; import com.alibaba.dubbo.remoting.transport.ServerDelegate; diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/com/alibaba/dubbo/remoting/p2p/PeerMain.java b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/com/alibaba/dubbo/remoting/p2p/PeerMain.java index de8d10995ab..0c9a91ccd78 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/com/alibaba/dubbo/remoting/p2p/PeerMain.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/com/alibaba/dubbo/remoting/p2p/PeerMain.java @@ -17,8 +17,8 @@ import java.util.Collection; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; /** diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 0c7faf42bbc..42969026f11 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -35,5 +35,6 @@ dubbo-remoting-p2p dubbo-remoting-http dubbo-remoting-zookeeper - + dubbo-remoting-common + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcConstants.java deleted file mode 100644 index c1275d5e731..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc; - -import com.alibaba.dubbo.common.Constants; - -/** - * RpcConstants - * - * @deprecated Replace to com.alibaba.dubbo.common.Constants - * @author william.liangf - */ -@Deprecated -public final class RpcConstants extends Constants { - - private RpcConstants() {} - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-common/pom.xml b/dubbo-rpc/dubbo-rpc-common/pom.xml new file mode 100644 index 00000000000..4b620cf64ea --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-common/pom.xml @@ -0,0 +1,15 @@ + + + + dubbo-rpc + com.alibaba + 2.8.4 + + 4.0.0 + + dubbo-rpc-common + + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index cb5c5a51566..416f786e299 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -1,40 +1,40 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.bytecode.Wrapper; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.ConcurrentHashSet; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.ProxyFactory; -import com.alibaba.dubbo.rpc.RpcInvocation; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.bytecode.Wrapper; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ConcurrentHashSet; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.rpc.Exporter; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.ProxyFactory; +import com.alibaba.dubbo.rpc.RpcInvocation; /** * callback 服务帮助类. @@ -49,7 +49,7 @@ class CallbackServiceCodec { private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; private static final byte CALLBACK_DESTROY = 0x2; - private static final String INV_ATT_CALLBACK_KEY = "sys_callback_arg-"; + private static final String INV_ATT_CALLBACK_KEY = "sys_callback_arg-"; private static byte isCallBack(URL url, String methodName ,int argIndex){ //参数callback的规则是 方法名称.参数index(0开始).callback @@ -68,11 +68,11 @@ private static byte isCallBack(URL url, String methodName ,int argIndex){ } /** - * client 端export callback service - * @param channel - * @param clazz - * @param inst - * @param export + * client 端export callback service + * @param channel + * @param clazz + * @param inst + * @param export * @param out * @throws IOException */ @@ -94,7 +94,7 @@ private static String exportOrunexportCallbackService(Channel channel, URL url, Map tmpmap = new HashMap(url.getParameters()); tmpmap.putAll(params); - tmpmap.remove(Constants.VERSION_KEY);//callback不需要区分version + tmpmap.remove(Constants.VERSION_KEY);//callback不需要区分version tmpmap.put(Constants.INTERFACE_KEY, clazz.getName()); URL exporturl = new URL(DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), channel.getLocalAddress().getPort(), clazz.getName()+"."+instid, tmpmap); @@ -126,7 +126,7 @@ private static String exportOrunexportCallbackService(Channel channel, URL url, } /** - * server端 应用一个callbackservice + * server端 应用一个callbackservice * @param url */ @SuppressWarnings("unchecked") @@ -138,10 +138,10 @@ private static Object referOrdestroyCallbackService(Channel channel, URL url, Cl String countkey = getServerSideCountKey(channel, clazz.getName()); if (isRefer){ if( proxy == null ){ - URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + Constants.INTERFACE_KEY + "=" + clazz.getName()); - referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(Constants.METHODS_KEY); - if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)){ - @SuppressWarnings("rawtypes") + URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + Constants.INTERFACE_KEY + "=" + clazz.getName()); + referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(Constants.METHODS_KEY); + if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)){ + @SuppressWarnings("rawtypes") Invoker invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); proxy = proxyFactory.getProxy(invoker); channel.setAttribute(proxyCacheKey, proxy); @@ -235,8 +235,8 @@ private static void decreaseInstanceCount(Channel channel, String countkey){ } } - public static Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int paraIndex) throws IOException{ - //encode时可直接获取url + public static Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int paraIndex) throws IOException{ + //encode时可直接获取url URL url = inv.getInvoker() == null ? null : inv.getInvoker().getUrl(); byte callbackstatus = isCallBack(url, inv.getMethodName(), paraIndex); Object[] args = inv.getArguments(); @@ -255,16 +255,16 @@ public static Object encodeInvocationArgument(Channel channel, RpcInvocation inv } } public static Object decodeInvocationArgument(Channel channel, RpcInvocation inv, Class[] pts, int paraIndex, Object inObject) throws IOException{ - //如果是callback,则创建proxy到客户端,方法的执行可通过channel调用到client端的callback接口 - //decode时需要根据channel及env获取url - URL url = null ; - try { - url = DubboProtocol.getDubboProtocol().getInvoker(channel, inv).getUrl(); - } catch (RemotingException e) { - if (logger.isInfoEnabled()) { - logger.info(e.getMessage(), e); - } - return inObject; + //如果是callback,则创建proxy到客户端,方法的执行可通过channel调用到client端的callback接口 + //decode时需要根据channel及env获取url + URL url = null ; + try { + url = DubboProtocol.getDubboProtocol().getInvoker(channel, inv).getUrl(); + } catch (RemotingException e) { + if (logger.isInfoEnabled()) { + logger.info(e.getMessage(), e); + } + return inObject; } byte callbackstatus = isCallBack(url, inv.getMethodName(), paraIndex); switch (callbackstatus) { @@ -286,5 +286,5 @@ public static Object decodeInvocationArgument(Channel channel, RpcInvocation inv default: return inObject ; } - } + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 0d4ded816b0..edc5043b07a 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -17,12 +17,15 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; +import com.alibaba.dubbo.common.Version; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeClient; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.ClientDelegate; import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; @@ -40,7 +43,6 @@ class ChannelWrappedInvoker extends AbstractInvoker { private final String serviceKey; public ChannelWrappedInvoker(Class serviceType, Channel channel, URL url, String serviceKey) { - super(serviceType, url, new String[]{Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); this.channel = channel; @@ -53,9 +55,7 @@ protected Result doInvoke(Invocation invocation) throws Throwable { //拿不到client端export 的service path.约定为interface的名称. inv.setAttachment(Constants.PATH_KEY, getInterface().getName()); inv.setAttachment(Constants.CALLBACK_SERVICE_KEY, serviceKey); - ExchangeClient currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel)); - try { if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { // 不可靠异步 currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), Constants.SENT_KEY, false)); @@ -63,11 +63,14 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } int timeout = getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + Request request = new Request.Builder().newId().version(Version.getVersion()).data(inv).build(); + Response response; if (timeout > 0) { - return (Result) currentClient.request(inv, timeout).get(); + response = currentClient.execute(request, timeout); } else { - return (Result) currentClient.request(inv).get(); + response = currentClient.execute(request); } + return (Result) response.getResult(); } catch (RpcException e) { throw e; } catch (TimeoutException e) { @@ -148,17 +151,5 @@ public void send(Object message) throws RemotingException { public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } - } - - public void destroy() { - //channel资源的清空由channel创建者清除. -// super.destroy(); -// try { -// channel.close(); -// } catch (Throwable t) { -// logger.warn(t.getMessage(), t); -// } - } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index fb1aca464aa..d6ccb8ad857 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -24,10 +24,10 @@ import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Decodeable; -import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.transport.CodecSupport; import com.alibaba.dubbo.rpc.RpcInvocation; @@ -98,7 +98,6 @@ public Object decode(Channel channel, InputStream input) throws IOException { try { Object[] args; Class[] pts; - // NOTICE modified by lishen int argNum = in.readInt(); if (argNum >= 0) { @@ -167,4 +166,8 @@ public Object decode(Channel channel, InputStream input) throws IOException { return this; } + public Channel getChannel(){ + return channel; + } + } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index 5ce30db7a63..64bdc370b55 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -22,19 +22,16 @@ import com.alibaba.dubbo.common.serialize.ObjectInput; import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Decodeable; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.CodecSupport; -import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.lang.reflect.Type; /** * @author kimi @@ -51,18 +48,15 @@ public class DecodeableRpcResult extends RpcResult implements Codec, Decodeable private Response response; - private Invocation invocation; - private volatile boolean hasDecoded; - public DecodeableRpcResult(Channel channel, Response response, InputStream is, Invocation invocation, byte id) { + public DecodeableRpcResult(Channel channel, Response response, InputStream is, byte id) { Assert.notNull(channel, "channel == null"); Assert.notNull(response, "response == null"); Assert.notNull(is, "inputStream == null"); this.channel = channel; this.response = response; this.inputStream = is; - this.invocation = invocation; this.serializationType = id; } @@ -81,10 +75,7 @@ public Object decode(Channel channel, InputStream input) throws IOException { break; case DubboCodec.RESPONSE_VALUE: try { - Type[] returnType = RpcUtils.getReturnTypes(invocation); - setValue(returnType == null || returnType.length == 0 ? in.readObject() : - (returnType.length == 1 ? in.readObject((Class) returnType[0]) - : in.readObject((Class) returnType[0], returnType[1]))); + setValue(in.readObject()); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read response data failed.", e)); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index 066736b334e..78a15fd0403 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -28,13 +28,12 @@ import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.CodecSupport; -import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcInvocation; @@ -94,13 +93,11 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro if (channel.getUrl().getParameter( Constants.DECODE_IN_IO_THREAD_KEY, Constants.DEFAULT_DECODE_IN_IO_THREAD)) { - result = new DecodeableRpcResult(channel, res, is, - (Invocation) getRequestData(id), proto); + result = new DecodeableRpcResult(channel, res, is, proto); result.decode(); } else { result = new DecodeableRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - (Invocation) getRequestData(id), proto); + new UnsafeByteArrayInputStream(readMessageData(is)), proto); } data = result; } @@ -171,15 +168,10 @@ private byte[] readMessageData(InputStream is) throws IOException { @Override protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { RpcInvocation inv = (RpcInvocation) data; - out.writeUTF(inv.getAttachment(Constants.DUBBO_VERSION_KEY, DUBBO_VERSION)); out.writeUTF(inv.getAttachment(Constants.PATH_KEY)); out.writeUTF(inv.getAttachment(Constants.VERSION_KEY)); - out.writeUTF(inv.getMethodName()); - - // NOTICE modified by lishen - // TODO if (getSerialization(channel) instanceof OptimizedSerialization && !containComplexArguments(inv)) { out.writeInt(inv.getParameterTypes().length); } else { @@ -198,7 +190,6 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) @Override protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { Result result = (Result) data; - Throwable th = result.getException(); if (th == null) { Object ret = result.getValue(); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 9c6b02cf236..c906083eb49 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -19,12 +19,12 @@ import java.io.IOException; import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index d98ef286b87..352fd7a3dc0 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -17,14 +17,13 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; import com.alibaba.dubbo.rpc.support.RpcUtils; @@ -90,7 +89,7 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { return new RpcResult(); } else { RpcContext.getContext().setFuture(null); - Request request = new Request.Builder().newId().version(Version.getVersion()).data(inv).build(); + Request request = new Request.Builder().newId().data(inv).build(); Response response = currentClient.execute(request, timeout); return (Result) response.getResult(); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index cf7c8139b02..d637d5ac9f0 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -24,9 +24,9 @@ import com.alibaba.dubbo.common.utils.ConcurrentHashSet; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Transporter; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.remoting.exchange.*; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import com.alibaba.dubbo.rpc.*; @@ -36,7 +36,6 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.locks.ReentrantLock; /** * dubbo protocol support. @@ -53,8 +52,6 @@ public class DubboProtocol extends AbstractProtocol { public static final int DEFAULT_PORT = 20880; - public final ReentrantLock lock = new ReentrantLock(); - private final Map serverMap = new ConcurrentHashMap(); // private final Map referenceClientMap = new ConcurrentHashMap(); // @@ -63,12 +60,21 @@ public class DubboProtocol extends AbstractProtocol { private final Set optimizers = new ConcurrentHashSet(); - //consumer side export a stub service for dispatching event - //servicekey-stubmethods - private final ConcurrentMap stubServiceMethodsMap = new ConcurrentHashMap(); - private static final String IS_CALLBACK_SERVICE_INVOKE = "_isCallBackServiceInvoke"; + private static DubboProtocol INSTANCE; + + public DubboProtocol() { + INSTANCE = this; + } + + public static DubboProtocol getDubboProtocol() { + if (INSTANCE == null) { + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME); + } + return INSTANCE; + } + private ExchangeHandler requestHandler = new ExchangeHandlerAdapter() { public Object reply(ExchangeChannel channel, Object message) throws RemotingException { @@ -151,19 +157,6 @@ private Invocation createInvocation(Channel channel, URL url, String methodKey) } }; - private static DubboProtocol INSTANCE; - - public DubboProtocol() { - INSTANCE = this; - } - - public static DubboProtocol getDubboProtocol() { - if (INSTANCE == null) { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME); // load - } - return INSTANCE; - } - public Collection getServers() { return Collections.unmodifiableCollection(serverMap.values()); } @@ -172,10 +165,6 @@ public Collection> getExporters() { return Collections.unmodifiableCollection(exporterMap.values()); } - Map> getExporterMap() { - return exporterMap; - } - private boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); @@ -224,7 +213,7 @@ public Exporter export(Invoker invoker) throws RpcException { String key = serviceKey(url); DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); exporterMap.put(key, exporter); - //export an stub service for dispaching event + //export an stub service for dispatching event Boolean isStubSupportEvent = url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT); Boolean isCallbackService = url.getParameter(Constants.IS_CALLBACK_SERVICE, false); if (isStubSupportEvent && !isCallbackService) { @@ -234,8 +223,6 @@ public Exporter export(Invoker invoker) throws RpcException { logger.warn(new IllegalStateException("consumer [" + url.getParameter(Constants.INTERFACE_KEY) + "], has set stubproxy support event ,but no stub methods founded.")); } - } else { - stubServiceMethodsMap.put(url.getServiceKey(), stubServiceMethods); } } openServer(url); @@ -267,7 +254,6 @@ private void optimizeSerialization(URL url) throws RpcException { for (Class c : optimizer.getSerializableClasses()) { SerializableClassRegistry.registerClass(c); } - optimizers.add(className); } catch (ClassNotFoundException e) { throw new RpcException("Cannot find the serialization optimizer class: " + className, e); @@ -322,10 +308,8 @@ private ExchangeServer createServer(URL url) { } public Invoker refer(Class serviceType, URL url) throws RpcException { - // modified by lishen optimizeSerialization(url); - // create rpc invoker. DubboInvoker invoker = new DubboInvoker(serviceType, url, getClients(url), invokers); invokers.add(invoker); @@ -367,9 +351,8 @@ private ExchangeClient getSharedClient(URL url) { referenceClientMap.remove(key); } } - ExchangeClient exchagneclient = initClient(url); - - client = new ReferenceCountExchangeClient(exchagneclient, ghostClientMap); + ExchangeClient exchangeClient = initClient(url); + client = new ReferenceCountExchangeClient(exchangeClient, ghostClientMap); referenceClientMap.put(key, client); ghostClientMap.remove(key); return client; @@ -379,7 +362,6 @@ private ExchangeClient getSharedClient(URL 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)); @@ -452,7 +434,6 @@ public void destroy() { } } } - stubServiceMethodsMap.clear(); super.destroy(); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java index c213116a9ff..9e24103e3e7 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java @@ -21,7 +21,7 @@ import java.util.concurrent.TimeoutException; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; @@ -71,7 +71,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution int timeoutInMillis = (int) unit.convert(timeout, TimeUnit.MILLISECONDS); try { return (V) (((Result) future.get(timeoutInMillis)).recreate()); - } catch (com.alibaba.dubbo.remoting.TimeoutException e) { + } catch (com.alibaba.dubbo.remoting.exception.TimeoutException e) { throw new TimeoutException(StringUtils.toString(e)); } catch (RemotingException e) { throw new ExecutionException(e.getMessage(), e); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 65ee7fba14e..1160d84589d 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -21,9 +21,12 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicLong; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index d3de82b9057..64ad9b0f6be 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -18,9 +18,12 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.Parameters; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentMap; @@ -38,13 +41,13 @@ final class ReferenceCountExchangeClient implements ExchangeClient { private final URL url; - private final AtomicInteger refenceCount = new AtomicInteger(0); + private final AtomicInteger referenceCount = new AtomicInteger(0); private final ConcurrentMap ghostClientMap; public ReferenceCountExchangeClient(ExchangeClient client, ConcurrentMap ghostClientMap) { this.client = client; - refenceCount.incrementAndGet(); + referenceCount.incrementAndGet(); this.url = client.getUrl(); if (ghostClientMap == null) { throw new IllegalStateException("ghostClientMap can not be null, url: " + url); @@ -138,7 +141,7 @@ public void close() { } public void close(int timeout) { - if (refenceCount.decrementAndGet() <= 0) { + if (referenceCount.decrementAndGet() <= 0) { if (timeout == 0) { client.close(); } else { @@ -173,7 +176,7 @@ public boolean isClosed() { } public void incrementAndGetCount() { - refenceCount.incrementAndGet(); + referenceCount.incrementAndGet(); } @Override diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index 26309233ec3..8bcd6d26a90 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -27,7 +27,7 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.ConcurrentHashSet; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandler.java index 1f998bfab3f..b3162a39e71 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandler.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.rpc.protocol.dubbo.telnet; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.rpc.Exporter; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CountTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CountTelnetHandler.java index b58be301212..d8071f10066 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CountTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CountTelnetHandler.java @@ -22,8 +22,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.remoting.telnet.support.TelnetUtils; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandler.java index 529c05b1e04..dae36192f59 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandler.java @@ -16,7 +16,7 @@ package com.alibaba.dubbo.rpc.protocol.dubbo.telnet; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java index 4bd16895815..c902c03f5a0 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java @@ -25,7 +25,7 @@ import com.alibaba.dubbo.common.utils.PojoUtils; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.rpc.Exporter; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java index 2f60210f8cb..eba5641d9e2 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.ReflectUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.rpc.Exporter; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java index e2c37df37be..85442b87493 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandler.java @@ -1,41 +1,41 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol.dubbo.telnet; -import java.io.File; -import java.io.FileInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.common.logger.Level; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.telnet.TelnetHandler; -import com.alibaba.dubbo.remoting.telnet.support.Help; +import java.io.File; +import java.io.FileInputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.common.logger.Level; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.telnet.TelnetHandler; +import com.alibaba.dubbo.remoting.telnet.support.Help; /** * LogTelnetHandler * @author chao.liuc * - */ + */ @Activate @Help(parameter = "level", summary = "Change log level or show log ", detail = "Change log level or show log") public class LogTelnetHandler implements TelnetHandler { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandler.java index 62add429e3e..d7282da369f 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandler.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/TraceTelnetHandler.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/TraceTelnetHandler.java index 615438d3b86..aa0312c35b4 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/TraceTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/TraceTelnetHandler.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.remoting.telnet.support.Help; import com.alibaba.dubbo.rpc.Exporter; diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandlerTest.java index 1e0a0abc871..7ac896f070f 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ChangeTelnetHandlerTest.java @@ -24,8 +24,8 @@ import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol; diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java index 531db0086da..97c053d3fa2 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/CurrentTelnetHandlerTest.java @@ -21,8 +21,8 @@ import org.junit.After; import org.junit.Test; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; /** diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokerTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokerTelnetHandlerTest.java index e26d1ae9166..834e59d3fc2 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokerTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/InvokerTelnetHandlerTest.java @@ -24,8 +24,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandlerTest.java index 0904894a78a..1f76595e5a7 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandlerTest.java @@ -27,8 +27,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.ReflectUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandlerTest.java index 5822c728dfe..4b7b7df1526 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/LogTelnetHandlerTest.java @@ -20,8 +20,8 @@ import org.easymock.EasyMock; import org.junit.Test; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; /** diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandlerTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandlerTest.java index c9eeaf81d60..9cc52735982 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/telnet/PortTelnetHandlerTest.java @@ -19,15 +19,12 @@ import static org.junit.Assert.assertTrue; import org.easymock.EasyMock; -import org.easymock.IAnswer; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java index 5f7d902f489..b1c2d376503 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -17,12 +17,12 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.ClassHelper; -import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java index 6f108d78744..3a4b0a21de8 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java @@ -16,9 +16,11 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; @@ -53,35 +55,25 @@ public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Setdubbo-rpc-memcached dubbo-rpc-redis dubbo-rpc-rest + dubbo-rpc-common diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java index 6ac6d95b3f2..066e938d6be 100644 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java +++ b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java @@ -2,79 +2,73 @@ /** * nfs-rpc - * Apache License - * - * http://code.google.com/p/nfs-rpc (c) 2011 + * Apache License + *

+ * http://code.google.com/p/nfs-rpc (c) 2011 */ + +import com.alibaba.dubbo.common.utils.ConfigUtils; + import java.io.BufferedWriter; -import java.io.FileInputStream; import java.io.FileWriter; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; +import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; -import com.alibaba.dubbo.common.utils.ConfigUtils; - /** * Abstract benchmark client,test for difference scenes Usage: -Dwrite.statistics=false BenchmarkClient serverIP * serverPort concurrents timeout codectype requestSize runtime(seconds) clientNums - * + * * @author bluedavy */ public abstract class AbstractBenchmarkClient { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - private static long maxTPS = 0; + private static long maxTPS = 0; - private static long minTPS = 0; + private static long minTPS = 0; - private static long allRequestSum; + private static long allRequestSum; - private static long allResponseTimeSum; + private static long allResponseTimeSum; - private static long allErrorRequestSum; + private static long allErrorRequestSum; - private static long allErrorResponseTimeSum; + private static long allErrorResponseTimeSum; - private static int runtime; + private static int runtime; // < 0 - private static long below0sum; + private static long below0sum; // (0,1] - private static long above0sum; + private static long above0sum; // (1,5] - private static long above1sum; + private static long above1sum; // (5,10] - private static long above5sum; + private static long above5sum; // (10,50] - private static long above10sum; + private static long above10sum; // (50,100] - private static long above50sum; + private static long above50sum; // (100,500] - private static long above100sum; + private static long above100sum; // (500,1000] - private static long above500sum; + private static long above500sum; // > 1000 - private static long above1000sum; + private static long above1000sum; - Properties properties = ConfigUtils.getProperties(); + Properties properties = ConfigUtils.getProperties(); public void run(String[] args) throws Exception { @@ -107,7 +101,7 @@ public void run(String[] args) throws Exception { long beginTime = System.nanoTime() / 1000L + 30 * 1000 * 1000L; for (int i = 0; i < concurrents; i++) { ClientRunnable runnable = getClientRunnable(serverIP, serverPort, clientNums, timeout, barrier, latch, - beginTime, endtime); + beginTime, endtime); runnables.add(runnable); } @@ -212,13 +206,13 @@ public void run(String[] args) throws Exception { long benchmarkRequest = allRequestSum + allErrorRequestSum; long allRequest = benchmarkRequest + ignoreRequest + ignoreErrorRequest; System.out.println(" Requests: " + allRequest + " Success: " + (allRequestSum + ignoreRequest) * 100 - / allRequest + "% (" + (allRequestSum + ignoreRequest) + ") Error: " - + (allErrorRequestSum + ignoreErrorRequest) * 100 / allRequest + "% (" - + (allErrorRequestSum + ignoreErrorRequest) + ")"); + / allRequest + "% (" + (allRequestSum + ignoreRequest) + ") Error: " + + (allErrorRequestSum + ignoreErrorRequest) * 100 / allRequest + "% (" + + (allErrorRequestSum + ignoreErrorRequest) + ")"); System.out.println(" Avg TPS: " + benchmarkRequest / times.keySet().size() + " Max TPS: " + maxTPS - + " Min TPS: " + minTPS); + + " Min TPS: " + minTPS); System.out.println(" Avg RT: " + (allErrorResponseTimeSum + allResponseTimeSum) / benchmarkRequest / 1000f - + "ms"); + + "ms"); System.out.println(" RT <= 0: " + (below0sum * 100 / allRequest) + "% " + below0sum + "/" + allRequest); System.out.println(" RT (0,1]: " + (above0sum * 100 / allRequest) + "% " + above0sum + "/" + allRequest); System.out.println(" RT (1,5]: " + (above1sum * 100 / allRequest) + "% " + above1sum + "/" + allRequest); @@ -227,7 +221,7 @@ public void run(String[] args) throws Exception { System.out.println(" RT (50,100]: " + (above50sum * 100 / allRequest) + "% " + above50sum + "/" + allRequest); System.out.println(" RT (100,500]: " + (above100sum * 100 / allRequest) + "% " + above100sum + "/" + allRequest); System.out.println(" RT (500,1000]: " + (above500sum * 100 / allRequest) + "% " + above500sum + "/" - + allRequest); + + allRequest); System.out.println(" RT > 1000: " + (above1000sum * 100 / allRequest) + "% " + above1000sum + "/" + allRequest); System.exit(0); } diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java index 3fade03740b..cf53c9f16bb 100644 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java +++ b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java @@ -6,7 +6,7 @@ import java.text.SimpleDateFormat; import java.util.Date; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java index f663a6af097..8cfd1ded5fa 100644 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java +++ b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java @@ -3,67 +3,68 @@ /** * nfs-rpc Apache License http://code.google.com/p/nfs-rpc (c) 2011 */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * Simple Processor RPC Benchmark Client Thread - * + * * @author bluedavy */ public class SimpleProcessorBenchmarkClientRunnable implements ClientRunnable { - private static final Log LOGGER = LogFactory.getLog(SimpleProcessorBenchmarkClientRunnable.class); + private static final Log LOGGER = LogFactory.getLog(SimpleProcessorBenchmarkClientRunnable.class); - private int requestSize; + private int requestSize; - private CyclicBarrier barrier; + private CyclicBarrier barrier; - private CountDownLatch latch; + private CountDownLatch latch; - private long endTime; + private long endTime; - private boolean running = true; + private boolean running = true; - private ExchangeClientFactory clientFactory = new ExchangeClientFactory(); + private ExchangeClientFactory clientFactory = new ExchangeClientFactory(); - private String targetIP; + private String targetIP; - private int targetPort; + private int targetPort; - private int clientNums; + private int clientNums; - private int rpcTimeout; + private int rpcTimeout; // response time spread - private long[] responseSpreads = new long[9]; + private long[] responseSpreads = new long[9]; // error request per second - private long[] errorTPS = null; + private long[] errorTPS = null; // error response times per second - private long[] errorResponseTimes = null; + private long[] errorResponseTimes = null; // tps per second - private long[] tps = null; + private long[] tps = null; // response times per second - private long[] responseTimes = null; + private long[] responseTimes = null; // benchmark startTime - private long startTime; + private long startTime; // benchmark maxRange - private int maxRange; + private int maxRange; public SimpleProcessorBenchmarkClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout, CyclicBarrier barrier, CountDownLatch latch, long startTime, - long endTime){ + long endTime) { this.targetIP = targetIP; this.targetPort = targetPort; @@ -117,7 +118,7 @@ private void runJavaAndHessian() { int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000; if (range >= maxRange) { System.err.println("benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " - + maxRange); + + maxRange); continue; } if (((ResponseObject) response).getBytes() != null) { @@ -139,7 +140,7 @@ private void runJavaAndHessian() { int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000; if (range >= maxRange) { System.err.println("benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " - + maxRange); + + maxRange); continue; } errorTPS[range] = errorTPS[range] + 1; diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java index 4f59404ac40..7bf96b99485 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java @@ -16,8 +16,8 @@ package com.alibaba.dubbo.examples.heartbeat; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index 801f44db09e..90694f84d2f 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -18,17 +18,18 @@ dubbo-common ${project.parent.version} + com.alibaba - dubbo-rpc-api - ${project.version} + dubbo-remoting-common + 2.8.4 + com.alibaba - dubbo-remoting-api - ${project.version} + dubbo-rpc-api + 2.8.4 - javax.servlet javax.servlet-api diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java index aafe335d6dc..826e567d3fb 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -1,6 +1,9 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.remoting.exchange.Request; + +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; public class DubboRequest { @@ -31,12 +34,20 @@ public void addAttachment(String key, String value) { invocation.setAttachment(key, value); } - public String getAttachment(String key){ + public String getAttachment(String key) { return invocation.getAttachment(key); } - public String providerAddress() { - return invocation.getInvoker().getUrl().getAddress(); + public String address() { + Invoker invoker = invocation.getInvoker(); + if (invoker != null) { + return invoker.getUrl().getAddress(); + } +// if (invocation instanceof DecodeableRpcInvocation){ +// Channel channel = ((DecodeableRpcInvocation) invocation).getChannel(); +// return channel.getUrl().getAddress(); +// } + return NetUtils.getLocalHost(); } public Request getRequest() { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java index 1a8b4056b56..15d3eed7059 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java @@ -1,13 +1,19 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.rpc.RpcContext; - /** * @author Xs */ -public class DubboRequestSpanNameProvider { +public class DubboRequestSpanNameProvider extends RpcContextMethodNameProvider { + + public String spanName(DubboRequest dubboRequest) { + String spanName = getMethodNameFromContext(); + if (spanName == null) { + spanName = getSpanNameFromAttachment(dubboRequest); + } + return spanName; + } - public String spanName() { - return RpcContext.getContext().getMethodName(); + private String getSpanNameFromAttachment(DubboRequest dubboRequest) { + return dubboRequest.getAttachment(RpcAttachment.SpanName.getName()); } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index 3035cb0f359..06a0f3a4c52 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcResult; public class DubboResponse { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java index 36e3bbc46ca..c58518e0ec9 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcAttachment.java @@ -13,7 +13,7 @@ public enum RpcAttachment { Sampled("X-B3-Sampled"), - Method("X-B3-Method"); + SpanName("X-B3-SpanName"); private final String name; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml index e6efb0cd1be..84b4ec12d0b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml +++ b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml @@ -18,18 +18,6 @@ ${project.version} - - com.alibaba - dubbo-remoting-api - ${project.version} - - - - com.alibaba - dubbo-rpc-default - ${project.version} - - io.zipkin.brave brave-core diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java index d16ef5e5d53..602690902da 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java @@ -30,7 +30,7 @@ public boolean isTraceable() { @Override public String getSpanName() { - return spanNameProvider.spanName(); + return spanNameProvider.spanName(request); } @Override @@ -44,12 +44,13 @@ public void addSpanIdToRequest(SpanId spanId) { if (spanId.nullableParentId() != null) { request.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); } + request.addAttachment(RpcAttachment.SpanName.getName(), getSpanName()); } } @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.providerAddress()); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.address()); return Collections.singletonList(annotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java index ecc647be7d1..016e5e9d1ef 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java @@ -1,9 +1,10 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Interceptor; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; + +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.tracker.DubboRequest; import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.DubboResponse; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java index 51f02e261a4..1451344d9b8 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java @@ -9,13 +9,13 @@ */ public class DubboRpcTracker implements RpcTracker { - private final ClientRequestInterceptor clientRequestInterceptor; + private final DubboClientRequestInterceptor clientRequestInterceptor; - private final ClientResponseInterceptor clientResponseInterceptor; + private final DubboClientResponseInterceptor clientResponseInterceptor; - private final ServerRequestInterceptor serverRequestInterceptor; + private final DubboServerRequestInterceptor serverRequestInterceptor; - private final ServerResponseInterceptor serverResponseInterceptor; + private final DubboServerResponseInterceptor serverResponseInterceptor; private final BraveRpcTrackerEngine trackerEngine; @@ -32,22 +32,22 @@ public DubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { } @Override - public ClientRequestInterceptor clientRequestInterceptor() { + public DubboClientRequestInterceptor clientRequestInterceptor() { return clientRequestInterceptor; } @Override - public ClientResponseInterceptor clientResponseInterceptor() { + public DubboClientResponseInterceptor clientResponseInterceptor() { return clientResponseInterceptor; } @Override - public ServerRequestInterceptor serverRequestInterceptor() { + public DubboServerRequestInterceptor serverRequestInterceptor() { return serverRequestInterceptor; } @Override - public ServerResponseInterceptor serverResponseInterceptor() { + public DubboServerResponseInterceptor serverResponseInterceptor() { return serverResponseInterceptor; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java index 672969c7971..938ef5986f6 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java @@ -54,12 +54,12 @@ public TraceData getTraceData() { @Override public String getSpanName() { - return spanNameProvider.spanName(); + return spanNameProvider.spanName(request); } @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.providerAddress()); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.address()); return Collections.singletonList(annotation); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java index e09539d2705..fcdfab32ff5 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java @@ -1,9 +1,9 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.Interceptor; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.tracker.DubboRequest; import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.DubboResponse; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java index 718dc98c791..29db4a689f0 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java @@ -14,7 +14,7 @@ public class AttachMethodNameInterceptor implements Interceptor { public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request.Builder builder = request.newBuilder(); - builder.addHeader(RpcAttachment.Method.getName(), RpcContext.getContext().getMethodName()); + builder.addHeader(RpcAttachment.SpanName.getName(), RpcContext.getContext().getMethodName()); return chain.proceed(builder.build()); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java index e5a555bdb55..62ea4e45663 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java @@ -24,7 +24,7 @@ public String spanName(HttpRequest request) { private String getSpanNameFromHeader(HttpServerRequest httpServerRequest) { - return httpServerRequest.getHttpHeaderValue(RpcAttachment.Method.getName()); + return httpServerRequest.getHttpHeaderValue(RpcAttachment.SpanName.getName()); } } diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 871e071bdab..ed079983e9f 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -415,7 +415,7 @@ com.alibaba:dubbo-container-jetty com.alibaba:dubbo-container-log4j com.alibaba:dubbo-container-logback - + com.alibaba:dubbo-tracker-api com.alibaba:dubbo-tracker-zipkin @@ -457,7 +457,8 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.transport.Transporter + diff --git a/pom.xml b/pom.xml index d926161a443..584a1da368f 100644 --- a/pom.xml +++ b/pom.xml @@ -76,7 +76,6 @@ dubbo-demo hessian-lite dubbo-tracker - From 822e3e8b9d8b4f46648c07d9b61ddf8cd4f71db1 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 5 Feb 2017 22:20:14 +0800 Subject: [PATCH 18/69] modify TrackerConfig and dubbo.xsd --- .../alibaba/dubbo/common/utils/UrlUtils.java | 4 +- .../dubbo/config/AbstractInterfaceConfig.java | 46 ++- .../alibaba/dubbo/config/MethodConfig.java | 10 +- .../alibaba/dubbo/config/ReferenceConfig.java | 312 +++++++++--------- .../alibaba/dubbo/config/ServiceConfig.java | 22 +- .../alibaba/dubbo/config/TrackerConfig.java | 34 +- .../alibaba/dubbo/config/TrackConfigTest.java | 4 +- .../dubbo/config/spring/ReferenceBean.java | 18 + .../dubbo/config/spring/ServiceBean.java | 34 +- .../schema/DubboBeanDefinitionParser.java | 1 + .../src/main/resources/META-INF/dubbo.xsd | 67 ++++ .../META-INF/spring/dubbo-demo-consumer.xml | 2 + .../META-INF/spring/dubbo-demo-provider.xml | 5 +- .../integration/RegistryProtocol.java | 33 +- .../registry/zookeeper/ZookeeperRegistry.java | 94 +++--- .../support/header/HeaderExchanger.java | 38 +-- .../remoting/transport/ChannelHandler.java | 16 +- .../curator/CuratorZookeeperClient.java | 6 +- .../dubbo/tracker/ClientRequestAdapter.java | 7 + .../tracker/ClientRequestInterceptor.java | 2 + .../dubbo/tracker/ClientResponseAdapter.java | 7 + .../tracker/ClientResponseInterceptor.java | 1 + .../alibaba/dubbo/tracker/RpcProtocol.java | 61 ++++ .../com/alibaba/dubbo/tracker/RpcTracker.java | 11 +- .../tracker/RpcTrackerEngineFactory.java | 3 +- .../dubbo/tracker/RpcTrackerFactory.java | 2 +- .../dubbo/tracker/RpcTrackerManager.java | 34 +- .../dubbo/tracker/ServerRequestAdapter.java | 7 + .../tracker/ServerRequestInterceptor.java | 3 + .../dubbo/tracker/ServerResponseAdapter.java | 7 + .../tracker/ServerResponseInterceptor.java | 3 + .../com/alibaba/dubbo/tracker/Traceable.java | 10 + ...va => BraveDubboClientRequestAdapter.java} | 4 +- .../BraveDubboClientRequestInterceptor.java | 13 +- ...DubboClientRequestResponseInterceptor.java | 35 ++ ...a => BraveDubboClientResponseAdapter.java} | 4 +- .../BraveDubboClientResponseInterceptor.java | 15 +- .../tracker/zipkin/BraveDubboRpcTracker.java | 57 ++++ ...va => BraveDubboServerRequestAdapter.java} | 4 +- .../BraveDubboServerRequestInterceptor.java | 14 +- ...DubboServerRequestResponseInterceptor.java | 31 ++ ...a => BraveDubboServerResponseAdapter.java} | 4 +- .../BraveDubboServerResponseInterceptor.java | 14 +- .../tracker/zipkin/BraveRpcTrackerEngine.java | 2 +- .../zipkin/BraveRpcTrackerEngineFactory.java | 12 +- .../zipkin/BraveRpcTrackerFactory.java | 20 +- .../zipkin/DubboClientRequestInterceptor.java | 8 - ...DubboClientRequestResponseInterceptor.java | 34 -- .../DubboClientResponseInterceptor.java | 8 - .../dubbo/tracker/zipkin/DubboRpcTracker.java | 58 ---- .../zipkin/DubboServerRequestInterceptor.java | 12 - ...DubboServerRequestResponseInterceptor.java | 35 -- .../DubboServerResponseInterceptor.java | 11 - .../dubbo/tracker/zipkin/SamplerFactory.java | 2 +- ...cTracker.java => BraveHttpRpcTracker.java} | 6 +- .../zipkin/http/FacadeHttpRpcTracker.java | 16 +- .../tracker/zipkin/test/ExtensionTest.java | 2 +- 57 files changed, 760 insertions(+), 565 deletions(-) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcProtocol.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseAdapter.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/Traceable.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{DubboClientRequestAdapter.java => BraveDubboClientRequestAdapter.java} (89%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{DubboClientResponseAdapter.java => BraveDubboClientResponseAdapter.java} (80%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{DubboServerRequestAdapter.java => BraveDubboServerRequestAdapter.java} (91%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{DubboServerResponseAdapter.java => BraveDubboServerResponseAdapter.java} (82%) delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/{HttpRpcTracker.java => BraveHttpRpcTracker.java} (65%) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java index 7712530c1c1..35b562cfc32 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -27,7 +27,7 @@ public static URL parseURL(String address, Map defaults) { return null; } String url; - if (address.indexOf("://") >= 0) { + if (address.contains("://")) { url = address; } else { String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(address); @@ -69,7 +69,7 @@ public static URL parseURL(String address, Map defaults) { int port = u.getPort(); String path = u.getPath(); Map parameters = new HashMap(u.getParameters()); - if ((protocol == null || protocol.length() == 0) && defaultProtocol != null && defaultProtocol.length() > 0) { + if ((protocol == null || protocol.length() == 0) && defaultProtocol.length() > 0) { changed = true; protocol = defaultProtocol; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java index bd37378fd9a..72068a890f3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java @@ -30,6 +30,9 @@ import com.alibaba.dubbo.rpc.ProxyFactory; import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.support.MockInvoker; +import com.alibaba.dubbo.tracker.RpcTrackerEngineFactory; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; +import com.alibaba.dubbo.tracker.RpcTrackerManager; import java.util.ArrayList; import java.util.HashMap; @@ -48,13 +51,11 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { // 服务接口的本地实现类名 protected String local; - // 服务接口的本地实现类名 protected String stub; - // 服务监控 protected MonitorConfig monitor; - + // 服务追踪 protected TrackerConfig tracker; // 代理类型 @@ -219,9 +220,9 @@ protected URL loadMonitor(URL registryURL) { } appendParameters(map, monitor); String address = monitor.getAddress(); - String sysaddress = System.getProperty("dubbo.monitor.address"); - if (sysaddress != null && sysaddress.length() > 0) { - address = sysaddress; + String sysAddress = System.getProperty("dubbo.monitor.address"); + if (sysAddress != null && sysAddress.length() > 0) { + address = sysAddress; } if (ConfigUtils.isNotEmpty(address)) { if (!map.containsKey(Constants.PROTOCOL_KEY)) { @@ -238,6 +239,39 @@ protected URL loadMonitor(URL registryURL) { return null; } + protected URL loadTracker() { + if (tracker != null) { + appendProperties(tracker); + Map map = new HashMap(); + map.put("dubbo", Version.getVersion()); + map.put("application", application.getName()); + map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); + if (ConfigUtils.getPid() > 0) { + map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); + } + appendParameters(map, tracker); + String address = tracker.getAddress(); + String sysAddress = System.getProperty("dubbo.tracker.address"); + if (sysAddress != null && sysAddress.length() > 0) { + address = sysAddress; + } + if (ConfigUtils.isNotEmpty(address)) { + return UrlUtils.parseURL(address, map); + } + } + return null; + } + + protected void initRpcTrackerManagerIfNeeded() { + URL url = loadTracker(); + if (url != null) { + RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); + RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); + RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); + RpcTrackerManager.createRpcTrackerEngine(rpcTrackerEngineFactory, url); + } + } + protected void checkInterfaceAndMethods(Class interfaceClass, List methods) { // 接口不能为空 if (interfaceClass == null) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java index 6221a6d4d17..b2d366e0eb3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java @@ -40,7 +40,7 @@ public class MethodConfig extends AbstractMethodConfig { private Boolean retry; // 是否开启track,默认开启 - private Boolean trackOn = Boolean.TRUE; + private Boolean enableTrack = Boolean.TRUE; // 是否为可靠异步 private Boolean reliable; @@ -152,12 +152,12 @@ public void setSticky(Boolean sticky) { this.sticky = sticky; } - public Boolean getTrackOn() { - return trackOn; + public Boolean getEnableTrack() { + return enableTrack; } - public void setTrackOn(Boolean trackOn) { - this.trackOn = trackOn; + public void setEnableTrack(Boolean enableTrack) { + this.enableTrack = enableTrack; } @Parameter(key = Constants.ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 12dcc9472a5..7d885421b84 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -15,18 +15,6 @@ */ package com.alibaba.dubbo.config; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.Version; @@ -50,40 +38,46 @@ import com.alibaba.dubbo.rpc.service.GenericService; import com.alibaba.dubbo.rpc.support.ProtocolUtils; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.*; + /** * ReferenceConfig - * + * * @author william.liangf * @export */ public class ReferenceConfig extends AbstractReferenceConfig { - private static final long serialVersionUID = -5864351140409987595L; + private static final long serialVersionUID = -5864351140409987595L; private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); - + private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); // 接口类型 - private String interfaceName; + private String interfaceName; - private Class interfaceClass; + private Class interfaceClass; // 客户端类型 - private String client; + private String client; // 点对点直连服务提供地址 - private String url; + private String url; // 方法配置 - private List methods; + private List methods; // 缺省配置 - private ConsumerConfig consumer; - - private String protocol; + private ConsumerConfig consumer; + + private String protocol; // 接口代理类引用 private transient volatile T ref; @@ -102,7 +96,7 @@ public class ReferenceConfig extends AbstractReferenceConfig { protected void finalize() throws Throwable { super.finalize(); - if(! ReferenceConfig.this.destroyed) { + if (!ReferenceConfig.this.destroyed) { logger.warn("ReferenceConfig(" + url + ") is not DESTROYED when FINALIZE"); /* 先不做Destroy操作 @@ -116,8 +110,9 @@ protected void finalize() throws Throwable { } }; - public ReferenceConfig() {} - + public ReferenceConfig() { + } + public ReferenceConfig(Reference reference) { appendAnnotation(Reference.class, reference); } @@ -131,20 +126,20 @@ public List toUrls() { } public synchronized T get() { - if (destroyed){ + if (destroyed) { throw new IllegalStateException("Already destroyed!"); } - if (ref == null) { - init(); - } - return ref; + if (ref == null) { + init(); + } + return ref; } - + public synchronized void destroy() { if (ref == null) { return; } - if (destroyed){ + if (destroyed) { return; } destroyed = true; @@ -158,15 +153,15 @@ public synchronized void destroy() { } private void init() { - if (initialized) { - return; - } - initialized = true; - if (interfaceName == null || interfaceName.length() == 0) { - throw new IllegalStateException(" interface not allow null!"); - } - // 获取消费者全局配置 - checkDefault(); + if (initialized) { + return; + } + initialized = true; + if (interfaceName == null || interfaceName.length() == 0) { + throw new IllegalStateException(" interface not allow null!"); + } + // 获取消费者全局配置 + checkDefault(); appendProperties(this); if (getGeneric() == null && getConsumer() != null) { setGeneric(getConsumer().getGeneric()); @@ -175,50 +170,50 @@ private void init() { interfaceClass = GenericService.class; } else { try { - interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() - .getContextClassLoader()); - } catch (ClassNotFoundException e) { - throw new IllegalStateException(e.getMessage(), e); - } + 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); - } catch (IOException e) { - throw new IllegalStateException("Unload " + resolveFile + ", cause: " + e.getMessage(), e); - } finally { - try { - if(null != fis) fis.close(); + 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); + } catch (IOException e) { + throw new IllegalStateException("Unload " + resolveFile + ", cause: " + e.getMessage(), e); + } finally { + try { + if (null != fis) fis.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } - } - resolve = properties.getProperty(interfaceName); - } + } + resolve = properties.getProperty(interfaceName); + } } if (resolve != null && resolve.length() > 0) { - url = resolve; - if (logger.isWarnEnabled()) { - if (resolveFile != null && resolveFile.length() > 0) { - logger.warn("Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); - } else { - logger.warn("Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); - } - } + url = resolve; + if (logger.isWarnEnabled()) { + if (resolveFile != null && resolveFile.length() > 0) { + logger.warn("Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); + } else { + logger.warn("Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); + } + } } if (consumer != null) { if (application == null) { @@ -260,18 +255,17 @@ private void init() { if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); } - if (! isGeneric()) { + if (!isGeneric()) { String revision = Version.getVersion(interfaceClass, version); if (revision != null && revision.length() > 0) { map.put("revision", revision); } String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); - if(methods.length == 0) { + if (methods.length == 0) { logger.warn("NO method found in service interface " + interfaceClass.getName()); map.put("methods", Constants.ANY_VALUE); - } - else { + } else { map.put("methods", StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); } } @@ -299,65 +293,67 @@ private void init() { StaticContext.getSystemContext().putAll(attributes); ref = createProxy(map); } - - private static void checkAndConvertImplicitConfig(MethodConfig method, Map map, Map attributes){ - //check config conflict + + private static void checkAndConvertImplicitConfig(MethodConfig method, Map map, Map attributes) { + //check config conflict if (Boolean.FALSE.equals(method.isReturn()) && (method.getOnreturn() != null || method.getOnthrow() != null)) { throw new IllegalStateException("method config error : return attribute must be set true when onreturn or onthrow has been setted."); } //convert onreturn methodName to Method - String onReturnMethodKey = StaticContext.getKey(map,method.getName(),Constants.ON_RETURN_METHOD_KEY); + String onReturnMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_RETURN_METHOD_KEY); Object onReturnMethod = attributes.get(onReturnMethodKey); - if (onReturnMethod != null && onReturnMethod instanceof String){ + if (onReturnMethod != null && onReturnMethod instanceof String) { attributes.put(onReturnMethodKey, getMethodByName(method.getOnreturn().getClass(), onReturnMethod.toString())); } //convert onthrow methodName to Method - String onThrowMethodKey = StaticContext.getKey(map,method.getName(),Constants.ON_THROW_METHOD_KEY); + String onThrowMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_THROW_METHOD_KEY); Object onThrowMethod = attributes.get(onThrowMethodKey); - if (onThrowMethod != null && onThrowMethod instanceof String){ + if (onThrowMethod != null && onThrowMethod instanceof String) { attributes.put(onThrowMethodKey, getMethodByName(method.getOnthrow().getClass(), onThrowMethod.toString())); } //convert oninvoke methodName to Method - String onInvokeMethodKey = StaticContext.getKey(map,method.getName(),Constants.ON_INVOKE_METHOD_KEY); + String onInvokeMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_INVOKE_METHOD_KEY); Object onInvokeMethod = attributes.get(onInvokeMethodKey); - if (onInvokeMethod != null && onInvokeMethod instanceof String){ + if (onInvokeMethod != null && onInvokeMethod instanceof String) { attributes.put(onInvokeMethodKey, getMethodByName(method.getOninvoke().getClass(), onInvokeMethod.toString())); } } - private static Method getMethodByName(Class clazz, String methodName){ + private static Method getMethodByName(Class clazz, String methodName) { try { return ReflectUtils.findMethodByMethodName(clazz, methodName); } catch (Exception e) { throw new IllegalStateException(e); } } - - @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" }) - private T createProxy(Map map) { - URL tmpUrl = new URL("temp", "localhost", 0, map); - final boolean isJvmRefer; + + @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) + private T createProxy(Map map) { + URL tmpUrl = new URL("temp", "localhost", 0, map); + final boolean isJvmRefer; if (isInjvm() == null) { - if (url != null && url.length() > 0) { //指定URL的情况下,不做本地引用 + if (url != null && url.length() > 0) { + //指定URL的情况下,不做本地引用 isJvmRefer = false; - } else if (InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl)) { - //默认情况下如果本地有服务暴露,则引用本地服务. - isJvmRefer = true; } else { - isJvmRefer = false; + //默认情况下如果本地有服务暴露,则引用本地服务. + isJvmRefer = InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl); } } else { - isJvmRefer = isInjvm().booleanValue(); + isJvmRefer = isInjvm(); } - - if (isJvmRefer) { - URL url = new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0, interfaceClass.getName()).addParameters(map); - invoker = refprotocol.refer(interfaceClass, url); + + initRpcTrackerManagerIfNeeded(); + + if (isJvmRefer) { + URL url = new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0, interfaceClass.getName()).addParameters(map); + invoker = refprotocol.refer(interfaceClass, url); if (logger.isInfoEnabled()) { logger.info("Using injvm service " + interfaceClass.getName()); } - } else { - if (url != null && url.length() > 0) { // 用户指定URL,指定的URL可能是对点对直连地址,也可能是注册中心URL + } else { + // 用户指定URL,指定的URL可能是对点对直连地址,也可能是注册中心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) { @@ -372,19 +368,22 @@ private T createProxy(Map map) { } } } - } else { // 通过注册中心配置拼装URL - List us = loadRegistries(false); - if (us != null && us.size() > 0) { - for (URL u : us) { - URL monitorUrl = loadMonitor(u); + } 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))); + 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 == 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."); } } @@ -401,9 +400,9 @@ private T createProxy(Map map) { } if (registryURL != null) { // 有 注册中心协议的URL // 对有注册中心的Cluster 只用 AvailableCluster - URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME); + URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME); invoker = cluster.join(new StaticDirectory(u, invokers)); - } else { // 不是 注册中心的URL + } else { // 不是 注册中心的URL invoker = cluster.join(new StaticDirectory(invokers)); } } @@ -414,10 +413,13 @@ private T createProxy(Map map) { c = consumer.isCheck(); } if (c == null) { - c = true; // default true + c = true; } - if (c && ! invoker.isAvailable()) { - throw new IllegalStateException("Failed to check the status of the service " + interfaceName + ". No provider available for the service " + (group == null ? "" : group + "/") + interfaceName + (version == null ? "" : ":" + version) + " from the url " + invoker.getUrl() + " to the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion()); + if (c && !invoker.isAvailable()) { + throw new IllegalStateException("Failed to check the status of the service " + + interfaceName + ". No provider available for the service " + (group == null ? "" : group + "/") + + interfaceName + (version == null ? "" : ":" + version) + " from the url " + + invoker.getUrl() + " to the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion()); } if (logger.isInfoEnabled()) { logger.info("Refer dubbo service " + interfaceClass.getName() + " from url " + invoker.getUrl()); @@ -433,34 +435,34 @@ private void checkDefault() { appendProperties(consumer); } - public Class getInterfaceClass() { - if (interfaceClass != null) { - return interfaceClass; - } - if (isGeneric() - || (getConsumer() != null && getConsumer().isGeneric())) { - return GenericService.class; - } - try { - if (interfaceName != null && interfaceName.length() > 0) { - this.interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() - .getContextClassLoader()); - } + public Class getInterfaceClass() { + if (interfaceClass != null) { + return interfaceClass; + } + if (isGeneric() + || (getConsumer() != null && getConsumer().isGeneric())) { + return GenericService.class; + } + try { + if (interfaceName != null && interfaceName.length() > 0) { + this.interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() + .getContextClassLoader()); + } } catch (ClassNotFoundException t) { throw new IllegalStateException(t.getMessage(), t); } - return interfaceClass; - } - - /** - * @deprecated - * @see #setInterface(Class) - * @param interfaceClass - */ - @Deprecated - public void setInterfaceClass(Class interfaceClass) { - setInterface(interfaceClass); - } + return interfaceClass; + } + + /** + * @param interfaceClass + * @see #setInterface(Class) + * @deprecated + */ + @Deprecated + public void setInterfaceClass(Class interfaceClass) { + setInterface(interfaceClass); + } public String getInterface() { return interfaceName; @@ -472,9 +474,9 @@ public void setInterface(String interfaceName) { id = interfaceName; } } - + public void setInterface(Class interfaceClass) { - if (interfaceClass != null && ! interfaceClass.isInterface()) { + if (interfaceClass != null && !interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } this.interfaceClass = interfaceClass; @@ -517,16 +519,16 @@ public void setConsumer(ConsumerConfig consumer) { } public String getProtocol() { - return protocol; - } + return protocol; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setProtocol(String protocol) { + this.protocol = protocol; + } - // just for test + // just for test Invoker getInvoker() { return invoker; } - + } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index bc143fdeff2..303fe65cdce 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -266,6 +266,7 @@ public synchronized void unexport() { @SuppressWarnings({"unchecked", "rawtypes"}) private void doExportUrls() { + initRpcTrackerManagerIfNeeded(); List registryURLs = loadRegistries(true); for (ProtocolConfig protocolConfig : protocols) { doExportUrlsFor1Protocol(protocolConfig, registryURLs); @@ -367,11 +368,11 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r Method[] methods = interfaceClass.getMethods(); //遍历所有方法 if (methods != null && methods.length > 0) { - for (int i = 0; i < methods.length; i++) { - String methodName = methods[i].getName(); + for (Method mtd : methods) { + String methodName = mtd.getName(); //匹配方法名称,获取方法签名. if (methodName.equals(method.getName())) { - Class[] argtypes = methods[i].getParameterTypes(); + Class[] argtypes = mtd.getParameterTypes(); //一个方法中单个callback if (argument.getIndex() != -1) { if (argtypes[argument.getIndex()].getName().equals(argument.getType())) { @@ -399,10 +400,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } else { throw new IllegalArgumentException("argument config must set index or type attribute.eg: or "); } - } } - } // end of methods for + } } if (ProtocolUtils.isGeneric(generic)) { @@ -449,7 +449,6 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r String scope = url.getParameter(Constants.SCOPE_KEY); //配置为none不暴露 if (!Constants.SCOPE_NONE.equalsIgnoreCase(scope)) { - //配置不是remote的情况下做本地暴露 (配置为remote,则表示只暴露远程服务) if (!Constants.SCOPE_REMOTE.equalsIgnoreCase(scope)) { exportLocal(url); @@ -470,14 +469,13 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (logger.isInfoEnabled()) { logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL); } - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); - + Invoker invoker = proxyFactory.getInvoker(ref, + (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); Exporter exporter = protocol.export(invoker); exporters.add(exporter); } } else { Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url); - Exporter exporter = protocol.export(invoker); exporters.add(exporter); } @@ -652,7 +650,7 @@ public void setProviders(List providers) { } @Deprecated - private static final List convertProviderToProtocol(List providers) { + private static List convertProviderToProtocol(List providers) { if (providers == null || providers.size() == 0) { return null; } @@ -664,7 +662,7 @@ private static final List convertProviderToProtocol(List convertProtocolToProvider(List protocols) { + private static List convertProtocolToProvider(List protocols) { if (protocols == null || protocols.size() == 0) { return null; } @@ -676,7 +674,7 @@ private static final List convertProtocolToProvider(List parameters; public TrackerConfig() { @@ -52,6 +56,14 @@ public void setAddress(String address) { this.address = address; } + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + public String getCollector() { return collector; } @@ -68,20 +80,20 @@ public void setSampler(String sampler) { this.sampler = sampler; } - public Float getSampleRate() { - return sampleRate; + public Float getSamplerate() { + return samplerate; } - public void setSampleRate(Float sampleRate) { - this.sampleRate = sampleRate; + public void setSamplerate(Float samplerate) { + this.samplerate = samplerate; } - public Integer getFlushInterval() { - return flushInterval; + public Integer getFlushinterval() { + return flushinterval; } - public void setFlushInterval(Integer flushInterval) { - this.flushInterval = flushInterval; + public void setFlushinterval(Integer flushinterval) { + this.flushinterval = flushinterval; } public String getGroup() { diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java index 56603d313fd..c9e4e0a9aaa 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java @@ -12,8 +12,8 @@ public void test_trackConfig(){ trackerConfig.setApplication("test"); trackerConfig.setCollector("kafka"); trackerConfig.setSampler("counting"); - trackerConfig.setSampleRate(0.1f); - trackerConfig.setFlushInterval(2); + trackerConfig.setSamplerate(0.1f); + trackerConfig.setFlushinterval(2); System.out.println(trackerConfig.toString()); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java index c2b9cd09f6d..c73ac065f66 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java @@ -158,6 +158,24 @@ public void afterPropertiesSet() throws Exception { } } } + + if (getTracker() == null && + (getConsumer() == null || getConsumer().getTracker() == null) && + (getApplication() == null || getApplication().getTracker() == null)) { + Map trackerConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, TrackerConfig.class, false, false); + if (trackerConfigMap != null && trackerConfigMap.size() > 0) { + TrackerConfig trackerConfig = null; + for (TrackerConfig config : trackerConfigMap.values()) { + trackerConfig = config; + } + if (trackerConfig != null) { + setTracker(trackerConfig); + } + } + } + + Boolean b = isInit(); if (b == null && getConsumer() != null) { b = getConsumer().isInit(); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index 0a2a0334e09..0007325beed 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -117,9 +117,11 @@ private boolean isDelay() { @SuppressWarnings({"unchecked", "deprecation"}) public void afterPropertiesSet() throws Exception { if (getProvider() == null) { - Map providerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false); + Map providerConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false); if (providerConfigMap != null && providerConfigMap.size() > 0) { - Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); + Map protocolConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); if ((protocolConfigMap == null || protocolConfigMap.size() == 0) && providerConfigMap.size() > 1) { // 兼容旧版本 List providerConfigs = new ArrayList(); @@ -149,7 +151,8 @@ public void afterPropertiesSet() throws Exception { } if (getApplication() == null && (getProvider() == null || getProvider().getApplication() == null)) { - Map applicationConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class, false, false); + Map applicationConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class, false, false); if (applicationConfigMap != null && applicationConfigMap.size() > 0) { ApplicationConfig applicationConfig = null; for (ApplicationConfig config : applicationConfigMap.values()) { @@ -167,7 +170,8 @@ public void afterPropertiesSet() throws Exception { } if (getModule() == null && (getProvider() == null || getProvider().getModule() == null)) { - Map moduleConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ModuleConfig.class, false, false); + Map moduleConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ModuleConfig.class, false, false); if (moduleConfigMap != null && moduleConfigMap.size() > 0) { ModuleConfig moduleConfig = null; for (ModuleConfig config : moduleConfigMap.values()) { @@ -186,7 +190,8 @@ public void afterPropertiesSet() throws Exception { if ((getRegistries() == null || getRegistries().size() == 0) && (getProvider() == null || getProvider().getRegistries() == null || getProvider().getRegistries().size() == 0) && (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().size() == 0)) { - Map registryConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false); + Map registryConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false); if (registryConfigMap != null && registryConfigMap.size() > 0) { List registryConfigs = new ArrayList(); for (RegistryConfig config : registryConfigMap.values()) { @@ -202,7 +207,8 @@ public void afterPropertiesSet() throws Exception { if (getMonitor() == null && (getProvider() == null || getProvider().getMonitor() == null) && (getApplication() == null || getApplication().getMonitor() == null)) { - Map monitorConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, MonitorConfig.class, false, false); + Map monitorConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, MonitorConfig.class, false, false); if (monitorConfigMap != null && monitorConfigMap.size() > 0) { MonitorConfig monitorConfig = null; for (MonitorConfig config : monitorConfigMap.values()) { @@ -219,16 +225,26 @@ public void afterPropertiesSet() throws Exception { } } - //TODO ADD TRACKER HERE if (getTracker() == null && (getProvider() == null || getProvider().getTracker() == null) && (getApplication() == null || getApplication().getTracker() == null)) { - + Map trackerConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, TrackerConfig.class, false, false); + if (trackerConfigMap != null && trackerConfigMap.size() > 0) { + TrackerConfig trackerConfig = null; + for (TrackerConfig config : trackerConfigMap.values()) { + trackerConfig = config; + } + if (trackerConfig != null) { + setTracker(trackerConfig); + } + } } if ((getProtocols() == null || getProtocols().size() == 0) && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().size() == 0)) { - Map protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); + Map protocolConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false); if (protocolConfigMap != null && protocolConfigMap.size() > 0) { List protocolConfigs = new ArrayList(); for (ProtocolConfig config : protocolConfigMap.values()) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java index 2110d034c8a..28ee29ef744 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java @@ -108,6 +108,7 @@ private static BeanDefinition parse(Element element, ParserContext parserContext PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol"); if (property != null) { Object value = property.getValue(); + assert id != null; if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) { definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id)); } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 93f1ae5eac3..a1c12ddc1e7 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -532,6 +532,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1146,6 +1207,12 @@ + + + + + + diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 494aff3c824..4d9d7afb4e4 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -9,6 +9,8 @@ + + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index d46308dad7c..9a06c500821 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,6 +24,8 @@ + + @@ -62,7 +64,8 @@ - + diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java index a1426464e5d..485fee0fb07 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/integration/RegistryProtocol.java @@ -103,7 +103,7 @@ public Exporter export(final Invoker originInvoker) throws RpcExceptio final ExporterChangeableWrapper exporter = doLocalExport(originInvoker); //registry provider final Registry registry = getRegistry(originInvoker); - final URL registedProviderUrl = getRegistedProviderUrl(originInvoker); + final URL registedProviderUrl = getRegisteredProviderUrl(originInvoker); registry.register(registedProviderUrl); // 订阅override数据 // FIXME 提供者订阅时,会影响同一JVM即暴露服务,又引用同一服务的的场景,因为subscribed以服务名为缓存的key,导致订阅信息覆盖。 @@ -146,13 +146,13 @@ private ExporterChangeableWrapper doLocalExport(final Invoker originIn synchronized (bounds) { exporter = (ExporterChangeableWrapper) bounds.get(key); if (exporter == null) { - final Invoker invokerDelegete = new InvokerDelegete(originInvoker, getProviderUrl(originInvoker)); - exporter = new ExporterChangeableWrapper((Exporter) protocol.export(invokerDelegete), originInvoker); + final Invoker invokerDelegate = new InvokerDelegate(originInvoker, getProviderUrl(originInvoker)); + exporter = new ExporterChangeableWrapper((Exporter) protocol.export(invokerDelegate), originInvoker); bounds.put(key, exporter); } } } - return (ExporterChangeableWrapper) exporter; + return exporter; } /** @@ -168,7 +168,7 @@ private void doChangeLocalExport(final Invoker originInvoker, URL newInvo if (exporter == null) { logger.warn(new IllegalStateException("error state, exporter should not be null")); } else { - final Invoker invokerDelegete = new InvokerDelegete(originInvoker, newInvokerUrl); + final Invoker invokerDelegete = new InvokerDelegate(originInvoker, newInvokerUrl); exporter.setExporter(protocol.export(invokerDelegete)); } } @@ -194,14 +194,14 @@ private Registry getRegistry(final Invoker originInvoker) { * @param originInvoker * @return */ - private URL getRegistedProviderUrl(final Invoker originInvoker) { + private URL getRegisteredProviderUrl(final Invoker originInvoker) { URL providerUrl = getProviderUrl(originInvoker); //注册中心看到的地址 return providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameter(Constants.MONITOR_KEY); } - private URL getSubscribedOverrideUrl(URL registedProviderUrl) { - return registedProviderUrl.setProtocol(Constants.PROVIDER_PROTOCOL) + private URL getSubscribedOverrideUrl(URL registeredProviderUrl) { + return registeredProviderUrl.setProtocol(Constants.PROVIDER_PROTOCOL) .addParameters(Constants.CATEGORY_KEY, Constants.CONFIGURATORS_CATEGORY, Constants.CHECK_KEY, String.valueOf(false)); } @@ -247,9 +247,6 @@ public Invoker refer(Class type, URL url) throws RpcException { if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1 || Constants.ANY_VALUE.equals(group)) { return doRefer(getCluster("mergeable"), registry, type, url); } -// else if (Constants.GROUPING.equals(group)) { -// return doRefer(getCluster("grouping"), registry, type, url); -// } } return doRefer(cluster, registry, type, url); } @@ -334,7 +331,7 @@ public void notify(List urls) { result = new ArrayList(urls); } result.remove(url); - logger.warn("Subsribe category=configurator, but notifed non-configurator urls. may be registry bug. unexcepted url: " + url); + logger.warn("Subscribe category=configurator, but notified non-configurator urls. may be registry bug. unexcepted url: " + url); } } if (result != null) { @@ -345,8 +342,8 @@ public void notify(List urls) { for (ExporterChangeableWrapper exporter : exporters) { Invoker invoker = exporter.getOriginInvoker(); final Invoker originInvoker; - if (invoker instanceof InvokerDelegete) { - originInvoker = ((InvokerDelegete) invoker).getInvoker(); + if (invoker instanceof InvokerDelegate) { + originInvoker = ((InvokerDelegate) invoker).getInvoker(); } else { originInvoker = invoker; } @@ -372,21 +369,21 @@ private URL getNewInvokerUrl(URL url, List urls) { } } - public static class InvokerDelegete extends InvokerWrapper { + public static class InvokerDelegate extends InvokerWrapper { private final Invoker invoker; /** * @param invoker * @param url invoker.getUrl返回此值 */ - public InvokerDelegete(Invoker invoker, URL url) { + public InvokerDelegate(Invoker invoker, URL url) { super(invoker, url); this.invoker = invoker; } public Invoker getInvoker() { - if (invoker instanceof InvokerDelegete) { - return ((InvokerDelegete) invoker).getInvoker(); + if (invoker instanceof InvokerDelegate) { + return ((InvokerDelegate) invoker).getInvoker(); } else { return invoker; } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java index 1a39435f964..ecf42042c65 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -15,12 +15,6 @@ */ package com.alibaba.dubbo.registry.zookeeper; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -30,14 +24,20 @@ import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.support.FailbackRegistry; import com.alibaba.dubbo.remoting.zookeeper.ChildListener; -import com.alibaba.dubbo.remoting.zookeeper.ZookeeperClient; import com.alibaba.dubbo.remoting.zookeeper.StateListener; +import com.alibaba.dubbo.remoting.zookeeper.ZookeeperClient; import com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter; import com.alibaba.dubbo.rpc.RpcException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + /** * ZookeeperRegistry - * + * * @author william.liangf */ public class ZookeeperRegistry extends FailbackRegistry { @@ -45,37 +45,37 @@ public class ZookeeperRegistry extends FailbackRegistry { private final static Logger logger = LoggerFactory.getLogger(ZookeeperRegistry.class); private final static int DEFAULT_ZOOKEEPER_PORT = 2181; - + private final static String DEFAULT_ROOT = "dubbo"; - private final String root; - + private final String root; + private final Set anyServices = new ConcurrentHashSet(); private final ConcurrentMap> zkListeners = new ConcurrentHashMap>(); - + private final ZookeeperClient zkClient; - + public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { super(url); if (url.isAnyHost()) { - throw new IllegalStateException("registry address == null"); - } + throw new IllegalStateException("registry address == null"); + } String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (! group.startsWith(Constants.PATH_SEPARATOR)) { + if (!group.startsWith(Constants.PATH_SEPARATOR)) { group = Constants.PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperTransporter.connect(url); zkClient.addStateListener(new StateListener() { public void stateChanged(int state) { - if (state == RECONNECTED) { - try { - recover(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } + if (state == RECONNECTED) { + try { + recover(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } } }); } @@ -95,7 +95,7 @@ public void destroy() { protected void doRegister(URL url) { try { - zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); + zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); } catch (Throwable e) { throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } @@ -123,10 +123,10 @@ protected void doSubscribe(final URL url, final NotifyListener listener) { listeners.putIfAbsent(listener, new ChildListener() { public void childChanged(String parentPath, List currentChilds) { for (String child : currentChilds) { - child = URL.decode(child); - if (! anyServices.contains(child)) { + child = URL.decode(child); + if (!anyServices.contains(child)) { anyServices.add(child); - subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, + subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, Constants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -138,9 +138,9 @@ public void childChanged(String parentPath, List currentChilds) { List services = zkClient.addChildListener(root, zkListener); if (services != null && services.size() > 0) { for (String service : services) { - service = URL.decode(service); - anyServices.add(service); - subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, + service = URL.decode(service); + anyServices.add(service); + subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -156,7 +156,7 @@ public void childChanged(String parentPath, List currentChilds) { if (zkListener == null) { listeners.putIfAbsent(listener, new ChildListener() { public void childChanged(String parentPath, List currentChilds) { - ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)); + ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)); } }); zkListener = listeners.get(listener); @@ -164,7 +164,7 @@ public void childChanged(String parentPath, List currentChilds) { zkClient.create(path, false); List children = zkClient.addChildListener(path, zkListener); if (children != null) { - urls.addAll(toUrlsWithEmpty(url, path, children)); + urls.addAll(toUrlsWithEmpty(url, path, children)); } } notify(url, listener, urls); @@ -191,28 +191,28 @@ public List lookup(URL url) { try { List providers = new ArrayList(); for (String path : toCategoriesPath(url)) { - List children = zkClient.getChildren(path); - if (children != null) { - providers.addAll(children); - } + List children = zkClient.getChildren(path); + if (children != null) { + providers.addAll(children); + } } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { throw new RpcException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } - + private String toRootDir() { if (root.equals(Constants.PATH_SEPARATOR)) { return root; } return root + Constants.PATH_SEPARATOR; } - + private String toRootPath() { return root; } - + private String toServicePath(URL url) { String name = url.getServiceInterface(); if (Constants.ANY_VALUE.equals(name)) { @@ -224,13 +224,13 @@ private String toServicePath(URL url) { private String[] toCategoriesPath(URL url) { String[] categroies; if (Constants.ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { - categroies = new String[] {Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, + categroies = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; } else { - categroies = url.getParameter(Constants.CATEGORY_KEY, new String[] {Constants.DEFAULT_CATEGORY}); + categroies = url.getParameter(Constants.CATEGORY_KEY, new String[]{Constants.DEFAULT_CATEGORY}); } String[] paths = new String[categroies.length]; - for (int i = 0; i < categroies.length; i ++) { + for (int i = 0; i < categroies.length; i++) { paths[i] = toServicePath(url) + Constants.PATH_SEPARATOR + categroies[i]; } return paths; @@ -243,9 +243,9 @@ private String toCategoryPath(URL url) { private String toUrlPath(URL url) { return toCategoryPath(url) + Constants.PATH_SEPARATOR + URL.encode(url.toFullString()); } - + private List toUrlsWithoutEmpty(URL consumer, List providers) { - List urls = new ArrayList(); + List urls = new ArrayList(); if (providers != null && providers.size() > 0) { for (String provider : providers) { provider = URL.decode(provider); @@ -263,9 +263,9 @@ private List toUrlsWithoutEmpty(URL consumer, List providers) { private List toUrlsWithEmpty(URL consumer, String path, List providers) { List urls = toUrlsWithoutEmpty(consumer, providers); if (urls.isEmpty()) { - int i = path.lastIndexOf('/'); - String category = i < 0 ? path : path.substring(i + 1); - URL empty = consumer.setProtocol(Constants.EMPTY_PROTOCOL).addParameter(Constants.CATEGORY_KEY, category); + int i = path.lastIndexOf('/'); + String category = i < 0 ? path : path.substring(i + 1); + URL empty = consumer.setProtocol(Constants.EMPTY_PROTOCOL).addParameter(Constants.CATEGORY_KEY, category); urls.add(empty); } return urls; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 603f771c096..dc05df681b7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -16,19 +16,19 @@ package com.alibaba.dubbo.remoting.exchange.support.header; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.Transporters; +import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.transport.DecodeHandler; import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.zipkin.DubboClientRequestResponseInterceptor; -import com.alibaba.dubbo.tracker.zipkin.DubboRpcTracker; -import com.alibaba.dubbo.tracker.zipkin.DubboServerRequestResponseInterceptor; +import com.alibaba.dubbo.tracker.zipkin.BraveDubboClientRequestResponseInterceptor; +import com.alibaba.dubbo.tracker.zipkin.BraveDubboServerRequestResponseInterceptor; /** * DefaultMessenger @@ -39,31 +39,23 @@ public class HeaderExchanger implements Exchanger { public static final String NAME = "header"; - // for test - public static RpcTrackerEngine rpcTrackerEngine; - public static DubboRpcTracker rpcTracker; - - static { - URL url = URL.valueOf("zipkin://localhost:9411?application=consumer&collector=http&sampler=counting&rate=1"); - rpcTrackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); - url = URL.valueOf("dubbo://localhost:9411?application=consumer&collector=http&sampler=counting&rate=0.2"); - rpcTracker = (DubboRpcTracker) RpcTrackerManager.createRpcTracker(url); - } - public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); - DubboClientRequestResponseInterceptor interceptor = new DubboClientRequestResponseInterceptor(rpcTracker.clientRequestInterceptor(), - rpcTracker.clientResponseInterceptor(), new DubboRequestSpanNameProvider()); - headerExchangeClient.addInterceptor(interceptor); + RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); + if (rpcTracker != null) { + BraveDubboClientRequestResponseInterceptor interceptor = new BraveDubboClientRequestResponseInterceptor(rpcTracker, new DubboRequestSpanNameProvider()); + headerExchangeClient.addInterceptor(interceptor); + } return headerExchangeClient; } public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeHandler exchangeHandler = new HeaderExchangeHandler(handler); - DubboServerRequestResponseInterceptor interceptor = new DubboServerRequestResponseInterceptor(rpcTracker.serverRequestInterceptor(), - rpcTracker.serverResponseInterceptor(), new DubboRequestSpanNameProvider()); - exchangeHandler.addInterceptor(interceptor); + RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); + if (rpcTracker != null) { + BraveDubboServerRequestResponseInterceptor interceptor = new BraveDubboServerRequestResponseInterceptor(rpcTracker, new DubboRequestSpanNameProvider()); + exchangeHandler.addInterceptor(interceptor); + } return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(exchangeHandler))); } - } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java index a93d8939e61..3f25af2d23c 100644 --- a/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-common/src/main/java/com/alibaba/dubbo/remoting/transport/ChannelHandler.java @@ -21,9 +21,7 @@ /** * ChannelHandler. (API, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.Transporter#bind(com.alibaba.dubbo.common.URL, ChannelHandler) - * @see com.alibaba.dubbo.remoting.Transporter#connect(com.alibaba.dubbo.common.URL, ChannelHandler) + * * @author qian.lei * @author william.liangf */ @@ -32,21 +30,21 @@ public interface ChannelHandler { /** * on channel connected. - * + * * @param channel channel. */ void connected(Channel channel) throws RemotingException; /** * on channel disconnected. - * + * * @param channel channel. */ void disconnected(Channel channel) throws RemotingException; /** * on message sent. - * + * * @param channel channel. * @param message message. */ @@ -54,7 +52,7 @@ public interface ChannelHandler { /** * on message received. - * + * * @param channel channel. * @param message message. */ @@ -62,8 +60,8 @@ public interface ChannelHandler { /** * on exception caught. - * - * @param channel channel. + * + * @param channel channel. * @param exception exception. */ void caught(Channel channel, Throwable exception) throws RemotingException; diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index dc091f954cf..156d2d09df3 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -54,7 +54,7 @@ public void stateChanged(CuratorFramework client, ConnectionState state) { public void createPersistent(String path) { try { client.create().forPath(path); - } catch (NodeExistsException e) { + } catch (NodeExistsException ignored) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } @@ -63,7 +63,7 @@ public void createPersistent(String path) { public void createEphemeral(String path) { try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (NodeExistsException e) { + } catch (NodeExistsException ignored) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } @@ -72,7 +72,7 @@ public void createEphemeral(String path) { public void delete(String path) { try { client.delete().forPath(path); - } catch (NoNodeException e) { + } catch (NoNodeException ignored) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestAdapter.java new file mode 100644 index 00000000000..7b03a8cf413 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestAdapter.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs. + */ +public interface ClientRequestAdapter extends Traceable{ +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java index c113aa5128a..e2c1649ad86 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientRequestInterceptor.java @@ -4,4 +4,6 @@ * @author Xs */ public interface ClientRequestInterceptor { + + void handle(ClientRequestAdapter clientRequestAdapter); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseAdapter.java new file mode 100644 index 00000000000..729c5cb95c7 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseAdapter.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs. + */ +public interface ClientResponseAdapter extends Traceable { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java index b01a1aad797..a2d0c72ae2f 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java @@ -4,4 +4,5 @@ * @author Xs */ public interface ClientResponseInterceptor { + void handle(ClientResponseAdapter clientResponseAdapter); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcProtocol.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcProtocol.java new file mode 100644 index 00000000000..ba228655c56 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcProtocol.java @@ -0,0 +1,61 @@ +package com.alibaba.dubbo.tracker; + +import com.alibaba.dubbo.common.utils.StringUtils; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Xs. + */ +public class RpcProtocol { + + public static final RpcProtocol DUBBO = new RpcProtocol("dubbo"); + public static final RpcProtocol HESSIAN = new RpcProtocol("hessian"); + public static final RpcProtocol HTTP = new RpcProtocol("http"); + + private static final Map PROTOCOL_MAP = new HashMap(); + + static { + PROTOCOL_MAP.put(DUBBO.protocol(), DUBBO); + PROTOCOL_MAP.put(HESSIAN.protocol(), HESSIAN); + PROTOCOL_MAP.put(HTTP.protocol(), HTTP); + } + + private final String protocol; + + public RpcProtocol(String protocol) { + this.protocol = protocol; + } + + public String protocol() { + return protocol; + } + + public static RpcProtocol valueOf(String protocol) { + if (StringUtils.isEmpty(protocol)) { + throw new IllegalArgumentException("protocol must not be null!"); + } + RpcProtocol rpcProtocol = PROTOCOL_MAP.get(protocol); + if (rpcProtocol == null) { + throw new IllegalArgumentException("cannot find protocol, " + protocol); + } + return rpcProtocol; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) { + return false; + } + RpcProtocol that = (RpcProtocol) o; + return protocol.equals(that.protocol); + + } + + @Override + public int hashCode() { + return 31 * protocol.hashCode() + 29; + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index 28d5e1c24b1..f18c72620d8 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -1,19 +1,18 @@ package com.alibaba.dubbo.tracker; -import com.sun.javafx.scene.traversal.TraversalEngine; - /** * @author Xs */ public interface RpcTracker { - ClientRequestInterceptor clientRequestInterceptor(); - ClientResponseInterceptor clientResponseInterceptor(); + void trackClientRequest(ClientRequestAdapter clientRequestAdapter); + + void trackClientResponse(ClientResponseAdapter clientResponseAdapter); - ServerRequestInterceptor serverRequestInterceptor(); + void trackServerRequest(ServerRequestAdapter serverRequestAdapter); - ServerResponseInterceptor serverResponseInterceptor(); + void trackServerResponse(ServerResponseAdapter serverResponseAdapter); RpcTrackerEngine trackerEngine(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java index 74af47aeb70..29685b3d374 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java @@ -10,8 +10,7 @@ @SPI("zipkin") public interface RpcTrackerEngineFactory { - @Adaptive("protocol") + @Adaptive("trackerEngine") RpcTrackerEngine createRpcTrackerEngine(URL url); - RpcTrackerEngine getTrackerEngine(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java index be1ce7aec20..2471d4033e9 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -10,7 +10,7 @@ @SPI("zipkin") public interface RpcTrackerFactory { - @Adaptive("protocol") + @Adaptive("tracker") RpcTracker createRpcTracker(URL url); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java index 20bebc4ac46..19b6adbf30f 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java @@ -1,7 +1,6 @@ package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; import java.util.HashMap; import java.util.Map; @@ -9,58 +8,51 @@ /** * @author Xs */ -public class RpcTrackerManager { +public final class RpcTrackerManager { private static RpcTrackerFactory rpcTrackerFactory; - private static RpcTrackerEngineFactory rpcTrackerEngineFactory; - private static RpcTrackerEngine rpcTrackerEngine; - private static Map rpcTrackerMap = new HashMap(); - - static { - rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getDefaultExtension(); - rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getDefaultExtension(); - } + private static Map rpcTrackerMap = new HashMap(); public static RpcTrackerFactory getTrackerFactory() { return rpcTrackerFactory; } - public static RpcTrackerEngineFactory getRpcTrackerEngineFactory() { - return rpcTrackerEngineFactory; + public static synchronized void setRpcTrackerFactory(RpcTrackerFactory rpcTrackerFactory) { + RpcTrackerManager.rpcTrackerFactory = rpcTrackerFactory; } - public static RpcTrackerEngine getRpcTrackerEngine() { - if (rpcTrackerEngine == null) { - throw new IllegalStateException("rpcTrackerEngine should create first"); - } + public static synchronized RpcTrackerEngine getRpcTrackerEngine() { return rpcTrackerEngine; } - public static synchronized RpcTrackerEngine createRpcTrackerEngine(URL url) { + public static synchronized RpcTrackerEngine createRpcTrackerEngine(RpcTrackerEngineFactory factory, URL url) { if (rpcTrackerEngine == null) { - rpcTrackerEngine = rpcTrackerEngineFactory.createRpcTrackerEngine(url); + rpcTrackerEngine = factory.createRpcTrackerEngine(url); } return rpcTrackerEngine; } public static synchronized RpcTracker createRpcTracker(URL url) { String protocol = url.getProtocol(); - RpcTracker rpcTracker = rpcTrackerMap.get(protocol); + if (rpcTrackerEngine == null || rpcTrackerFactory == null) { + return null; + } + RpcTracker rpcTracker = rpcTrackerMap.get(RpcProtocol.valueOf(protocol)); if (rpcTracker == null) { rpcTracker = rpcTrackerFactory.createRpcTracker(url); if (rpcTracker == null) { throw new IllegalStateException("rpcTracker should not be null here, url: " + url); } - rpcTrackerMap.put(protocol, rpcTracker); + rpcTrackerMap.put(RpcProtocol.valueOf(protocol), rpcTracker); } return rpcTracker; } public static RpcTracker getRpcTracker(String protocol) { - RpcTracker rpcTracker = rpcTrackerMap.get(protocol); + RpcTracker rpcTracker = rpcTrackerMap.get(RpcProtocol.valueOf(protocol)); if (rpcTracker == null) { throw new IllegalStateException("rpcTracker should be create first!"); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestAdapter.java new file mode 100644 index 00000000000..d3563b624ef --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestAdapter.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs. + */ +public interface ServerRequestAdapter extends Traceable{ +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java index 3a1110e6fd0..3502ff3a0be 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerRequestInterceptor.java @@ -1,4 +1,7 @@ package com.alibaba.dubbo.tracker; public interface ServerRequestInterceptor { + + void handle(ServerRequestAdapter serverRequestAdapter); + } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseAdapter.java new file mode 100644 index 00000000000..80d56237618 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseAdapter.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs. + */ +public interface ServerResponseAdapter extends Traceable { +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java index a43e1a5d169..ee5947279b8 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ServerResponseInterceptor.java @@ -1,4 +1,7 @@ package com.alibaba.dubbo.tracker; public interface ServerResponseInterceptor { + + void handle(ServerResponseAdapter serverResponseAdapter); + } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/Traceable.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/Traceable.java new file mode 100644 index 00000000000..788c5bb304e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/Traceable.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs. + */ +public interface Traceable { + + boolean isTraceable(); + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java similarity index 89% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java index 602690902da..b34293e5868 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java @@ -13,13 +13,13 @@ import java.util.Collection; import java.util.Collections; -public class DubboClientRequestAdapter implements ClientRequestAdapter { +public class BraveDubboClientRequestAdapter implements ClientRequestAdapter, com.alibaba.dubbo.tracker.ClientRequestAdapter { private final DubboRequest request; private final DubboRequestSpanNameProvider spanNameProvider; - public DubboClientRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { + public BraveDubboClientRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { this.request = request; this.spanNameProvider = spanNameProvider; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java index ec4ac43482c..57f888286be 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java @@ -1,19 +1,20 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.github.kristofa.brave.ClientRequestInterceptor; +import com.alibaba.dubbo.tracker.ClientRequestAdapter; +import com.alibaba.dubbo.tracker.ClientRequestInterceptor; -public class BraveDubboClientRequestInterceptor implements DubboClientRequestInterceptor { +public class BraveDubboClientRequestInterceptor implements ClientRequestInterceptor { - private final ClientRequestInterceptor clientRequestInterceptor; + private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; - public BraveDubboClientRequestInterceptor(ClientRequestInterceptor clientRequestInterceptor) { + public BraveDubboClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor) { this.clientRequestInterceptor = clientRequestInterceptor; } @Override - public void handle(DubboClientRequestAdapter clientRequestAdapter) { + public void handle(ClientRequestAdapter clientRequestAdapter) { if (clientRequestAdapter.isTraceable()) { - clientRequestInterceptor.handle(clientRequestAdapter); + clientRequestInterceptor.handle((com.github.kristofa.brave.ClientRequestAdapter) clientRequestAdapter); } } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java new file mode 100644 index 00000000000..1270748aa03 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java @@ -0,0 +1,35 @@ +package com.alibaba.dubbo.tracker.zipkin; + + +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.RpcTracker; + +/** + * 对dubbo协议request拦截 + */ +public class BraveDubboClientRequestResponseInterceptor implements Interceptor { + + private final RpcTracker rpcTracker; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public BraveDubboClientRequestResponseInterceptor(RpcTracker rpcTracker, DubboRequestSpanNameProvider spanNameProvider) { + this.rpcTracker = rpcTracker; + this.spanNameProvider = spanNameProvider; + } + + @Override + public Response intercept(Chain chain) throws RemotingException { + Request request = chain.request(); + rpcTracker.trackClientRequest(new BraveDubboClientRequestAdapter(new DubboRequest(request), spanNameProvider)); + Response response = chain.proceed(request, chain.timeout()); + rpcTracker.trackClientResponse(new BraveDubboClientResponseAdapter(new DubboResponse(response))); + return response; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java similarity index 80% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java index 2e982e65f22..3093696bc48 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java @@ -8,11 +8,11 @@ import java.util.Collection; import java.util.Collections; -public class DubboClientResponseAdapter implements ClientResponseAdapter { +public class BraveDubboClientResponseAdapter implements ClientResponseAdapter, com.alibaba.dubbo.tracker.ClientResponseAdapter { private final DubboResponse response; - public DubboClientResponseAdapter(DubboResponse response) { + public BraveDubboClientResponseAdapter(DubboResponse response) { this.response = response; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java index 19d6151a4e4..733ffd7a367 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java @@ -1,19 +1,22 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.github.kristofa.brave.ClientResponseInterceptor; -public class BraveDubboClientResponseInterceptor implements DubboClientResponseInterceptor { +import com.alibaba.dubbo.tracker.ClientResponseAdapter; +import com.alibaba.dubbo.tracker.ClientResponseInterceptor; - private final ClientResponseInterceptor clientResponseInterceptor; +public class BraveDubboClientResponseInterceptor implements ClientResponseInterceptor { - public BraveDubboClientResponseInterceptor(ClientResponseInterceptor clientResponseInterceptor) { + private final com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor; + + public BraveDubboClientResponseInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { this.clientResponseInterceptor = clientResponseInterceptor; } + @Override - public void handle(DubboClientResponseAdapter clientResponseAdapter) { + public void handle(ClientResponseAdapter clientResponseAdapter) { if (clientResponseAdapter.isTraceable()) { - clientResponseInterceptor.handle(clientResponseAdapter); + clientResponseInterceptor.handle((com.github.kristofa.brave.ClientResponseAdapter) clientResponseAdapter); } } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java new file mode 100644 index 00000000000..4440d1687ad --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java @@ -0,0 +1,57 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.tracker.*; + +/** + * 追踪dubbo协议同步调用 + * + * @author Xs + */ +public class BraveDubboRpcTracker implements RpcTracker { + + private final ClientRequestInterceptor clientRequestInterceptor; + + private final ClientResponseInterceptor clientResponseInterceptor; + + private final ServerRequestInterceptor serverRequestInterceptor; + + private final ServerResponseInterceptor serverResponseInterceptor; + + private final BraveRpcTrackerEngine trackerEngine; + + public BraveDubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { + this.trackerEngine = trackerEngine; + this.clientRequestInterceptor = new BraveDubboClientRequestInterceptor(trackerEngine.clientRequestInterceptor()); + this.clientResponseInterceptor = new BraveDubboClientResponseInterceptor( + trackerEngine.clientResponseInterceptor()); + this.serverRequestInterceptor = new BraveDubboServerRequestInterceptor( + trackerEngine.serverRequestInterceptor()); + this.serverResponseInterceptor = new BraveDubboServerResponseInterceptor( + trackerEngine.serverResponseInterceptor()); + } + + @Override + public void trackClientRequest(ClientRequestAdapter clientRequestAdapter) { + clientRequestInterceptor.handle(clientRequestAdapter); + } + + @Override + public void trackClientResponse(ClientResponseAdapter clientResponseAdapter) { + clientResponseInterceptor.handle(clientResponseAdapter); + } + + @Override + public void trackServerRequest(ServerRequestAdapter serverRequestAdapter) { + serverRequestInterceptor.handle(serverRequestAdapter); + } + + @Override + public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { + serverResponseInterceptor.handle(serverResponseAdapter); + } + + @Override + public RpcTrackerEngine trackerEngine() { + return trackerEngine; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java similarity index 91% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java index 938ef5986f6..6ec78f527e6 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java @@ -17,13 +17,13 @@ /** * @author Xs */ -public class DubboServerRequestAdapter implements ServerRequestAdapter { +public class BraveDubboServerRequestAdapter implements ServerRequestAdapter, com.alibaba.dubbo.tracker.ServerRequestAdapter { private final DubboRequest request; private final DubboRequestSpanNameProvider spanNameProvider; - public DubboServerRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { + public BraveDubboServerRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { this.request = request; this.spanNameProvider = spanNameProvider; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java index f7d9dd60c84..1fce714bf81 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java @@ -1,22 +1,24 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.github.kristofa.brave.ServerRequestInterceptor; + +import com.alibaba.dubbo.tracker.ServerRequestAdapter; +import com.alibaba.dubbo.tracker.ServerRequestInterceptor; /** * @author Xs */ -public class BraveDubboServerRequestInterceptor implements DubboServerRequestInterceptor { +public class BraveDubboServerRequestInterceptor implements ServerRequestInterceptor { - private final ServerRequestInterceptor serverRequestInterceptor; + private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; - public BraveDubboServerRequestInterceptor(ServerRequestInterceptor serverRequestInterceptor) { + public BraveDubboServerRequestInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor) { this.serverRequestInterceptor = serverRequestInterceptor; } @Override - public void handle(DubboServerRequestAdapter serverRequestAdapter) { + public void handle(ServerRequestAdapter serverRequestAdapter) { if (serverRequestAdapter.isTraceable()) { - serverRequestInterceptor.handle(serverRequestAdapter); + serverRequestInterceptor.handle((com.github.kristofa.brave.ServerRequestAdapter) serverRequestAdapter); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java new file mode 100644 index 00000000000..9c4504b8889 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java @@ -0,0 +1,31 @@ +package com.alibaba.dubbo.tracker.zipkin; + +import com.alibaba.dubbo.remoting.exception.RemotingException; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.tracker.DubboRequest; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.RpcTracker; + +public class BraveDubboServerRequestResponseInterceptor implements Interceptor { + + private final RpcTracker rpcTracker; + + private final DubboRequestSpanNameProvider spanNameProvider; + + public BraveDubboServerRequestResponseInterceptor(RpcTracker rpcTracker, DubboRequestSpanNameProvider spanNameProvider) { + this.rpcTracker = rpcTracker; + this.spanNameProvider = spanNameProvider; + } + + @Override + public Response intercept(Chain chain) throws RemotingException { + Request request = chain.request(); + rpcTracker.trackServerRequest(new BraveDubboServerRequestAdapter(new DubboRequest(request), spanNameProvider)); + Response response = chain.proceed(request); + rpcTracker.trackServerResponse(new BraveDubboServerResponseAdapter(new DubboResponse(response))); + return response; + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java similarity index 82% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java index 953737540af..86d73c095d2 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java @@ -11,11 +11,11 @@ /** * @author Xs */ -public class DubboServerResponseAdapter implements ServerResponseAdapter { +public class BraveDubboServerResponseAdapter implements ServerResponseAdapter, com.alibaba.dubbo.tracker.ServerResponseAdapter { private final DubboResponse response; - public DubboServerResponseAdapter(DubboResponse response) { + public BraveDubboServerResponseAdapter(DubboResponse response) { this.response = response; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java index d5fe2f8d7d4..4871859c986 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java @@ -1,22 +1,24 @@ package com.alibaba.dubbo.tracker.zipkin; -import com.github.kristofa.brave.ServerResponseInterceptor; + +import com.alibaba.dubbo.tracker.ServerResponseAdapter; +import com.alibaba.dubbo.tracker.ServerResponseInterceptor; /** * @author Xs */ -public class BraveDubboServerResponseInterceptor implements DubboServerResponseInterceptor { +public class BraveDubboServerResponseInterceptor implements ServerResponseInterceptor { - private final ServerResponseInterceptor serverResponseInterceptor; + private final com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor; - public BraveDubboServerResponseInterceptor(ServerResponseInterceptor serverResponseInterceptor) { + public BraveDubboServerResponseInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { this.serverResponseInterceptor = serverResponseInterceptor; } @Override - public void handle(DubboServerResponseAdapter serverResponseAdapter) { + public void handle(ServerResponseAdapter serverResponseAdapter) { if (serverResponseAdapter.isTraceable()) { - serverResponseInterceptor.handle(serverResponseAdapter); + serverResponseInterceptor.handle((com.github.kristofa.brave.ServerResponseAdapter) serverResponseAdapter); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java index 26d13df012d..4b20be5af7e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java @@ -14,7 +14,7 @@ public class BraveRpcTrackerEngine implements RpcTrackerEngine { private final Brave brave; BraveRpcTrackerEngine(URL url) { - Brave.Builder builder = new Brave.Builder(url.getParameter("application", "demo")); + Brave.Builder builder = new Brave.Builder(url.getParameter("application")); builder.spanCollector(SpanCollectorFactory.create(url)); builder.traceSampler(SamplerFactory.create(url)); brave = builder.build(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java index dcfa7ac065b..46ee855c5dc 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java @@ -9,18 +9,8 @@ */ public class BraveRpcTrackerEngineFactory implements RpcTrackerEngineFactory { - private volatile BraveRpcTrackerEngine braveRpcTrackerEngine; - @Override public RpcTrackerEngine createRpcTrackerEngine(URL url) { - if (braveRpcTrackerEngine == null) { - braveRpcTrackerEngine = BraveRpcTrackerEngine.create(url); - } - return braveRpcTrackerEngine; - } - - @Override - public RpcTrackerEngine getTrackerEngine() { - return braveRpcTrackerEngine; + return BraveRpcTrackerEngine.create(url); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index 38867a2c2ad..496cc5f187c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -1,10 +1,8 @@ package com.alibaba.dubbo.tracker.zipkin; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; -import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.zipkin.http.HttpRpcTracker; +import com.alibaba.dubbo.tracker.*; +import com.alibaba.dubbo.tracker.zipkin.http.BraveHttpRpcTracker; /** * @author Xs @@ -13,12 +11,16 @@ public class BraveRpcTrackerFactory implements RpcTrackerFactory { @Override public RpcTracker createRpcTracker(URL url) { - String protocol = url.getProtocol(); + RpcTrackerEngine rpcTrackerEngine = RpcTrackerManager.getRpcTrackerEngine(); + if (rpcTrackerEngine == null) { + return null; + } RpcTracker rpcTracker = null; - if (protocol.equals("dubbo")) { - rpcTracker = new DubboRpcTracker((BraveRpcTrackerEngine) RpcTrackerManager.getRpcTrackerEngine()); - } else if (protocol.equals("http") || protocol.equals("hessian")) { - rpcTracker = new HttpRpcTracker((BraveRpcTrackerEngine) RpcTrackerManager.getRpcTrackerEngine()); + RpcProtocol rpcProtocol = RpcProtocol.valueOf(url.getProtocol()); + if (rpcProtocol.equals(RpcProtocol.DUBBO)) { + rpcTracker = new BraveDubboRpcTracker((BraveRpcTrackerEngine) rpcTrackerEngine); + } else if (rpcProtocol.equals(RpcProtocol.HTTP) || rpcProtocol.equals(RpcProtocol.HESSIAN)) { + rpcTracker = new BraveHttpRpcTracker(rpcTrackerEngine); } return rpcTracker; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java deleted file mode 100644 index 35ecc0f5180..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestInterceptor.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; - -public interface DubboClientRequestInterceptor extends ClientRequestInterceptor { - - void handle(DubboClientRequestAdapter clientRequestAdapter); -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java deleted file mode 100644 index 016e5e9d1ef..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientRequestResponseInterceptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - - -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.message.Interceptor; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.DubboResponse; - -public class DubboClientRequestResponseInterceptor implements Interceptor { - - private final DubboClientRequestInterceptor clientRequestInterceptor; - private final DubboClientResponseInterceptor clientResponseInterceptor; - private final DubboRequestSpanNameProvider spanNameProvider; - - public DubboClientRequestResponseInterceptor(DubboClientRequestInterceptor clientRequestInterceptor, - DubboClientResponseInterceptor clientResponseInterceptor, - DubboRequestSpanNameProvider spanNameProvider) { - this.clientRequestInterceptor = clientRequestInterceptor; - this.clientResponseInterceptor = clientResponseInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public Response intercept(Chain chain) throws RemotingException { - Request request = chain.request(); - clientRequestInterceptor.handle(new DubboClientRequestAdapter(new DubboRequest(request), spanNameProvider)); - Response response = chain.proceed(request, chain.timeout()); - clientResponseInterceptor.handle(new DubboClientResponseAdapter(new DubboResponse(response))); - return response; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java deleted file mode 100644 index c06bf6418d2..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboClientResponseInterceptor.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; - -public interface DubboClientResponseInterceptor extends ClientResponseInterceptor { - - void handle(DubboClientResponseAdapter clientResponseAdapter); -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java deleted file mode 100644 index 1451344d9b8..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboRpcTracker.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.*; - -/** - * 追踪dubbo协议同步调用 - * - * @author Xs - */ -public class DubboRpcTracker implements RpcTracker { - - private final DubboClientRequestInterceptor clientRequestInterceptor; - - private final DubboClientResponseInterceptor clientResponseInterceptor; - - private final DubboServerRequestInterceptor serverRequestInterceptor; - - private final DubboServerResponseInterceptor serverResponseInterceptor; - - private final BraveRpcTrackerEngine trackerEngine; - - public DubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { - this.trackerEngine = trackerEngine; - this.clientRequestInterceptor = new BraveDubboClientRequestInterceptor( - trackerEngine.clientRequestInterceptor()); - this.clientResponseInterceptor = new BraveDubboClientResponseInterceptor( - trackerEngine.clientResponseInterceptor()); - this.serverRequestInterceptor = new BraveDubboServerRequestInterceptor( - trackerEngine.serverRequestInterceptor()); - this.serverResponseInterceptor = new BraveDubboServerResponseInterceptor( - trackerEngine.serverResponseInterceptor()); - } - - @Override - public DubboClientRequestInterceptor clientRequestInterceptor() { - return clientRequestInterceptor; - } - - @Override - public DubboClientResponseInterceptor clientResponseInterceptor() { - return clientResponseInterceptor; - } - - @Override - public DubboServerRequestInterceptor serverRequestInterceptor() { - return serverRequestInterceptor; - } - - @Override - public DubboServerResponseInterceptor serverResponseInterceptor() { - return serverResponseInterceptor; - } - - @Override - public RpcTrackerEngine trackerEngine() { - return trackerEngine; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java deleted file mode 100644 index 13ce478e8a9..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestInterceptor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ServerRequestInterceptor; - -/** - * @author Xs - */ -public interface DubboServerRequestInterceptor extends ServerRequestInterceptor { - - void handle(DubboServerRequestAdapter serverRequestAdapter); - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java deleted file mode 100644 index fcdfab32ff5..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerRequestResponseInterceptor.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.message.Interceptor; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.DubboResponse; - -public class DubboServerRequestResponseInterceptor implements Interceptor { - - private final DubboServerRequestInterceptor serverRequestInterceptor; - - private final DubboServerResponseInterceptor serverResponseInterceptor; - - private final DubboRequestSpanNameProvider spanNameProvider; - - public DubboServerRequestResponseInterceptor(DubboServerRequestInterceptor serverRequestInterceptor, - DubboServerResponseInterceptor serverResponseInterceptor, - DubboRequestSpanNameProvider spanNameProvider) { - this.serverRequestInterceptor = serverRequestInterceptor; - this.serverResponseInterceptor = serverResponseInterceptor; - this.spanNameProvider = spanNameProvider; - } - - @Override - public Response intercept(Chain chain) throws RemotingException { - Request request = chain.request(); - serverRequestInterceptor.handle(new DubboServerRequestAdapter(new DubboRequest(request), spanNameProvider)); - Response response = chain.proceed(request); - serverResponseInterceptor.handle(new DubboServerResponseAdapter(new DubboResponse(response))); - return response; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java deleted file mode 100644 index f303b16d958..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/DubboServerResponseInterceptor.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.tracker.ServerResponseInterceptor; - -/** - * @author Xs - */ -public interface DubboServerResponseInterceptor extends ServerResponseInterceptor { - - void handle(DubboServerResponseAdapter serverResponseAdapter); -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java index 6d885268d20..8a00ba4404b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java @@ -15,7 +15,7 @@ public static Sampler create(URL url) { } else { String rate = url.getParameter("rate"); if (StringUtils.isEmpty(rate)) { - throw new IllegalArgumentException("sample rate must not be null"); + return Sampler.ALWAYS_SAMPLE; } if (sampler.equals("counting")) { return CountingSampler.create(Float.valueOf(rate)); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java similarity index 65% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java index 3a942fc1e6b..bc56e035b9e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java @@ -6,11 +6,11 @@ /** * @author Xs */ -public class HttpRpcTracker extends FacadeHttpRpcTracker { +public class BraveHttpRpcTracker extends FacadeHttpRpcTracker { - private final BraveRpcTrackerEngine trackerEngine; + private final RpcTrackerEngine trackerEngine; - public HttpRpcTracker(BraveRpcTrackerEngine trackerEngine) { + public BraveHttpRpcTracker(RpcTrackerEngine trackerEngine) { this.trackerEngine = trackerEngine; } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java index 864f7708dc2..b58b53859e4 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java @@ -5,23 +5,23 @@ public class FacadeHttpRpcTracker implements RpcTracker { @Override - public ClientRequestInterceptor clientRequestInterceptor() { - return null; + public void trackClientRequest(ClientRequestAdapter clientRequestAdapter) { + } @Override - public ClientResponseInterceptor clientResponseInterceptor() { - return null; + public void trackClientResponse(ClientResponseAdapter clientResponseAdapter) { + } @Override - public ServerRequestInterceptor serverRequestInterceptor() { - return null; + public void trackServerRequest(ServerRequestAdapter serverRequestAdapter) { + } @Override - public ServerResponseInterceptor serverResponseInterceptor() { - return null; + public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { + } @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java index 635d323f313..37882c131a9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java @@ -16,7 +16,7 @@ public class ExtensionTest { @BeforeClass public static void before(){ URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - trackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); +// trackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); } @Test From f50b1bdad4e4f6ef940b79e2808d4c1a5f790c06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Tue, 7 Feb 2017 18:57:52 +0800 Subject: [PATCH 19/69] modify zipkin annotations --- README.md | 2 +- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- .../dubbo-container-javaconfig/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- .../support/header/HeaderExchangeClient.java | 18 ++++---- dubbo-remoting/dubbo-remoting-common/pom.xml | 4 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-common/pom.xml | 15 ------- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 3 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-api/pom.xml | 2 +- .../dubbo-test-benchmark-client/pom.xml | 2 +- .../dubbo-test-benchmark-server/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo-tool/dubbo-demo-lite-archetype/pom.xml | 2 +- .../resources/archetype-resources/pom.xml | 4 +- .../dubbo-demo-lite-api/pom.xml | 2 +- .../dubbo-demo-lite-consumer/pom.xml | 2 +- .../dubbo-demo-lite-provider/pom.xml | 2 +- dubbo-tool/dubbo-demo-lite/pom.xml | 4 +- dubbo-tracker/dubbo-tracker-api/pom.xml | 6 +-- .../alibaba/dubbo/tracker/DubboRequest.java | 43 ++++++++++++++---- .../alibaba/dubbo/tracker/DubboResponse.java | 3 ++ .../com/alibaba/dubbo/tracker/RpcRequest.java | 45 ------------------- .../com/alibaba/dubbo/tracker/RpcTracker.java | 3 +- .../alibaba/dubbo/tracker/TrackerKeys.java | 8 +++- .../exceptions/RequestIllegalException.java | 17 +++++++ dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 2 +- .../BraveDubboClientRequestAdapter.java | 16 +++++-- .../BraveDubboClientRequestInterceptor.java | 3 ++ ...DubboClientRequestResponseInterceptor.java | 4 +- .../BraveDubboClientResponseAdapter.java | 3 ++ .../BraveDubboClientResponseInterceptor.java | 3 ++ .../tracker/zipkin/BraveDubboRpcTracker.java | 1 + .../BraveDubboServerRequestAdapter.java | 3 +- ...DubboServerRequestResponseInterceptor.java | 3 ++ .../dubbo/tracker/zipkin/SamplerFactory.java | 3 ++ .../tracker/zipkin/SpanCollectorFactory.java | 5 ++- .../zipkin/filter/BraveHttpServletFilter.java | 3 ++ .../http/AttachMethodNameInterceptor.java | 3 ++ .../zipkin/http/FacadeHttpRpcTracker.java | 3 ++ .../zipkin/http/HttpSpanNameProvider.java | 3 ++ .../internal/com.alibaba.dubbo.rpc.Filter | 2 - dubbo-tracker/pom.xml | 2 +- dubbo/pom.xml | 12 ++++- hessian-lite/pom.xml | 2 +- pom.xml | 2 +- 97 files changed, 210 insertions(+), 169 deletions(-) delete mode 100644 dubbo-rpc/dubbo-rpc-common/pom.xml delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/exceptions/RequestIllegalException.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter diff --git a/README.md b/README.md index 888c4848ef7..7e8d97ae4da 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p ## 依赖 -从dubbox-2.8.4开始,所有依赖库的使用方式将和dubbo原来的一样:即如果要使用REST、Kyro、FST、Jackson等功能,需要用户自行手工添加相关的依赖。例如: +从dubbox-3.0.0开始,所有依赖库的使用方式将和dubbo原来的一样:即如果要使用REST、Kyro、FST、Jackson等功能,需要用户自行手工添加相关的依赖。例如: ### REST风格远程调用 diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index ec2a30be84a..9fc1d69e102 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index ec6af560cb0..b1f58409646 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 0d5e9f761de..c6b3817a896 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index d1f6a82c9c8..eb956be9c58 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.4 + 3.0.0 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 9732dff29d6..634517385d4 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.4 + 3.0.0 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 925195632b1..e5fb886e287 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 3cb4bda94c4..3f6856f1303 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml index 3cc3985b60e..f5419d78178 100644 --- a/dubbo-container/dubbo-container-javaconfig/pom.xml +++ b/dubbo-container/dubbo-container-javaconfig/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-javaconfig jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index 3fd180fb91a..ac41c174a2c 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index be4637f3263..b0bb8a6d5f6 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index a123294937e..5b8b849a640 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 9564561a899..e6e1e1ffb78 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.4 + 3.0.0 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index b277ac00762..8f1bc37dff0 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index a311efe313b..71721c1d142 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.4 + 3.0.0 dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 3e2427967bb..62ac9a61980 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.4 + 3.0.0 dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 1d6192f7aec..4c1ac3629de 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.4 + 3.0.0 dubbo-demo-provider war diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 4d77e14ec9a..3e99a31b968 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 8431bef623d..088b2f731af 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.4 + 3.0.0 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index d3d9cc12134..60f5c97d877 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.4 + 3.0.0 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 86e2ef12fbf..75e20543c08 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index e654f038a54..a0820ae0d0c 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.4 + 3.0.0 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 957fda3e422..2456a08ce17 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.4 + 3.0.0 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 5061c3f5606..3c8d82cea68 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 25572a8b656..26687c56d26 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.4 + 3.0.0 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 2ee2515bed9..4634d207baf 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.4 + 3.0.0 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 478d4fb67b7..d1c2a5aa67f 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.4 + 3.0.0 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 10c9fa26b49..c370a57c56b 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.4 + 3.0.0 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 774d0b73bda..3dd9592a604 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.4 + 3.0.0 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 4dedf4fc732..fa31d2ce6d2 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 3e533158c91..116ac2b531b 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 8b745f7ab5d..dab1f38cbcd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -20,14 +20,17 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; -import com.alibaba.dubbo.remoting.transport.Client; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; +import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Client; import java.net.InetSocketAddress; import java.util.ArrayList; @@ -54,9 +57,9 @@ public class HeaderExchangeClient implements ExchangeClient { private ScheduledFuture heartbeatTimer; // 心跳超时,毫秒。缺省0,不会执行心跳。 - private int heartbeat; + private final int heartbeat; - private int heartbeatTimeout; + private final int heartbeatTimeout; private final Client client; @@ -238,8 +241,7 @@ public Response proceed(Request request, int timeout) throws RemotingException { Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(chain); if (response == null) { - throw new NullPointerException("interceptor " + interceptor - + " returned null"); + throw new NullPointerException("interceptor " + interceptor + " returned null"); } return response; } diff --git a/dubbo-remoting/dubbo-remoting-common/pom.xml b/dubbo-remoting/dubbo-remoting-common/pom.xml index dbc3d3d9bf2..dacfa22efaa 100644 --- a/dubbo-remoting/dubbo-remoting-common/pom.xml +++ b/dubbo-remoting/dubbo-remoting-common/pom.xml @@ -5,7 +5,7 @@ dubbo-remoting com.alibaba - 2.8.4 + 3.0.0 4.0.0 @@ -15,7 +15,7 @@ com.alibaba dubbo-common - 2.8.4 + 3.0.0 diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index ce4b6520072..2f6e0c94e9e 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index c08a31deb77..a6f7682096f 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index b3e36966f1a..37821fc9bf4 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index cbab97d96ab..2837f08a43b 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 0dce25f736f..57774870ef7 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 47520dae0d8..7b1582604e1 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.4 + 3.0.0 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 42969026f11..439317330c5 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index e713642d38e..9dc31083291 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-common/pom.xml b/dubbo-rpc/dubbo-rpc-common/pom.xml deleted file mode 100644 index 4b620cf64ea..00000000000 --- a/dubbo-rpc/dubbo-rpc-common/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - dubbo-rpc - com.alibaba - 2.8.4 - - 4.0.0 - - dubbo-rpc-common - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index a31250d37db..5d65b682e93 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index e49c58789a0..f87537c3845 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 33e8f4d1cc2..9bf6ea32603 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index dcdda8d5345..e16cb426fa3 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 6a2af14c3c6..86af859d0bf 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 9e39b9fa31f..558c11c335e 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 11edf84ca91..1ec6d963c7f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-rest jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 84b76b9a059..8610b1a3883 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 4b5d5d075ec..3fafc6e227a 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 069d285b432..a7874cc90d3 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.4 + 3.0.0 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 29217b6e6f4..16de37c16a5 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-rpc pom @@ -40,6 +40,5 @@ dubbo-rpc-memcached dubbo-rpc-redis dubbo-rpc-rest - dubbo-rpc-common diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 4068dfc52fa..f2cece907e3 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.4 + 3.0.0 dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 6c1912bee66..17440add37b 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.4 + 3.0.0 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 5bb270f0179..ea699e98c92 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml index 79f9a30036c..f91bc0579a3 100644 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-benchmark-api jar diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml index 09aded71106..335725f7776 100644 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-benchmark-client jar diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml index 9a97c7df23f..2d68048777f 100644 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-benchmark-server jar diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 2593c9e5054..df7d33c9c03 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index d02370e64cc..b95015b61fb 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 43b4b699291..8adc3826a24 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index cbf43a6836a..873dd43c0dd 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.4 + 3.0.0 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 8ccfec26d31..01160655faf 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-test pom diff --git a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml index 844d9844dbd..dd7a4bcb83c 100644 --- a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml +++ b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-demo-lite-archetype - 2.8.4 + 3.0.0 maven-archetype dubbo-demo-lite-archetype diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml index 561a683e509..76274150c22 100644 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml +++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 ${artifactId} ${groupId} @@ -35,7 +35,7 @@ com.alibaba dubbo - 2.8.4 + 3.0.0 diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml index fb06b640479..f9b13b5f81c 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 2.8.4 + 3.0.0 dubbo-demo-lite-api jar diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml index e59c2df0903..9e5c551d6c6 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 2.8.4 + 3.0.0 dubbo-demo-lite-consumer jar diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml index ab2cead41cd..8871c05369a 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 2.8.4 + 3.0.0 dubbo-demo-lite-provider war diff --git a/dubbo-tool/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml index b43142ae691..4704caa8851 100644 --- a/dubbo-tool/dubbo-demo-lite/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo-demo-lite pom @@ -39,7 +39,7 @@ com.alibaba dubbo - 2.8.4 + 3.0.0 diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index 90694f84d2f..f39df09ad21 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -5,7 +5,7 @@ dubbo-tracker com.alibaba - 2.8.4 + 3.0.0 4.0.0 @@ -22,13 +22,13 @@ com.alibaba dubbo-remoting-common - 2.8.4 + 3.0.0 com.alibaba dubbo-rpc-api - 2.8.4 + 3.0.0 javax.servlet diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java index 826e567d3fb..e60c45ae31c 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -1,11 +1,15 @@ package com.alibaba.dubbo.tracker; -import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.tracker.exceptions.RequestIllegalException; +/** + * @author Xs. + */ public class DubboRequest { private final Request request; @@ -38,16 +42,37 @@ public String getAttachment(String key) { return invocation.getAttachment(key); } - public String address() { + public String providerAddress() { Invoker invoker = invocation.getInvoker(); - if (invoker != null) { - return invoker.getUrl().getAddress(); + if (invoker == null) { + throw new RequestIllegalException("Invoker must not be null, request { " + request + " }"); } -// if (invocation instanceof DecodeableRpcInvocation){ -// Channel channel = ((DecodeableRpcInvocation) invocation).getChannel(); -// return channel.getUrl().getAddress(); -// } - return NetUtils.getLocalHost(); + return invoker.getUrl().getAddress(); + } + + public String remoteMethod() { + String interfaceStr = invocation.getAttachment("interface"); + if (StringUtils.isEmpty(interfaceStr)) { + return invocation.getMethodName(); + } else { + StringBuilder builder = new StringBuilder(); + builder.append(interfaceStr).append("."); + builder.append(invocation.getMethodName()).append("("); + Class[] parameterTypes = invocation.getParameterTypes(); + int len = parameterTypes.length; + for (int i = 0; i < len - 1; i++) { + builder.append(parameterTypes[i].getCanonicalName()).append(" ,"); + } + if (len > 0) { + builder.append(parameterTypes[len - 1].getCanonicalName()); + } + builder.append(")"); + return builder.toString(); + } + } + + public String serviceVersion() { + return invocation.getAttachment("version"); } public Request getRequest() { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index 06a0f3a4c52..0f4a2a564f0 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -3,6 +3,9 @@ import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcResult; +/** + * @author Xs. + */ public class DubboResponse { private final Response response; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java deleted file mode 100644 index e065a22fa49..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcRequest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.alibaba.dubbo.tracker; - -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcInvocation; - -public class RpcRequest { - - private final Invoker invoker; - - private final Invocation invocation; - - public RpcRequest(Invoker invoker, Invocation invocation) { - this.invoker = invoker; - this.invocation = invocation; - } - - public Invoker getInvoker() { - return invoker; - } - - public Invocation getInvocation() { - return invocation; - } - - public boolean isTraceableRequest() { - return invocation instanceof RpcInvocation; - } - - public String getMethodName() { - return invocation.getMethodName(); - } - - public void addAttachment(String key, String value) { - ((RpcInvocation) invocation).setAttachment(key, value); - } - - public String getAttachment(String key) { - return invocation.getAttachment(key); - } - - public String providerAddress() { - return invoker.getUrl().getAddress(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index f18c72620d8..898d694b464 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -5,7 +5,6 @@ */ public interface RpcTracker { - void trackClientRequest(ClientRequestAdapter clientRequestAdapter); void trackClientResponse(ClientResponseAdapter clientResponseAdapter); @@ -15,4 +14,6 @@ public interface RpcTracker { void trackServerResponse(ServerResponseAdapter serverResponseAdapter); RpcTrackerEngine trackerEngine(); + +// boolean isStrict(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java index a53a64c80bf..ae1247e59ca 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TrackerKeys.java @@ -1,11 +1,15 @@ package com.alibaba.dubbo.tracker; /** - * @author Xs + * @author Xs. */ public class TrackerKeys { - public static final String PROVIDER_ADDR = "provider.address"; + public static final String PROVIDER_ADDRESS = "provider.address"; + + public static final String REMOTE_METHOD = "remote.method"; + + public static final String SERVICE_VERSION = "service.version"; public static final String RETURN_STATUS = "return.status"; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/exceptions/RequestIllegalException.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/exceptions/RequestIllegalException.java new file mode 100644 index 00000000000..9cace7211ca --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/exceptions/RequestIllegalException.java @@ -0,0 +1,17 @@ +package com.alibaba.dubbo.tracker.exceptions; + +public class RequestIllegalException extends RuntimeException { + + public RequestIllegalException(String message) { + super(message); + } + + public RequestIllegalException(String message, Throwable cause) { + super(message, cause); + } + + public RequestIllegalException(Throwable cause) { + super(cause); + } + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml index 84b4ec12d0b..6f70237f1c8 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml +++ b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml @@ -5,7 +5,7 @@ dubbo-tracker com.alibaba - 2.8.4 + 3.0.0 4.0.0 diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java index b34293e5868..adae935ce08 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java @@ -10,9 +10,13 @@ import com.github.kristofa.brave.SpanId; import com.twitter.zipkin.gen.Endpoint; +import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; +import java.util.List; +/** + * @author Xs + */ public class BraveDubboClientRequestAdapter implements ClientRequestAdapter, com.alibaba.dubbo.tracker.ClientRequestAdapter { private final DubboRequest request; @@ -50,8 +54,14 @@ public void addSpanIdToRequest(SpanId spanId) { @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.address()); - return Collections.singletonList(annotation); + List requestAnnotations = new ArrayList(); + KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDRESS, request.providerAddress()); + requestAnnotations.add(annotation); + annotation = KeyValueAnnotation.create(TrackerKeys.REMOTE_METHOD, request.remoteMethod()); + requestAnnotations.add(annotation); + annotation = KeyValueAnnotation.create(TrackerKeys.SERVICE_VERSION, request.serviceVersion()); + requestAnnotations.add(annotation); + return requestAnnotations; } @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java index 57f888286be..9d4054b2330 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java @@ -3,6 +3,9 @@ import com.alibaba.dubbo.tracker.ClientRequestAdapter; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; +/** + * @author Xs. + */ public class BraveDubboClientRequestInterceptor implements ClientRequestInterceptor { private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java index 1270748aa03..8ceee2b544e 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java @@ -11,7 +11,9 @@ import com.alibaba.dubbo.tracker.RpcTracker; /** - * 对dubbo协议request拦截 + * dubbo协议client request拦截器 + * + * @author Xs */ public class BraveDubboClientRequestResponseInterceptor implements Interceptor { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java index 3093696bc48..094239beaed 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java @@ -8,6 +8,9 @@ import java.util.Collection; import java.util.Collections; +/** + * @author Xs. + */ public class BraveDubboClientResponseAdapter implements ClientResponseAdapter, com.alibaba.dubbo.tracker.ClientResponseAdapter { private final DubboResponse response; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java index 733ffd7a367..03bcce668b7 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java @@ -4,6 +4,9 @@ import com.alibaba.dubbo.tracker.ClientResponseAdapter; import com.alibaba.dubbo.tracker.ClientResponseInterceptor; +/** + * @author Xs. + */ public class BraveDubboClientResponseInterceptor implements ClientResponseInterceptor { private final com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java index 4440d1687ad..3cbbf4a03ec 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java @@ -54,4 +54,5 @@ public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { public RpcTrackerEngine trackerEngine() { return trackerEngine; } + } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java index 6ec78f527e6..0816d8b9ae9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java @@ -59,8 +59,7 @@ public String getSpanName() { @Override public Collection requestAnnotations() { - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDR, request.address()); - return Collections.singletonList(annotation); + return Collections.emptyList(); } private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java index 9c4504b8889..08e9e465acd 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java @@ -9,6 +9,9 @@ import com.alibaba.dubbo.tracker.DubboResponse; import com.alibaba.dubbo.tracker.RpcTracker; +/** + * @author Xs. + */ public class BraveDubboServerRequestResponseInterceptor implements Interceptor { private final RpcTracker rpcTracker; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java index 8a00ba4404b..83a1ef2cec5 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java @@ -6,6 +6,9 @@ import com.github.kristofa.brave.CountingSampler; import com.github.kristofa.brave.Sampler; +/** + * @author Xs. + */ public class SamplerFactory { public static Sampler create(URL url) { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java index 2f7aa0d8289..37eceb730ac 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java @@ -8,11 +8,14 @@ import com.github.kristofa.brave.scribe.ScribeSpanCollector; import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; +/** + * @author Xs. + */ public class SpanCollectorFactory { private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); - public static SpanCollector create(URL url){ + public static SpanCollector create(URL url) { String collector = url.getParameter("collector", "http"); if (collector.equals("http")) { HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java index fd1bb566df9..0df05ac58f3 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java @@ -6,6 +6,9 @@ import javax.servlet.*; import java.io.IOException; +/** + * @author Xs. + */ public class BraveHttpServletFilter implements ServletFilter { private final BraveServletFilter servletFilter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java index 29db4a689f0..69fb505be0c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java @@ -8,6 +8,9 @@ import java.io.IOException; +/** + * @author Xs. + */ public class AttachMethodNameInterceptor implements Interceptor { @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java index b58b53859e4..e6a5f84a01d 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java @@ -2,6 +2,9 @@ import com.alibaba.dubbo.tracker.*; +/** + * @author Xs. + */ public class FacadeHttpRpcTracker implements RpcTracker { @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java index 62ea4e45663..03b17fcedd6 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java @@ -7,6 +7,9 @@ import com.github.kristofa.brave.http.HttpServerRequest; import com.github.kristofa.brave.http.SpanNameProvider; +/** + * @author Xs. + */ public class HttpSpanNameProvider extends RpcContextMethodNameProvider implements SpanNameProvider { @Override diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter deleted file mode 100644 index 4667af8ec8a..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter +++ /dev/null @@ -1,2 +0,0 @@ -clientTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveClientRpcTrackerFilter -serverTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveServerRpcTrackerFilter \ No newline at end of file diff --git a/dubbo-tracker/pom.xml b/dubbo-tracker/pom.xml index 3252d9b44fa..fe0cd97f9ee 100644 --- a/dubbo-tracker/pom.xml +++ b/dubbo-tracker/pom.xml @@ -5,7 +5,7 @@ dubbo-parent com.alibaba - 2.8.4 + 3.0.0 4.0.0 diff --git a/dubbo/pom.xml b/dubbo/pom.xml index ed079983e9f..d6de7ca64bd 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,15 +19,17 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 dubbo jar ${project.artifactId} The all in one project of dubbo + false + com.alibaba @@ -380,6 +382,7 @@ com.alibaba:hessian-lite com.alibaba:dubbo-common com.alibaba:dubbo-remoting-api + com.alibaba:dubbo-remoting-common com.alibaba:dubbo-remoting-netty com.alibaba:dubbo-remoting-mina com.alibaba:dubbo-remoting-grizzly @@ -574,6 +577,13 @@ META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory + + + diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index c377884a45e..468b76df2d8 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 2.8.4 + 3.0.0 hessian-lite jar diff --git a/pom.xml b/pom.xml index 584a1da368f..d7b27bb29fe 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 2.0 --> com.alibaba dubbo-parent - 2.8.4 + 3.0.0 pom ${project.artifactId} The parent project of dubbo From 085538767a53132ffaf68dc20c03c6f2bb317103 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 13 Feb 2017 23:22:12 +0800 Subject: [PATCH 20/69] add DubboRequestInterceptorBuilder,HttpRequestResponseInterceptorBuilder --- .../common/extension/ExtensionLoader.java | 1 - .../support/header/HeaderExchanger.java | 24 ++++++++------ dubbo-rpc/dubbo-rpc-hessian/pom.xml | 5 +++ .../rpc/protocol/hessian/HessianProtocol.java | 10 ++++-- .../hessian/OkHttpConnectionFactory.java | 15 ++++++--- dubbo-rpc/dubbo-rpc-http/pom.xml | 10 ++++++ .../dubbo/rpc/protocol/http/HttpProtocol.java | 11 +++++-- .../http/OkHttpInvokerRequestExecutor.java | 20 +++++++++++- dubbo-tracker/dubbo-tracker-api/pom.xml | 4 +++ .../dubbo/tracker/RpcTrackerManager.java | 7 ++-- .../tracker/{ => dubbo}/DubboRequest.java | 2 +- .../dubbo/DubboRequestInterceptorBuilder.java | 17 ++++++++++ .../DubboRequestSpanNameProvider.java | 14 +++++++- .../tracker/{ => dubbo}/DubboResponse.java | 2 +- ...HttpRequestResponseInterceptorBuilder.java | 17 ++++++++++ .../zipkin/BraveRpcTrackerFactory.java | 3 +- .../BraveDubboClientRequestAdapter.java | 6 ++-- .../BraveDubboClientRequestInterceptor.java | 2 +- ...DubboClientRequestResponseInterceptor.java | 8 ++--- .../BraveDubboClientResponseAdapter.java | 4 +-- .../BraveDubboClientResponseInterceptor.java | 2 +- .../BraveDubboRequestInterceptorBuilder.java | 30 +++++++++++++++++ .../{ => dubbo}/BraveDubboRpcTracker.java | 3 +- .../BraveDubboServerRequestAdapter.java | 7 ++-- .../BraveDubboServerRequestInterceptor.java | 2 +- ...DubboServerRequestResponseInterceptor.java | 8 ++--- .../BraveDubboServerResponseAdapter.java | 4 +-- .../BraveDubboServerResponseInterceptor.java | 2 +- .../http/AttachMethodNameInterceptor.java | 9 ++++++ ...BraveOkHttpRequestResponseInterceptor.java | 32 +++++++++++++++++++ ...HttpRequestResponseInterceptorBuilder.java | 22 +++++++++++++ .../zipkin/http/FacadeHttpRpcTracker.java | 15 +++------ .../zipkin/http/HttpSpanNameProvider.java | 9 ++++++ ...acker.dubbo.DubboRequestInterceptorBuilder | 1 + ...http.HttpRequestResponseInterceptorBuilder | 1 + 35 files changed, 267 insertions(+), 62 deletions(-) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ => dubbo}/DubboRequest.java (98%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ => dubbo}/DubboRequestSpanNameProvider.java (56%) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{ => dubbo}/DubboResponse.java (96%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboClientRequestAdapter.java (93%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboClientRequestInterceptor.java (94%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboClientRequestResponseInterceptor.java (84%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboClientResponseAdapter.java (90%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboClientResponseInterceptor.java (94%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboRpcTracker.java (94%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboServerRequestAdapter.java (92%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboServerRequestInterceptor.java (94%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboServerRequestResponseInterceptor.java (83%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboServerResponseAdapter.java (91%) rename dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/{ => dubbo}/BraveDubboServerResponseInterceptor.java (94%) create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java index 2f69cd31207..7c4a35caef9 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java @@ -774,7 +774,6 @@ private String createAdaptiveExtensionClassCode() { // 参数没有URL类型 else { String attribMethod = null; - // 找到参数的URL属性 LBL_PTS: for (int i = 0; i < pts.length; ++i) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index dc05df681b7..752a7064b61 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -22,13 +22,13 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchanger; +import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.transport.DecodeHandler; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.zipkin.BraveDubboClientRequestResponseInterceptor; -import com.alibaba.dubbo.tracker.zipkin.BraveDubboServerRequestResponseInterceptor; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboServerRequestResponseInterceptor; /** * DefaultMessenger @@ -39,11 +39,16 @@ public class HeaderExchanger implements Exchanger { public static final String NAME = "header"; + private DubboRequestInterceptorBuilder dubboRequestInterceptorBuilder; + + public void setDubboRequestInterceptorBuilder(DubboRequestInterceptorBuilder dubboRequestInterceptorBuilder) { + this.dubboRequestInterceptorBuilder = dubboRequestInterceptorBuilder; + } + public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); - RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); - if (rpcTracker != null) { - BraveDubboClientRequestResponseInterceptor interceptor = new BraveDubboClientRequestResponseInterceptor(rpcTracker, new DubboRequestSpanNameProvider()); + Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); + if (interceptor != null) { headerExchangeClient.addInterceptor(interceptor); } return headerExchangeClient; @@ -51,9 +56,8 @@ public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingE public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeHandler exchangeHandler = new HeaderExchangeHandler(handler); - RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); - if (rpcTracker != null) { - BraveDubboServerRequestResponseInterceptor interceptor = new BraveDubboServerRequestResponseInterceptor(rpcTracker, new DubboRequestSpanNameProvider()); + Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); + if (interceptor != null){ exchangeHandler.addInterceptor(interceptor); } return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(exchangeHandler))); diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index f87537c3845..adf8f9fcda6 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -58,5 +58,10 @@ dubbo-tracker-api ${project.parent.version} + + com.alibaba + dubbo-tracker-zipkin + ${project.parent.version} + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java index f6acd0d0a7b..b089cf8e8d4 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/HessianProtocol.java @@ -23,6 +23,7 @@ import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; import com.caucho.hessian.HessianException; import com.caucho.hessian.client.HessianConnectionException; import com.caucho.hessian.client.HessianProxyFactory; @@ -51,6 +52,8 @@ public class HessianProtocol extends AbstractProxyProtocol { private HttpBinder httpBinder; + private HttpRequestResponseInterceptorBuilder httpRequestResponseInterceptorBuilder; + public HessianProtocol() { super(HessianException.class); } @@ -59,12 +62,15 @@ public void setHttpBinder(HttpBinder httpBinder) { this.httpBinder = httpBinder; } + public void setHttpRequestResponseInterceptorBuilder(HttpRequestResponseInterceptorBuilder httpRequestResponseInterceptorBuilder) { + this.httpRequestResponseInterceptorBuilder = httpRequestResponseInterceptorBuilder; + } + public int getDefaultPort() { return 80; } private class HessianHandler implements HttpHandler { - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); @@ -106,7 +112,7 @@ protected T doRefer(Class serviceType, URL url) throws RpcException { if ("httpclient".equalsIgnoreCase(client)) { hessianProxyFactory.setConnectionFactory(new HttpClientConnectionFactory()); } else if ("okHttpClient".equalsIgnoreCase(client)) { - hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory(url)); + hessianProxyFactory.setConnectionFactory(new OkHttpConnectionFactory(url, httpRequestResponseInterceptorBuilder)); } else if (client != null && client.length() > 0 && !Constants.DEFAULT_HTTP_CLIENT.equals(client)) { throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index f40ee063327..372e8d58329 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -1,14 +1,14 @@ package com.alibaba.dubbo.rpc.protocol.hessian; import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; +import com.alibaba.dubbo.tracker.zipkin.http.AttachMethodNameInterceptor; import com.caucho.hessian.client.HessianConnection; import com.caucho.hessian.client.HessianConnectionFactory; import com.caucho.hessian.client.HessianProxyFactory; import okhttp3.Interceptor; import okhttp3.OkHttpClient; -import okhttp3.Response; import java.io.IOException; import java.net.URL; @@ -21,10 +21,17 @@ public class OkHttpConnectionFactory implements HessianConnectionFactory { private final OkHttpClient client; - public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url) { + public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url, HttpRequestResponseInterceptorBuilder requestResponseInterceptorBuilder) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + Interceptor interceptor = requestResponseInterceptorBuilder.build(url); + if (interceptor != null) { + builder.addInterceptor(interceptor); + if (RpcTrackerManager.getRpcTracker(url) != null) { + builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); + } + } client = builder.build(); } diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 9bf6ea32603..77b549d1e0b 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -51,5 +51,15 @@ com.squareup.okhttp3 okhttp + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + + + com.alibaba + dubbo-tracker-zipkin + ${project.parent.version} + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java index d08109b7a63..debb8342eb5 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java @@ -24,6 +24,7 @@ import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; @@ -54,6 +55,8 @@ public class HttpProtocol extends AbstractProxyProtocol { private HttpBinder httpBinder; + private HttpRequestResponseInterceptorBuilder httpRequestResponseInterceptorBuilder; + public HttpProtocol() { super(RemoteAccessException.class); } @@ -62,12 +65,15 @@ public void setHttpBinder(HttpBinder httpBinder) { this.httpBinder = httpBinder; } + public void setHttpRequestResponseInterceptorBuilder(HttpRequestResponseInterceptorBuilder httpRequestResponseInterceptorBuilder) { + this.httpRequestResponseInterceptorBuilder = httpRequestResponseInterceptorBuilder; + } + public int getDefaultPort() { return DEFAULT_PORT; } private class InternalHandler implements HttpHandler { - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); @@ -83,7 +89,6 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } } } - } protected Runnable doExport(final T impl, Class type, URL url) throws RpcException { @@ -117,7 +122,7 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc httpProxyFactoryBean.setServiceInterface(serviceType); String client = url.getParameter(Constants.CLIENT_KEY); if (StringUtils.isEmpty(client) || "okHttpClient".equals(client)) { - httpProxyFactoryBean.setHttpInvokerRequestExecutor(new OkHttpInvokerRequestExecutor(url)); + httpProxyFactoryBean.setHttpInvokerRequestExecutor(new OkHttpInvokerRequestExecutor(url, httpRequestResponseInterceptorBuilder)); } else if ("simple".equals(client)) { SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { protected void prepareConnection(HttpURLConnection con, diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java index 9c66643578b..f02a8e3d1b0 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java @@ -2,6 +2,12 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; +import com.alibaba.dubbo.tracker.zipkin.http.AttachMethodNameInterceptor; +import com.alibaba.dubbo.tracker.zipkin.http.BraveOkHttpRequestResponseInterceptor; +import com.alibaba.dubbo.tracker.zipkin.http.HttpSpanNameProvider; import okhttp3.*; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; @@ -17,10 +23,22 @@ public class OkHttpInvokerRequestExecutor extends AbstractHttpInvokerRequestExec private final OkHttpClient client; - public OkHttpInvokerRequestExecutor(URL url) { + public OkHttpInvokerRequestExecutor(URL url, HttpRequestResponseInterceptorBuilder requestResponseInterceptorBuilder) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); + RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); + if (rpcTracker != null) { + builder.addInterceptor(new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance())); + builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); + } + Interceptor interceptor = requestResponseInterceptorBuilder.build(url); + if (interceptor != null) { + builder.addInterceptor(interceptor); + if (RpcTrackerManager.getRpcTracker(url) != null) { + builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); + } + } client = builder.build(); } diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index f39df09ad21..e64e24ea107 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -34,6 +34,10 @@ javax.servlet javax.servlet-api + + com.squareup.okhttp3 + okhttp + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java index 19b6adbf30f..da87314f5e6 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java @@ -6,7 +6,7 @@ import java.util.Map; /** - * @author Xs + * @author Xs. */ public final class RpcTrackerManager { @@ -51,10 +51,11 @@ public static synchronized RpcTracker createRpcTracker(URL url) { return rpcTracker; } - public static RpcTracker getRpcTracker(String protocol) { + public static synchronized RpcTracker getRpcTracker(URL url) { + String protocol = url.getProtocol(); RpcTracker rpcTracker = rpcTrackerMap.get(RpcProtocol.valueOf(protocol)); if (rpcTracker == null) { - throw new IllegalStateException("rpcTracker should be create first!"); + rpcTracker = createRpcTracker(url); } return rpcTracker; } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java similarity index 98% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java index e60c45ae31c..ea84c46b751 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker; +package com.alibaba.dubbo.tracker.dubbo; import com.alibaba.dubbo.common.utils.StringUtils; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java new file mode 100644 index 00000000000..2e753ab4ee8 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java @@ -0,0 +1,17 @@ +package com.alibaba.dubbo.tracker.dubbo; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.message.Interceptor; + +/** + * @author Xs. + */ +@SPI("zipkin") +public interface DubboRequestInterceptorBuilder { + + @Adaptive + Interceptor build(URL url, DubboRequestSpanNameProvider spanNameProvider); + +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java similarity index 56% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java index 15d3eed7059..74608a47336 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java @@ -1,10 +1,22 @@ -package com.alibaba.dubbo.tracker; +package com.alibaba.dubbo.tracker.dubbo; + +import com.alibaba.dubbo.tracker.RpcAttachment; +import com.alibaba.dubbo.tracker.RpcContextMethodNameProvider; /** * @author Xs */ public class DubboRequestSpanNameProvider extends RpcContextMethodNameProvider { + private static final DubboRequestSpanNameProvider instance = new DubboRequestSpanNameProvider(); + + private DubboRequestSpanNameProvider() { + } + + public static DubboRequestSpanNameProvider getInstance() { + return instance; + } + public String spanName(DubboRequest dubboRequest) { String spanName = getMethodNameFromContext(); if (spanName == null) { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java similarity index 96% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java index 0f4a2a564f0..46b5eb5c9cd 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker; +package com.alibaba.dubbo.tracker.dubbo; import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcResult; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java new file mode 100644 index 00000000000..e0c772efec8 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java @@ -0,0 +1,17 @@ +package com.alibaba.dubbo.tracker.http; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; +import okhttp3.Interceptor; + +/** + * @author Xs. + */ +@SPI("zipkin") +public interface HttpRequestResponseInterceptorBuilder { + + @Adaptive + Interceptor build(URL url); + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java index 496cc5f187c..0f5c5675e23 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java @@ -2,10 +2,11 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.tracker.*; +import com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboRpcTracker; import com.alibaba.dubbo.tracker.zipkin.http.BraveHttpRpcTracker; /** - * @author Xs + * @author Xs. */ public class BraveRpcTrackerFactory implements RpcTrackerFactory { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java similarity index 93% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java index adae935ce08..fd9618bf099 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java @@ -1,7 +1,7 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.dubbo.DubboRequest; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientRequestAdapter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java similarity index 94% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java index 9d4054b2330..36ca7a6dc4d 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.ClientRequestAdapter; import com.alibaba.dubbo.tracker.ClientRequestInterceptor; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java similarity index 84% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java index 8ceee2b544e..e3f2e5ce547 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java @@ -1,13 +1,13 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.dubbo.DubboRequest; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.dubbo.DubboResponse; import com.alibaba.dubbo.tracker.RpcTracker; /** diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java similarity index 90% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java index 094239beaed..11af85fd8f7 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java @@ -1,6 +1,6 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; -import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.dubbo.DubboResponse; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.ClientResponseAdapter; import com.github.kristofa.brave.KeyValueAnnotation; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java similarity index 94% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java index 03bcce668b7..c4f71f0d558 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.ClientResponseAdapter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java new file mode 100644 index 00000000000..a7c33cf09b5 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.tracker.zipkin.dubbo; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.message.Interceptor; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; + +/** + * @author Xs. + */ +public class BraveDubboRequestInterceptorBuilder implements DubboRequestInterceptorBuilder { + + @Override + public Interceptor build(URL url, DubboRequestSpanNameProvider spanNameProvider) { + RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); + if (rpcTracker == null) { + return null; + } + if (url.getParameter(Constants.SIDE_KEY).equals("provider")) { + return new BraveDubboServerRequestResponseInterceptor(rpcTracker, spanNameProvider); + } else if (url.getParameter(Constants.SIDE_KEY).equals("consumer")) { + return new BraveDubboClientRequestResponseInterceptor(rpcTracker, spanNameProvider); + } else { + throw new IllegalArgumentException("URL doesn't contain side key, " + url); + } + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java similarity index 94% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java index 3cbbf4a03ec..3ee9726184f 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java @@ -1,6 +1,7 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.*; +import com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngine; /** * 追踪dubbo协议同步调用 diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java similarity index 92% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java index 0816d8b9ae9..583c1ff687f 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java @@ -1,9 +1,8 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.dubbo.DubboRequest; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.KeyValueAnnotation; import com.github.kristofa.brave.ServerRequestAdapter; import com.github.kristofa.brave.SpanId; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java similarity index 94% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java index 1fce714bf81..d972a607a92 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.ServerRequestAdapter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java similarity index 83% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java index 08e9e465acd..ce740ef2ff9 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java @@ -1,12 +1,12 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.DubboRequest; -import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.dubbo.DubboRequest; +import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.dubbo.DubboResponse; import com.alibaba.dubbo.tracker.RpcTracker; /** diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java similarity index 91% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java index 86d73c095d2..77e4326870b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java @@ -1,6 +1,6 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; -import com.alibaba.dubbo.tracker.DubboResponse; +import com.alibaba.dubbo.tracker.dubbo.DubboResponse; import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.KeyValueAnnotation; import com.github.kristofa.brave.ServerResponseAdapter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java similarity index 94% rename from dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java rename to dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java index 4871859c986..6848093cbdd 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveDubboServerResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.zipkin; +package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.ServerResponseAdapter; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java index 69fb505be0c..e7cfba3f2e0 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java @@ -13,6 +13,15 @@ */ public class AttachMethodNameInterceptor implements Interceptor { + private static final AttachMethodNameInterceptor instance = new AttachMethodNameInterceptor(); + + private AttachMethodNameInterceptor() { + } + + public static AttachMethodNameInterceptor getInstance() { + return instance; + } + @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java new file mode 100644 index 00000000000..5b052f4b4a3 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java @@ -0,0 +1,32 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.github.kristofa.brave.ClientRequestInterceptor; +import com.github.kristofa.brave.ClientResponseInterceptor; +import com.github.kristofa.brave.http.SpanNameProvider; +import okhttp3.Interceptor; +import okhttp3.Response; + +import java.io.IOException; + +/** + * @author Xs. + */ +public class BraveOkHttpRequestResponseInterceptor implements Interceptor { + + private Interceptor delegate; + + public BraveOkHttpRequestResponseInterceptor(RpcTracker rpcTracker, SpanNameProvider spanNameProvider) { + RpcTrackerEngine trackerEngine = rpcTracker.trackerEngine(); + delegate = new com.github.kristofa.brave.okhttp.BraveOkHttpRequestResponseInterceptor((ClientRequestInterceptor)trackerEngine.clientRequestInterceptor(), + (ClientResponseInterceptor)trackerEngine.clientResponseInterceptor(), spanNameProvider); + } + + @Override + public Response intercept(Chain chain) throws IOException { + return delegate.intercept(chain); + } + + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java new file mode 100644 index 00000000000..3d8ba8c0734 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; +import okhttp3.Interceptor; + +/** + * @author Xs. + */ +public class BraveOkHttpRequestResponseInterceptorBuilder implements HttpRequestResponseInterceptorBuilder { + + @Override + public Interceptor build(URL url) { + RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); + if (rpcTracker == null) { + return null; + } + return new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance()); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java index e6a5f84a01d..d3b61b5def4 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java @@ -5,30 +5,25 @@ /** * @author Xs. */ -public class FacadeHttpRpcTracker implements RpcTracker { +public abstract class FacadeHttpRpcTracker implements RpcTracker { @Override public void trackClientRequest(ClientRequestAdapter clientRequestAdapter) { - + // NOP } @Override public void trackClientResponse(ClientResponseAdapter clientResponseAdapter) { - + // NOP } @Override public void trackServerRequest(ServerRequestAdapter serverRequestAdapter) { - + // NOP } @Override public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { - - } - - @Override - public RpcTrackerEngine trackerEngine() { - return null; + // NOP } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java index 03b17fcedd6..631f45f601b 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java @@ -12,6 +12,15 @@ */ public class HttpSpanNameProvider extends RpcContextMethodNameProvider implements SpanNameProvider { + private static final HttpSpanNameProvider instance = new HttpSpanNameProvider(); + + private HttpSpanNameProvider() { + } + + public static HttpSpanNameProvider getInstance() { + return instance; + } + @Override public String spanName(HttpRequest request) { String spanName; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder new file mode 100644 index 00000000000..a1f918dec88 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboRequestInterceptorBuilder \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder new file mode 100644 index 00000000000..a559e923109 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.http.BraveOkHttpRequestResponseInterceptorBuilder \ No newline at end of file From 5a2d8a537666ffcd620b58ff523551ef1a1d445e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=AB=E6=A0=91=E6=9D=BE?= Date: Tue, 14 Feb 2017 18:50:26 +0800 Subject: [PATCH 21/69] add BraveServletFilter --- .../com/alibaba/dubbo/common/Constants.java | 3 +- .../dubbo/config/AbstractInterfaceConfig.java | 1 + .../alibaba/dubbo/config/ReferenceConfig.java | 5 +-- .../alibaba/dubbo/config/ServiceConfig.java | 1 + .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 8 ++-- dubbo-remoting/dubbo-remoting-http/pom.xml | 5 +++ .../remoting/http/jetty/JettyHttpBinder.java | 9 ++++- .../remoting/http/jetty/JettyHttpServer.java | 17 +++++++-- .../tracker/RpcTrackerEngineFactory.java | 2 +- .../dubbo/tracker/RpcTrackerFactory.java | 2 +- .../dubbo/DubboRequestInterceptorBuilder.java | 2 +- ...HttpRequestResponseInterceptorBuilder.java | 2 +- .../{filter => http}/ServletFilter.java | 2 +- .../tracker/http/ServletFilterBuilder.java | 13 +++++++ .../BraveDubboClientResponseAdapter.java | 10 +++-- .../BraveDubboServerResponseAdapter.java | 9 +---- .../zipkin/filter/BraveHttpServletFilter.java | 2 +- ...BraveOkHttpRequestResponseInterceptor.java | 6 +-- .../zipkin/http/BraveServletFilter.java | 37 +++++++++++++++++++ .../http/BraveServletFilterBuilder.java | 19 ++++++++++ ...ba.dubbo.tracker.http.ServletFilterBuilder | 1 + 22 files changed, 122 insertions(+), 36 deletions(-) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{filter => http}/ServletFilter.java (65%) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilterBuilder.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java create mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 09c28db60e1..1d0469d8d2b 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -593,8 +593,9 @@ public class Constants { public static final String GENERIC_SERIALIZATION_BEAN = "bean"; - //--------------------------------trace-------------------------------------------------------// + //--------------------------------tracker-------------------------------------------------------// public static final String ENABLE_TRACE_KEY = "enableTrace"; + public static final String TRACKER_KEY = "tracker"; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java index 72068a890f3..fecc29cf314 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java @@ -265,6 +265,7 @@ protected URL loadTracker() { protected void initRpcTrackerManagerIfNeeded() { URL url = loadTracker(); if (url != null) { + tracker.setProtocol(url.getProtocol() == null ? "zipkin" : url.getProtocol()); RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 7d885421b84..79329d213be 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -246,6 +246,7 @@ private void init() { } } checkApplication(); + initRpcTrackerManagerIfNeeded(); checkStubAndMock(interfaceClass); Map map = new HashMap(); Map attributes = new HashMap(); @@ -270,6 +271,7 @@ private void init() { } } map.put(Constants.INTERFACE_KEY, interfaceName); + map.put(Constants.TRACKER_KEY, tracker.getProtocol()); appendParameters(map, application); appendParameters(map, module); appendParameters(map, consumer, Constants.DEFAULT_KEY); @@ -342,9 +344,6 @@ private T createProxy(Map map) { } else { isJvmRefer = isInjvm(); } - - initRpcTrackerManagerIfNeeded(); - if (isJvmRefer) { URL url = new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0, interfaceClass.getName()).addParameters(map); invoker = refprotocol.refer(interfaceClass, url); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index 303fe65cdce..b7fb13ea52b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -345,6 +345,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); } + map.put(Constants.TRACKER_KEY, tracker.getProtocol()); appendParameters(map, application); appendParameters(map, module); appendParameters(map, provider, Constants.DEFAULT_KEY); diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 4d9d7afb4e4..beed8eb4e6a 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -9,7 +9,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 9a06c500821..024322be274 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,7 +24,7 @@ - + @@ -60,11 +60,11 @@ - - + + - diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index a6f7682096f..f505c61bbb2 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -34,6 +34,11 @@ dubbo-common ${project.parent.version} + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + org.mortbay.jetty jetty diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpBinder.java index 4741b90dcd0..b8f675e6fd6 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpBinder.java @@ -19,6 +19,7 @@ import com.alibaba.dubbo.remoting.http.HttpBinder; import com.alibaba.dubbo.remoting.http.HttpHandler; import com.alibaba.dubbo.remoting.http.HttpServer; +import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; /** * JettyHttpTransporter @@ -27,8 +28,14 @@ */ public class JettyHttpBinder implements HttpBinder { + private ServletFilterBuilder servletFilterBuilder; + + public void setServletFilterBuilder(ServletFilterBuilder servletFilterBuilder) { + this.servletFilterBuilder = servletFilterBuilder; + } + public HttpServer bind(URL url, HttpHandler handler) { - return new JettyHttpServer(url, handler); + return new JettyHttpServer(url, handler, servletFilterBuilder); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java index bd393a904c4..2cc6c7c38b0 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -24,15 +24,20 @@ import com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet; import com.alibaba.dubbo.remoting.http.servlet.ServletManager; import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; +import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; +import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.servlet.Context; +import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.ServletHandler; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.log.Log; import org.mortbay.log.StdErrLog; import org.mortbay.thread.QueuedThreadPool; +import javax.servlet.Filter; + public class JettyHttpServer extends AbstractHttpServer { private static final Logger logger = LoggerFactory.getLogger(JettyHttpServer.class); @@ -41,7 +46,7 @@ public class JettyHttpServer extends AbstractHttpServer { private final URL url; - public JettyHttpServer(URL url, final HttpHandler handler) { + public JettyHttpServer(URL url, final HttpHandler handler, ServletFilterBuilder servletFilterBuilder) { super(url, handler); this.url = url; Log.setLog(new StdErrLog()); @@ -59,17 +64,21 @@ public JettyHttpServer(URL url, final HttpHandler handler) { connector.setHost(url.getHost()); } connector.setPort(url.getPort()); - server = new Server(); server.setThreadPool(threadPool); server.addConnector(connector); + Context context = new Context(server, "/", Context.SESSIONS); ServletHandler servletHandler = new ServletHandler(); ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*"); servletHolder.setInitOrder(2); - - Context context = new Context(server, "/", Context.SESSIONS); context.setServletHandler(servletHandler); + + Filter filter = servletFilterBuilder.build(url); + if (filter != null) { + FilterHolder filterHolder = new FilterHolder(filter); + context.addFilter(filterHolder, "/*", Handler.REQUEST); + } ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); try { diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java index 29685b3d374..0c6825dd69f 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngineFactory.java @@ -10,7 +10,7 @@ @SPI("zipkin") public interface RpcTrackerEngineFactory { - @Adaptive("trackerEngine") + @Adaptive("protocol") RpcTrackerEngine createRpcTrackerEngine(URL url); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java index 2471d4033e9..be1ce7aec20 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerFactory.java @@ -10,7 +10,7 @@ @SPI("zipkin") public interface RpcTrackerFactory { - @Adaptive("tracker") + @Adaptive("protocol") RpcTracker createRpcTracker(URL url); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java index 2e753ab4ee8..05335d5f1f7 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java @@ -11,7 +11,7 @@ @SPI("zipkin") public interface DubboRequestInterceptorBuilder { - @Adaptive + @Adaptive({"tracker"}) Interceptor build(URL url, DubboRequestSpanNameProvider spanNameProvider); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java index e0c772efec8..d43777ef1b5 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/HttpRequestResponseInterceptorBuilder.java @@ -11,7 +11,7 @@ @SPI("zipkin") public interface HttpRequestResponseInterceptorBuilder { - @Adaptive + @Adaptive({"tracker"}) Interceptor build(URL url); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilter.java similarity index 65% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilter.java index d5179de7f8e..18d22ed7bc6 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/filter/ServletFilter.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilter.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.filter; +package com.alibaba.dubbo.tracker.http; import javax.servlet.Filter; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilterBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilterBuilder.java new file mode 100644 index 00000000000..59240ae9e2d --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/http/ServletFilterBuilder.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.tracker.http; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +@SPI("zipkin") +public interface ServletFilterBuilder { + + @Adaptive("tracker") + ServletFilter build(URL url); + +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java index 11af85fd8f7..e713af8722c 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java @@ -25,10 +25,12 @@ public boolean isTraceable() { @Override public Collection responseAnnotations() { - if (!response.returnOK()) { - KeyValueAnnotation statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); - return Collections.singletonList(statusAnnotation); + KeyValueAnnotation statusAnnotation; + if (response.returnOK()) { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); + } else { + statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); } - return Collections.emptyList(); + return Collections.singletonList(statusAnnotation); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java index 77e4326870b..06461665eae 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java @@ -1,7 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin.dubbo; import com.alibaba.dubbo.tracker.dubbo.DubboResponse; -import com.alibaba.dubbo.tracker.TrackerKeys; import com.github.kristofa.brave.KeyValueAnnotation; import com.github.kristofa.brave.ServerResponseAdapter; @@ -25,13 +24,7 @@ public boolean isTraceable() { @Override public Collection responseAnnotations() { - KeyValueAnnotation statusAnnotation; - if (response.returnOK()) { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); - } else { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); - } - return Collections.singletonList(statusAnnotation); + return Collections.emptyList(); } } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java index 0df05ac58f3..95f6b47d15a 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin.filter; -import com.alibaba.dubbo.tracker.filter.ServletFilter; +import com.alibaba.dubbo.tracker.http.ServletFilter; import com.github.kristofa.brave.servlet.BraveServletFilter; import javax.servlet.*; diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java index 5b052f4b4a3..444e7877018 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java @@ -19,14 +19,12 @@ public class BraveOkHttpRequestResponseInterceptor implements Interceptor { public BraveOkHttpRequestResponseInterceptor(RpcTracker rpcTracker, SpanNameProvider spanNameProvider) { RpcTrackerEngine trackerEngine = rpcTracker.trackerEngine(); - delegate = new com.github.kristofa.brave.okhttp.BraveOkHttpRequestResponseInterceptor((ClientRequestInterceptor)trackerEngine.clientRequestInterceptor(), - (ClientResponseInterceptor)trackerEngine.clientResponseInterceptor(), spanNameProvider); + delegate = new com.github.kristofa.brave.okhttp.BraveOkHttpRequestResponseInterceptor((ClientRequestInterceptor) trackerEngine.clientRequestInterceptor(), + (ClientResponseInterceptor) trackerEngine.clientResponseInterceptor(), spanNameProvider); } @Override public Response intercept(Chain chain) throws IOException { return delegate.intercept(chain); } - - } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java new file mode 100644 index 00000000000..ffc9236e85e --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java @@ -0,0 +1,37 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; +import com.alibaba.dubbo.tracker.http.ServletFilter; +import com.github.kristofa.brave.ServerRequestInterceptor; +import com.github.kristofa.brave.ServerResponseInterceptor; +import com.github.kristofa.brave.http.SpanNameProvider; + +import javax.servlet.*; +import java.io.IOException; + +public class BraveServletFilter implements ServletFilter { + + private final Filter delegate; + + public BraveServletFilter(RpcTracker rpcTracker, SpanNameProvider spanNameProvider) { + RpcTrackerEngine trackerEngine = rpcTracker.trackerEngine(); + delegate = new com.github.kristofa.brave.servlet.BraveServletFilter((ServerRequestInterceptor) trackerEngine.serverRequestInterceptor(), + (ServerResponseInterceptor) trackerEngine.serverResponseInterceptor(), spanNameProvider); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + delegate.init(filterConfig); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + delegate.doFilter(request, response, chain); + } + + @Override + public void destroy() { + delegate.destroy(); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java new file mode 100644 index 00000000000..d0314870e90 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.tracker.zipkin.http; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.tracker.RpcTracker; +import com.alibaba.dubbo.tracker.RpcTrackerManager; +import com.alibaba.dubbo.tracker.http.ServletFilter; +import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; + +public class BraveServletFilterBuilder implements ServletFilterBuilder { + + @Override + public ServletFilter build(URL url) { + RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); + if (rpcTracker == null) { + return null; + } + return new BraveServletFilter(rpcTracker, HttpSpanNameProvider.getInstance()); + } +} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder new file mode 100644 index 00000000000..e9a3ceb4b66 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder @@ -0,0 +1 @@ +zipkin=com.alibaba.dubbo.tracker.zipkin.http.BraveServletFilterBuilder \ No newline at end of file From df19474b76c24cebadde510b836de4ed6118ec73 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 14 Feb 2017 23:44:15 +0800 Subject: [PATCH 22/69] modify README.md, change collector to transport in TrackerConfig and dubbo.xsd --- README.md | 202 ++++-------------- .../alibaba/dubbo/config/TrackerConfig.java | 10 +- .../alibaba/dubbo/config/TrackConfigTest.java | 2 +- .../src/main/resources/META-INF/dubbo.xsd | 4 +- .../META-INF/spring/dubbo-demo-consumer.xml | 3 +- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../tracker/zipkin/SpanCollectorFactory.java | 2 +- 7 files changed, 53 insertions(+), 172 deletions(-) diff --git a/README.md b/README.md index 7e8d97ae4da..3ae22afb37b 100644 --- a/README.md +++ b/README.md @@ -1,202 +1,84 @@ -Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know what dubbox is :) +# dubbo3 -Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It's been used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. +dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) -## 主要贡献者 +## dubbo3修改和增加的功能 -* 沈理 [当当网](http://www.dangdang.com/) shenli@dangdang.com -* 王宇轩 [当当网](http://www.dangdang.com/) wangyuxuan@dangdang.com -* 马金凯 [韩都衣舍](http://www.handu.com/) majinkai@handu.com -* Dylan 独立开发者 dinguangx@163.com -* Kangfoo 独立开发者 +* 实现基于dubbo、hessian、http协议的分布式服务链路监控和追踪功能,可以将服务链路信息报告给[Zipkin](http://zipkin.io/),Zipkin的用户界面可以浏览全链路每一个服务的延迟 -有技术问题请移步此处讨论 https://github.com/dangdangdotcom/dubbox/issues +* 修改了ExchangeChannel中基于dubbo协议同步调用的接口,便于添加Interceptor拦截request记录服务调用信息 -## Dubbox当前的主要功能 +* 添加了okhttp3支持hessian协议、http协议,目前对这两种协议的拦截基于OkhttpClient的Interceptor机制 -* **支持REST风格远程调用(HTTP + JSON/XML)**:基于非常成熟的JBoss [RestEasy](http://resteasy.jboss.org/)框架,在dubbo中实现了REST风格(HTTP + JSON/XML)的远程调用,以显著简化企业内部的跨语言交互,同时显著简化企业对外的Open API、无线API甚至AJAX服务端等等的开发。事实上,这个REST调用也使得Dubbo可以对当今特别流行的“微服务”架构提供基础性支持。 另外,REST调用也达到了比较高的性能,在基准测试下,HTTP + JSON与Dubbo 2.x默认的RPC协议(即TCP + Hessian2二进制序列化)之间只有1.5倍左右的差距,详见文档中的基准测试报告。 +## 如何开启tracker -* **支持基于Kryo和FST的Java高效序列化实现**:基于当今比较知名的[Kryo](https://github.com/EsotericSoftware/kryo)和[FST](https://github.com/RuedigerMoeller/fast-serialization)高性能序列化库,为Dubbo默认的RPC协议添加新的序列化实现,并优化调整了其序列化体系,比较显著的提高了Dubbo RPC的性能,详见文档中的基准测试报告。 +目前tracker的使用方式只支持基于spring xml配置 -* **支持基于Jackson的JSON序列化**:基于业界应用最广泛的[Jackson](http://jackson.codehaus.org/)序列化库,为Dubbo默认的RPC协议添加新的JSON序列化实现。 + -* **支持基于嵌入式Tomcat的HTTP remoting体系**:基于嵌入式tomcat实现dubbo的HTTP remoting体系(即dubbo-remoting-http),用以逐步取代Dubbo中旧版本的嵌入式Jetty,可以显著的提高REST等的远程调用性能,并将Servlet API的支持从2.5升级到3.1。(注:除了REST,dubbo中的WebServices、Hessian、HTTP Invoker等协议都基于这个HTTP remoting体系)。 - -* **升级Spring**:将dubbo中Spring由2.x升级到目前最常用的3.x版本,减少版本冲突带来的麻烦。 - -* **升级ZooKeeper客户端**:将dubbo中的zookeeper客户端升级到最新的版本,以修正老版本中包含的bug。 - -* **支持完全基于Java代码的Dubbo配置**:基于Spring的Java Config,实现完全无XML的纯Java代码方式来配置dubbo - -* **调整Demo应用**:暂时将dubbo的demo应用调整并改写以主要演示REST功能、Dubbo协议的新序列化方式、基于Java代码的Spring配置等等。 - -* **修正了dubbo的bug** 包括配置、序列化、管理界面等等的bug。 - -**注:dubbox和dubbo 2.x是兼容的,没有改变dubbo的任何已有的功能和配置方式(除了升级了spring之类的版本)** - -## 文档资料 - -[在Dubbo中开发REST风格的远程调用(RESTful Remoting)](http://dangdangdotcom.github.io/dubbox/rest.html) - -[在Dubbo中使用高效的Java序列化(Kryo和FST)](http://dangdangdotcom.github.io/dubbox/serialization.html) - -[使用JavaConfig方式配置dubbox](http://dangdangdotcom.github.io/dubbox/java-config.html) - -[Dubbo Jackson序列化使用说明](http://dangdangdotcom.github.io/dubbox/jackson.html) - -[Demo应用简单运行指南](http://dangdangdotcom.github.io/dubbox/demo.html) - -[Dubbox@InfoQ](http://www.infoq.com/cn/news/2014/10/dubbox-open-source) - -[Dubbox Wiki](https://github.com/dangdangdotcom/dubbox/wiki) (由社区志愿者自由编辑的) - -## 版本 - -详见:https://github.com/dangdangdotcom/dubbox/releases - -* **dubbox-2.8.0**:主要支持REST风格远程调用、支持Kryo和FST序列化、升级了Spring和Zookeeper客户端、调整了demo应用等等 -* **dubbox-2.8.1**:主要支持基于嵌入式tomcat的http-remoting,优化了REST客户端性能,在REST中支持限制服务端接纳的最大HTTP连接数等等 -* **dubbox-2.8.2**: - * 支持REST中的HTTP logging,包括HTTP header的字段和HTTP body中的消息体,方便调试、日志纪录等等 - * 提供辅助类便于REST的中文处理 - * 改变使用`@Reference` annotation配置时的异常处理方式,即当用annotation配置时,过去dubbo在启动期间不抛出依赖服务找不到的异常,而是在具体调用时抛出NPE,这与用XML配置时的行为不一致。 - * 较大的充实了Dubbo REST的文档 -* **dubbox-2.8.3**: - * 在REST中支持dubbo统一的方式用bean validation annotation作参数校验(沈理) - * 在RpcContext上支持获取底层协议的Request/Response(沈理) - * 支持采用Spring的Java Config方式配置dubbo(马金凯) - * 在Dubbo协议中支持基于Jackson的json序列化(Dylan) - * 在Spring AOP代理过的对象上支持dubbo annotation配置(Dylan) - * 修正Dubbo管理界面中没有consumer时出现空指针异常(马金凯) - * 修正@Reference annotation中protocol设置不起作用的bug(沈理) - * 修正@Reference annotation放在setter方法上即会出错的bug(Dylan) +address: zipkin transport address +collector(transport): http\kafka\scribe +sampler:采样器 +samplerate:采样率 +flushinterval:数据刷新频率 ## 依赖 -从dubbox-3.0.0开始,所有依赖库的使用方式将和dubbo原来的一样:即如果要使用REST、Kyro、FST、Jackson等功能,需要用户自行手工添加相关的依赖。例如: - -### REST风格远程调用 +服务链路追踪主要基于Zipkin的[brave](https://github.com/openzipkin/brave) ```xml - org.jboss.resteasy - resteasy-jaxrs - 3.0.7.Final - - - org.jboss.resteasy - resteasy-client - 3.0.7.Final - - - javax.validation - validation-api - 1.0.0.GA + com.squareup.okhttp3 + okhttp + 3.2.0 - - org.jboss.resteasy - resteasy-jackson-provider - 3.0.7.Final + io.zipkin.brave + brave-core + 3.9.0 - - org.jboss.resteasy - resteasy-jaxb-provider - 3.0.7.Final + io.zipkin.brave + brave-http + 3.9.0 - - org.jboss.resteasy - resteasy-netty - 3.0.7.Final + io.zipkin.brave + brave-web-servlet-filter + 3.9.0 - - org.jboss.resteasy - resteasy-jdk-http - 3.0.7.Final + io.zipkin.brave + brave-okhttp + 3.9.0 - - - org.apache.tomcat.embed - tomcat-embed-core - 8.0.11 - - org.apache.tomcat.embed - tomcat-embed-logging-juli - 8.0.11 + io.zipkin.brave + brave-spancollector-http + 3.9.0 -``` - -### Kyro序列化 -```xml - com.esotericsoftware.kryo - kryo - 2.24.0 + io.zipkin.brave + brave-spancollector-kafka + 3.9.0 - - de.javakaffee - kryo-serializers - 0.26 - -``` -### FST序列化 - -```xml - de.ruedigermoeller - fst - 1.55 + io.zipkin.brave + brave-spancollector-scribe + 3.9.0 -``` -### Jackson序列化 - -```xml - - com.fasterxml.jackson.core - jackson-core - 2.3.3 - - com.fasterxml.jackson.core - jackson-databind - 2.3.3 + com.google.auto.value + auto-value + 1.3 ``` - -## FAQ(暂存) - -### Dubbox需要什么版本的JDK? - -目前最好在JDK 1.7以上运行 - -### Dubbo REST的服务能和Dubbo注册中心、监控中心集成吗? - -可以的,而且是自动集成的,也就是你在dubbo中开发的所有REST服务都会自动注册到服务册中心和监控中心,可以通过它们做管理。 - -但是,只有当REST的消费端也是基于dubbo的时候,注册中心中的许多服务治理操作才能完全起作用。而如果消费端是非dubbo的,自然不受注册中心管理,所以其中很多操作是不会对消费端起作用的。 - -### Dubbo REST中如何实现负载均衡和容错(failover)? - -如果dubbo REST的消费端也是dubbo的,则Dubbo REST和其他dubbo远程调用协议基本完全一样,由dubbo框架透明的在消费端做load balance、failover等等。 - -如果dubbo REST的消费端是非dubbo的,甚至是非java的,则最好配置服务提供端的软负载均衡机制,目前可考虑用LVS、HAProxy、 Nginx等等对HTTP请求做负载均衡。 - -### JAX-RS中重载的方法能够映射到同一URL地址吗? - -http://stackoverflow.com/questions/17196766/can-resteasy-choose-method-based-on-query-params - -### JAX-RS中作POST的方法能够接收多个参数吗? -http://stackoverflow.com/questions/5553218/jax-rs-post-multiple-objects diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java index d53a8cffedd..faaf7c3dbab 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java @@ -12,7 +12,7 @@ public class TrackerConfig extends AbstractConfig { private Integer port; - private String collector; + private String transport; private String sampler; @@ -64,12 +64,12 @@ public void setPort(Integer port) { this.port = port; } - public String getCollector() { - return collector; + public String getTransport() { + return transport; } - public void setCollector(String collector) { - this.collector = collector; + public void setTransport(String transport) { + this.transport = transport; } public String getSampler() { diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java index c9e4e0a9aaa..e421096462b 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java @@ -10,7 +10,7 @@ public void test_trackConfig(){ trackerConfig.setProtocol("zipkin"); trackerConfig.setAddress("localhost:9411"); trackerConfig.setApplication("test"); - trackerConfig.setCollector("kafka"); + trackerConfig.setTransport("kafka"); trackerConfig.setSampler("counting"); trackerConfig.setSamplerate(0.1f); trackerConfig.setFlushinterval(2); diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index a1c12ddc1e7..1680899406c 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -566,9 +566,9 @@ - + - + diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index beed8eb4e6a..1784ce09f71 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -9,7 +9,7 @@ - + @@ -19,5 +19,4 @@ - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 024322be274..41d7808623c 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,7 +24,7 @@ - + diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java index 37eceb730ac..3a67c069649 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java @@ -16,7 +16,7 @@ public class SpanCollectorFactory { private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); public static SpanCollector create(URL url) { - String collector = url.getParameter("collector", "http"); + String collector = url.getParameter("transport", "http"); if (collector.equals("http")) { HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); From 50afcb2194b6dafef22c8314ab89262e6fc202b8 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 14 Feb 2017 23:48:09 +0800 Subject: [PATCH 23/69] modify README.md --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3ae22afb37b..7d594a5ab46 100644 --- a/README.md +++ b/README.md @@ -12,15 +12,17 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 ## 如何开启tracker -目前tracker的使用方式只支持基于spring xml配置 +目前tracker的使用方式只支持spring xml配置,如下 +```xml +``` -address: zipkin transport address -collector(transport): http\kafka\scribe -sampler:采样器 -samplerate:采样率 -flushinterval:数据刷新频率 +* address: zipkin transport address +* collector(transport): http\kafka\scribe +* sampler:采样器 +* samplerate:采样率 +* flushinterval:数据刷新频率 ## 依赖 From 1e7613d21e915b3cbea6d939d51e0b6672a99068 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 15 Feb 2017 20:11:34 +0800 Subject: [PATCH 24/69] =?UTF-8?q?=E5=86=85=E7=BD=AEtomcat=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E6=B7=BB=E5=8A=A0Filter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/Constants.java | 3 +- .../http/tomcat/TomcatHttpBinder.java | 17 ++++-- .../http/tomcat/TomcatHttpServer.java | 23 ++++++-- .../tracker/zipkin/BraveRpcTrackerEngine.java | 57 ++++++++++++++++++- .../dubbo/tracker/zipkin/SamplerFactory.java | 32 ----------- .../tracker/zipkin/SpanCollectorFactory.java | 34 ----------- 6 files changed, 86 insertions(+), 80 deletions(-) delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 1d0469d8d2b..07f9c188acd 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -595,7 +595,6 @@ public class Constants { //--------------------------------tracker-------------------------------------------------------// - public static final String ENABLE_TRACE_KEY = "enableTrace"; - public static final String TRACKER_KEY = "tracker"; + } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java index fd6a05eb36c..ca4220d94d5 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,14 +19,21 @@ import com.alibaba.dubbo.remoting.http.HttpBinder; import com.alibaba.dubbo.remoting.http.HttpHandler; import com.alibaba.dubbo.remoting.http.HttpServer; +import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; /** * @author lishen */ public class TomcatHttpBinder implements HttpBinder { + private ServletFilterBuilder servletFilterBuilder; + + public void setServletFilterBuilder(ServletFilterBuilder servletFilterBuilder) { + this.servletFilterBuilder = servletFilterBuilder; + } + public HttpServer bind(URL url, HttpHandler handler) { - return new TomcatHttpServer(url, handler); + return new TomcatHttpServer(url, handler, servletFilterBuilder); } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java index bd03ce7f312..fde3b6648b6 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -24,10 +24,14 @@ import com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet; import com.alibaba.dubbo.remoting.http.servlet.ServletManager; import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; +import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.startup.Tomcat; +import org.apache.tomcat.util.descriptor.web.FilterDef; +import org.apache.tomcat.util.descriptor.web.FilterMap; +import javax.servlet.Filter; import java.io.File; @@ -42,7 +46,7 @@ public class TomcatHttpServer extends AbstractHttpServer { private final URL url; - public TomcatHttpServer(URL url, final HttpHandler handler) { + public TomcatHttpServer(URL url, final HttpHandler handler, ServletFilterBuilder servletFilterBuilder) { super(url, handler); this.url = url; DispatcherServlet.addHttpHandler(url.getPort(), handler); @@ -52,19 +56,28 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { tomcat.setPort(url.getPort()); tomcat.getConnector().setProperty( "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); - tomcat.getConnector().setProperty( "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1))); - tomcat.getConnector().setProperty("URIEncoding", "UTF-8"); tomcat.getConnector().setProperty("connectionTimeout", "60000"); - tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1"); tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol"); - Context context = tomcat.addContext("/", baseDir); Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); context.addServletMapping("/*", "dispatcher"); + Filter filter = servletFilterBuilder.build(url); + if (filter != null) { + FilterDef filterDef = new FilterDef(); + filterDef.setFilter(filter); + filterDef.setFilterName("servletFilter"); + context.addFilterDef(filterDef); + + FilterMap filterMap = new FilterMap(); + filterMap.addServletName("dispatcher"); + filterMap.setFilterName("servletFilter"); + filterMap.addURLPattern("*"); + context.addFilterMap(filterMap); + } ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); try { tomcat.start(); diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java index 4b20be5af7e..77554ba3324 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java @@ -1,8 +1,15 @@ package com.alibaba.dubbo.tracker.zipkin; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.tracker.RpcTrackerEngine; import com.github.kristofa.brave.*; +import com.github.kristofa.brave.http.HttpSpanCollector; +import com.github.kristofa.brave.kafka.KafkaSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollector; +import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; + +import java.net.URLDecoder; /** * 基于Zipkin的RpcTracker引擎 @@ -11,15 +18,61 @@ */ public class BraveRpcTrackerEngine implements RpcTrackerEngine { + private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); + private final Brave brave; BraveRpcTrackerEngine(URL url) { Brave.Builder builder = new Brave.Builder(url.getParameter("application")); - builder.spanCollector(SpanCollectorFactory.create(url)); - builder.traceSampler(SamplerFactory.create(url)); + builder.spanCollector(createSpanCollector(url)); + builder.traceSampler(createSampler(url)); brave = builder.build(); } + private SpanCollector createSpanCollector(URL url) { + String transport = url.getParameter("transport", "http"); + Integer flushInterval = url.getParameter("flushiterval", 1); + if (transport.equals("http")) { + HttpSpanCollector.Config.Builder builder = HttpSpanCollector.Config.builder(); + builder.flushInterval(flushInterval); + String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); + return HttpSpanCollector.create(baseUrl, builder.build(), DEFAULT_HANDLER); + } else if (transport.equals("kafka")) { + String address = url.getParameter("address"); + if (StringUtils.isEmpty(address)) { + throw new IllegalArgumentException("transport address must not be null"); + } + KafkaSpanCollector.Config.Builder builder = KafkaSpanCollector.Config.builder(address); + builder.flushInterval(flushInterval); + return KafkaSpanCollector.create(builder.build(), DEFAULT_HANDLER); + } else if (transport.equals("scribe")) { + ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); + params.setMetricsHandler(DEFAULT_HANDLER); + return new ScribeSpanCollector(url.getHost(), url.getPort(), params); + } else { + throw new IllegalArgumentException("unknown transport type, transport: " + transport); + } + } + + private Sampler createSampler(URL url) { + String sampler = url.getParameter("sampler"); + if (StringUtils.isEmpty(sampler)) { + return Sampler.ALWAYS_SAMPLE; + } else { + String rate = url.getParameter("rate"); + if (StringUtils.isEmpty(rate)) { + return Sampler.ALWAYS_SAMPLE; + } + if (sampler.equals("counting")) { + return CountingSampler.create(Float.valueOf(rate)); + } else if (sampler.equals("boundary")) { + return BoundarySampler.create(Float.valueOf(rate)); + } else { + throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); + } + } + } + public static BraveRpcTrackerEngine create(URL url) { return new BraveRpcTrackerEngine(url); } diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java deleted file mode 100644 index 83a1ef2cec5..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SamplerFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.github.kristofa.brave.BoundarySampler; -import com.github.kristofa.brave.CountingSampler; -import com.github.kristofa.brave.Sampler; - -/** - * @author Xs. - */ -public class SamplerFactory { - - public static Sampler create(URL url) { - String sampler = url.getParameter("sampler"); - if (StringUtils.isEmpty(sampler)) { - return Sampler.ALWAYS_SAMPLE; - } else { - String rate = url.getParameter("rate"); - if (StringUtils.isEmpty(rate)) { - return Sampler.ALWAYS_SAMPLE; - } - if (sampler.equals("counting")) { - return CountingSampler.create(Float.valueOf(rate)); - } else if (sampler.equals("boundary")) { - return BoundarySampler.create(Float.valueOf(rate)); - } else { - throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); - } - } - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java deleted file mode 100644 index 3a67c069649..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/SpanCollectorFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.github.kristofa.brave.SpanCollector; -import com.github.kristofa.brave.SpanCollectorMetricsHandler; -import com.github.kristofa.brave.http.HttpSpanCollector; -import com.github.kristofa.brave.kafka.KafkaSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; - -/** - * @author Xs. - */ -public class SpanCollectorFactory { - - private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); - - public static SpanCollector create(URL url) { - String collector = url.getParameter("transport", "http"); - if (collector.equals("http")) { - HttpSpanCollector.Config config = HttpSpanCollector.Config.builder().build(); - String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); - return HttpSpanCollector.create(baseUrl, config, DEFAULT_HANDLER); - } else if (collector.equals("kafka")) { - return KafkaSpanCollector.create(url.getHost() + ":" + url.getPort(), DEFAULT_HANDLER); - } else if (collector.equals("scribe")) { - ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); - params.setMetricsHandler(DEFAULT_HANDLER); - return new ScribeSpanCollector(url.getHost(), url.getPort(), params); - } else { - throw new IllegalArgumentException("unknown collector type, collector: " + collector); - } - } -} From 9c7f031f7eff51162c10a9677093cfbdada7ea1e Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 18 Feb 2017 00:26:52 +0800 Subject: [PATCH 25/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86consumer,provi?= =?UTF-8?q?der=E6=B2=A1=E6=9C=89=E9=85=8D=E7=BD=AEtracker=E5=BC=95?= =?UTF-8?q?=E8=B5=B7=E7=9A=84=E7=A9=BA=E6=8C=87=E9=92=88bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/config/ReferenceConfig.java | 4 +++- .../java/com/alibaba/dubbo/config/ServiceConfig.java | 6 ++++-- .../java/com/alibaba/dubbo/config/TrackerConfig.java | 3 --- .../tracker/zipkin/http/BraveServletFilter.java | 12 +++++++++++- pom.xml | 1 + 5 files changed, 19 insertions(+), 7 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 79329d213be..a801279685b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -256,6 +256,9 @@ private void init() { if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); } + if (tracker != null) { + map.put(Constants.TRACKER_KEY, tracker.getProtocol()); + } if (!isGeneric()) { String revision = Version.getVersion(interfaceClass, version); if (revision != null && revision.length() > 0) { @@ -271,7 +274,6 @@ private void init() { } } map.put(Constants.INTERFACE_KEY, interfaceName); - map.put(Constants.TRACKER_KEY, tracker.getProtocol()); appendParameters(map, application); appendParameters(map, module); appendParameters(map, consumer, Constants.DEFAULT_KEY); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index b7fb13ea52b..be40811acd1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -345,7 +345,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (ConfigUtils.getPid() > 0) { map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); } - map.put(Constants.TRACKER_KEY, tracker.getProtocol()); + if (tracker != null) { + map.put(Constants.TRACKER_KEY, tracker.getProtocol()); + } appendParameters(map, application); appendParameters(map, module); appendParameters(map, provider, Constants.DEFAULT_KEY); @@ -691,7 +693,7 @@ private static ProtocolConfig convertProviderToProtocol(ProviderConfig provider) } @Deprecated - private static final ProviderConfig convertProtocolToProvider(ProtocolConfig protocol) { + private static ProviderConfig convertProtocolToProvider(ProtocolConfig protocol) { ProviderConfig provider = new ProviderConfig(); provider.setProtocol(protocol); provider.setServer(protocol.getServer()); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java index faaf7c3dbab..5ce36d3f71c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java @@ -24,9 +24,6 @@ public class TrackerConfig extends AbstractConfig { private String version; - /** - * 自定义参数 - */ private Map parameters; public TrackerConfig() { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java index ffc9236e85e..cf541ea7a2d 100644 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java +++ b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.tracker.zipkin.http; +import com.alibaba.dubbo.tracker.RpcAttachment; import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.RpcTrackerEngine; import com.alibaba.dubbo.tracker.http.ServletFilter; @@ -8,6 +9,7 @@ import com.github.kristofa.brave.http.SpanNameProvider; import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class BraveServletFilter implements ServletFilter { @@ -27,7 +29,15 @@ public void init(FilterConfig filterConfig) throws ServletException { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - delegate.doFilter(request, response, chain); + if (isSampleNeeded(request)) { + delegate.doFilter(request, response, chain); + } else { + chain.doFilter(request, response); + } + } + + private boolean isSampleNeeded(ServletRequest request) { + return ((HttpServletRequest) request).getHeader(RpcAttachment.Sampled.getName()) != null; } @Override diff --git a/pom.xml b/pom.xml index d7b27bb29fe..912dd1cf3da 100644 --- a/pom.xml +++ b/pom.xml @@ -77,6 +77,7 @@ hessian-lite dubbo-tracker + test From 4247d1751cd1a41b5fd078a4aef3bfd7d01b84be Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 22 Feb 2017 06:56:39 +0800 Subject: [PATCH 26/69] =?UTF-8?q?1.=E4=BF=AE=E6=94=B9TrackerConfig?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0ref=E5=B1=9E=E6=80=A7=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E5=BC=95=E7=94=A8=E5=A4=96=E9=83=A8Brave=202.?= =?UTF-8?q?=E5=88=86=E7=A6=BBdubbo-tracker-zipkin=E5=88=B0brave-dubbo?= =?UTF-8?q?=E4=B8=AD=EF=BC=8C=E4=B9=8B=E5=90=8E=E4=BC=9A=E8=BF=9B=E4=B8=80?= =?UTF-8?q?=E6=AD=A5=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 20 +++- .../alibaba/dubbo/common/utils/UrlUtils.java | 10 -- .../alibaba/dubbo/config/AbstractConfig.java | 6 +- .../dubbo/config/AbstractInterfaceConfig.java | 42 ++++---- .../dubbo/config/AbstractMethodConfig.java | 36 +++---- .../dubbo/config/ApplicationConfig.java | 6 +- ...onfig.java => RpcTrackerEngineConfig.java} | 14 ++- .../alibaba/dubbo/config/ServiceConfig.java | 1 + .../alibaba/dubbo/config/TrackConfigTest.java | 18 ++-- .../dubbo/config/spring/ReferenceBean.java | 14 +-- .../dubbo/config/spring/ServiceBean.java | 14 +-- .../spring/schema/DubboNamespaceHandler.java | 3 +- .../src/main/resources/META-INF/dubbo.xsd | 5 + .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 15 ++- dubbo-remoting/dubbo-remoting-api/pom.xml | 10 +- .../support/header/HeaderExchanger.java | 5 +- .../dubbo/rpc/filter/ContextFilter.java | 1 - .../dubbo/rpc/filter/TimeoutFilter.java | 17 ++-- .../alibaba/dubbo/rpc/filter/TokenFilter.java | 40 ++++---- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 95 +++++++++--------- .../hessian/OkHttpConnectionFactory.java | 5 - dubbo-rpc/dubbo-rpc-http/pom.xml | 91 ++++++++--------- .../http/OkHttpInvokerRequestExecutor.java | 25 +++-- dubbo-tracker/dubbo-tracker-api/pom.xml | 2 + .../dubbo/tracker/RpcTrackerManager.java | 4 + dubbo-tracker/dubbo-tracker-zipkin/pom.xml | 73 -------------- .../tracker/zipkin/BraveRpcTrackerEngine.java | 99 ------------------- .../zipkin/BraveRpcTrackerEngineFactory.java | 16 --- .../zipkin/BraveRpcTrackerFactory.java | 28 ------ .../LoggingSpanCollectorMetricsHandler.java | 23 ----- .../dubbo/BraveDubboClientRequestAdapter.java | 71 ------------- .../BraveDubboClientRequestInterceptor.java | 23 ----- ...DubboClientRequestResponseInterceptor.java | 37 ------- .../BraveDubboClientResponseAdapter.java | 36 ------- .../BraveDubboClientResponseInterceptor.java | 25 ----- .../BraveDubboRequestInterceptorBuilder.java | 30 ------ .../zipkin/dubbo/BraveDubboRpcTracker.java | 59 ----------- .../dubbo/BraveDubboServerRequestAdapter.java | 70 ------------- .../BraveDubboServerRequestInterceptor.java | 25 ----- ...DubboServerRequestResponseInterceptor.java | 34 ------- .../BraveDubboServerResponseAdapter.java | 30 ------ .../BraveDubboServerResponseInterceptor.java | 25 ----- .../zipkin/filter/BraveHttpServletFilter.java | 34 ------- .../http/AttachMethodNameInterceptor.java | 32 ------ .../zipkin/http/BraveHttpRpcTracker.java | 21 ---- ...BraveOkHttpRequestResponseInterceptor.java | 30 ------ ...HttpRequestResponseInterceptorBuilder.java | 22 ----- .../zipkin/http/BraveServletFilter.java | 47 --------- .../http/BraveServletFilterBuilder.java | 19 ---- .../zipkin/http/FacadeHttpRpcTracker.java | 29 ------ .../zipkin/http/HttpSpanNameProvider.java | 42 -------- ...baba.dubbo.tracker.RpcTrackerEngineFactory | 1 - ...om.alibaba.dubbo.tracker.RpcTrackerFactory | 1 - ...acker.dubbo.DubboRequestInterceptorBuilder | 1 - ...http.HttpRequestResponseInterceptorBuilder | 1 - ...ba.dubbo.tracker.http.ServletFilterBuilder | 1 - .../tracker/zipkin/test/ExtensionTest.java | 42 -------- .../internal/com.alibaba.dubbo.rpc.Filter | 2 - ...baba.dubbo.tracker.RpcTrackerEngineFactory | 1 - ...om.alibaba.dubbo.tracker.RpcTrackerFactory | 1 - dubbo-tracker/pom.xml | 2 +- dubbo/pom.xml | 12 +-- pom.xml | 18 ++++ 64 files changed, 282 insertions(+), 1282 deletions(-) rename dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/{TrackerConfig.java => RpcTrackerEngineConfig.java} (90%) delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/pom.xml delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory delete mode 100644 dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory diff --git a/README.md b/README.md index 7d594a5ab46..55c803936c7 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 ## 如何开启tracker -目前tracker的使用方式只支持spring xml配置,如下 +目前tracker的使用方式只支持spring xml配置,目前有如下两种方式 +方式一: ```xml ``` @@ -24,6 +25,23 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 * samplerate:采样率 * flushinterval:数据刷新频率 +方式二: +使用方式一在dubbo内部创建tracker对象,因为目前只支持zipkin,tracker对应Brave,没有办法同其他系统,比如数据库的监控结合起来,推荐使用下面的方式 +配置 +```xml + + + + + + + + + + + +```xml + ## 依赖 服务链路追踪主要基于Zipkin的[brave](https://github.com/openzipkin/brave) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java index 35b562cfc32..68d81e4cbd1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -81,10 +81,6 @@ public static URL parseURL(String address, Map defaults) { changed = true; password = defaultPassword; } - /*if (u.isAnyHost() || u.isLocalHost()) { - changed = true; - host = NetUtils.getLocalHost(); - }*/ if (port <= 0) { if (defaultPort > 0) { changed = true; @@ -146,8 +142,6 @@ public static Map> convertRegister(Map params = StringUtils.parseQueryString(serviceQuery); String group = params.get("group"); String version = params.get("version"); - //params.remove("group"); - //params.remove("version"); String name = serviceName; if (group != null && group.length() > 0) { name = group + "/" + name; @@ -178,8 +172,6 @@ public static Map convertSubscribe(Map subscribe Map params = StringUtils.parseQueryString(serviceQuery); String group = params.get("group"); String version = params.get("version"); - //params.remove("group"); - //params.remove("version"); String name = serviceName; if (group != null && group.length() > 0) { name = group + "/" + name; @@ -270,8 +262,6 @@ public static Map> revertNotify(Map params = StringUtils.parseQueryString(query); String group = params.get("group"); String version = params.get("version"); - // params.remove("group"); - // params.remove("version"); String name = serviceName; if (group != null && group.length() > 0) { name = group + "/" + name; diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 96dce69fb35..281b0d29cd6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -251,11 +251,11 @@ && isPrimitive(method.getReturnType())) { str = URL.encode(str); } if (parameter != null && parameter.append()) { - String pre = (String) parameters.get(Constants.DEFAULT_KEY + "." + key); + String pre = parameters.get(Constants.DEFAULT_KEY + "." + key); if (pre != null && pre.length() > 0) { str = pre + "," + str; } - pre = (String) parameters.get(key); + pre = parameters.get(key); if (pre != null && pre.length() > 0) { str = pre + "," + str; } @@ -474,7 +474,7 @@ public String toString() { && isPrimitive(method.getReturnType())) { int i = name.startsWith("get") ? 3 : 2; String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); - Object value = method.invoke(this, new Object[0]); + Object value = method.invoke(this); if (value != null) { buf.append(" "); buf.append(key); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java index fecc29cf314..9966fe5fed8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java @@ -30,6 +30,7 @@ import com.alibaba.dubbo.rpc.ProxyFactory; import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.support.MockInvoker; +import com.alibaba.dubbo.tracker.RpcTrackerEngine; import com.alibaba.dubbo.tracker.RpcTrackerEngineFactory; import com.alibaba.dubbo.tracker.RpcTrackerFactory; import com.alibaba.dubbo.tracker.RpcTrackerManager; @@ -56,7 +57,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { // 服务监控 protected MonitorConfig monitor; // 服务追踪 - protected TrackerConfig tracker; + protected RpcTrackerEngineConfig tracker; // 代理类型 protected String proxy; @@ -239,7 +240,23 @@ protected URL loadMonitor(URL registryURL) { return null; } - protected URL loadTracker() { + + protected void initRpcTrackerManagerIfNeeded() { + URL url = loadTracker(); + if (url != null) { + tracker.setProtocol(url.getProtocol() == null ? "zipkin" : url.getProtocol()); + RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); + RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); + RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); + if (tracker.getRef() != null) { + RpcTrackerManager.setRpcTrackerEngine((RpcTrackerEngine) tracker.getRef()); + } else { + RpcTrackerManager.createRpcTrackerEngine(rpcTrackerEngineFactory, url); + } + } + } + + private URL loadTracker() { if (tracker != null) { appendProperties(tracker); Map map = new HashMap(); @@ -251,28 +268,15 @@ protected URL loadTracker() { } appendParameters(map, tracker); String address = tracker.getAddress(); - String sysAddress = System.getProperty("dubbo.tracker.address"); - if (sysAddress != null && sysAddress.length() > 0) { - address = sysAddress; - } if (ConfigUtils.isNotEmpty(address)) { return UrlUtils.parseURL(address, map); + } else { + return UrlUtils.parseURL(NetUtils.ANYHOST, map); } } return null; } - protected void initRpcTrackerManagerIfNeeded() { - URL url = loadTracker(); - if (url != null) { - tracker.setProtocol(url.getProtocol() == null ? "zipkin" : url.getProtocol()); - RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); - RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); - RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); - RpcTrackerManager.createRpcTrackerEngine(rpcTrackerEngineFactory, url); - } - } - protected void checkInterfaceAndMethods(Class interfaceClass, List methods) { // 接口不能为空 if (interfaceClass == null) { @@ -500,11 +504,11 @@ public void setMonitor(String monitor) { this.monitor = new MonitorConfig(monitor); } - public TrackerConfig getTracker() { + public RpcTrackerEngineConfig getTracker() { return tracker; } - public void setTracker(TrackerConfig tracker) { + public void setTracker(RpcTrackerEngineConfig tracker) { this.tracker = tracker; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java index 1c838c64b1b..97292fad6b4 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java @@ -15,15 +15,15 @@ */ package com.alibaba.dubbo.config; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.rpc.cluster.LoadBalance; +import java.util.Map; + /** * AbstractMethodConfig - * + * * @author william.liangf * @export */ @@ -32,34 +32,34 @@ public abstract class AbstractMethodConfig extends AbstractConfig { private static final long serialVersionUID = 1L; // 远程调用超时时间(毫秒) - protected Integer timeout; + protected Integer timeout; // 重试次数 - protected Integer retries; + protected Integer retries; // 最大并发调用 - protected Integer actives; - + protected Integer actives; + // 负载均衡 - protected String loadbalance; + protected String loadbalance; // 是否异步 - protected Boolean async; - + protected Boolean async; + // 异步发送是否等待发送成功 - protected Boolean sent; + protected Boolean sent; // 服务接口的失败mock实现类名 - protected String mock; + protected String mock; // 合并器 - protected String merger; - + protected String merger; + // 服务接口的失败mock实现类名 - protected String cache; + protected String cache; // 服务接口的失败mock实现类名 - protected String validation; + protected String validation; // 自定义参数 protected Map parameters; @@ -100,7 +100,7 @@ public void setAsync(Boolean async) { public Integer getActives() { return actives; } - + public void setActives(Integer actives) { this.actives = actives; } @@ -126,7 +126,7 @@ public void setMock(String mock) { } this.mock = mock; } - + public void setMock(Boolean mock) { if (mock == null) { setMock((String) null); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java index e664da5ccbc..dcf03bff9cd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java @@ -64,7 +64,7 @@ public class ApplicationConfig extends AbstractConfig { // 服务监控 private MonitorConfig monitor; - private TrackerConfig tracker; + private RpcTrackerEngineConfig tracker; // 是否为缺省 private Boolean isDefault; @@ -172,11 +172,11 @@ public void setMonitor(String monitor) { this.monitor = new MonitorConfig(monitor); } - public TrackerConfig getTracker() { + public RpcTrackerEngineConfig getTracker() { return tracker; } - public void setTracker(TrackerConfig tracker) { + public void setTracker(RpcTrackerEngineConfig tracker) { this.tracker = tracker; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RpcTrackerEngineConfig.java similarity index 90% rename from dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java rename to dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RpcTrackerEngineConfig.java index 5ce36d3f71c..b23a54a04c4 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/TrackerConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/RpcTrackerEngineConfig.java @@ -2,7 +2,7 @@ import java.util.Map; -public class TrackerConfig extends AbstractConfig { +public class RpcTrackerEngineConfig extends AbstractConfig { private String application; @@ -24,9 +24,11 @@ public class TrackerConfig extends AbstractConfig { private String version; + private T ref; + private Map parameters; - public TrackerConfig() { + public RpcTrackerEngineConfig() { } public String getApplication() { @@ -109,6 +111,14 @@ public void setVersion(String version) { this.version = version; } + public T getRef() { + return ref; + } + + public void setRef(T ref) { + this.ref = ref; + } + public Map getParameters() { return parameters; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index be40811acd1..5f7b113447d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -425,6 +425,7 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r map.put("methods", StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); } } + if (!ConfigUtils.isEmpty(token)) { if (ConfigUtils.isDefault(token)) { map.put("token", UUID.randomUUID().toString()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java index e421096462b..289af411859 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/TrackConfigTest.java @@ -6,14 +6,14 @@ public class TrackConfigTest { @Test public void test_trackConfig(){ - TrackerConfig trackerConfig = new TrackerConfig(); - trackerConfig.setProtocol("zipkin"); - trackerConfig.setAddress("localhost:9411"); - trackerConfig.setApplication("test"); - trackerConfig.setTransport("kafka"); - trackerConfig.setSampler("counting"); - trackerConfig.setSamplerate(0.1f); - trackerConfig.setFlushinterval(2); - System.out.println(trackerConfig.toString()); + RpcTrackerEngineConfig trackerEngineConfig = new RpcTrackerEngineConfig(); + trackerEngineConfig.setProtocol("zipkin"); + trackerEngineConfig.setAddress("localhost:9411"); + trackerEngineConfig.setApplication("test"); + trackerEngineConfig.setTransport("kafka"); + trackerEngineConfig.setSampler("counting"); + trackerEngineConfig.setSamplerate(0.1f); + trackerEngineConfig.setFlushinterval(2); + System.out.println(trackerEngineConfig.toString()); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java index c73ac065f66..ab3794a57a4 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java @@ -162,15 +162,15 @@ public void afterPropertiesSet() throws Exception { if (getTracker() == null && (getConsumer() == null || getConsumer().getTracker() == null) && (getApplication() == null || getApplication().getTracker() == null)) { - Map trackerConfigMap = applicationContext == null ? null : - BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, TrackerConfig.class, false, false); + Map trackerConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RpcTrackerEngineConfig.class, false, false); if (trackerConfigMap != null && trackerConfigMap.size() > 0) { - TrackerConfig trackerConfig = null; - for (TrackerConfig config : trackerConfigMap.values()) { - trackerConfig = config; + RpcTrackerEngineConfig trackerEngineConfig = null; + for (RpcTrackerEngineConfig config : trackerConfigMap.values()) { + trackerEngineConfig = config; } - if (trackerConfig != null) { - setTracker(trackerConfig); + if (trackerEngineConfig != null) { + setTracker(trackerEngineConfig); } } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index 0007325beed..96e2d1231f3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -228,15 +228,15 @@ public void afterPropertiesSet() throws Exception { if (getTracker() == null && (getProvider() == null || getProvider().getTracker() == null) && (getApplication() == null || getApplication().getTracker() == null)) { - Map trackerConfigMap = applicationContext == null ? null : - BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, TrackerConfig.class, false, false); + Map trackerConfigMap = applicationContext == null ? null : + BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RpcTrackerEngineConfig.class, false, false); if (trackerConfigMap != null && trackerConfigMap.size() > 0) { - TrackerConfig trackerConfig = null; - for (TrackerConfig config : trackerConfigMap.values()) { - trackerConfig = config; + RpcTrackerEngineConfig trackerEngineConfig = null; + for (RpcTrackerEngineConfig config : trackerConfigMap.values()) { + trackerEngineConfig = config; } - if (trackerConfig != null) { - setTracker(trackerConfig); + if (trackerEngineConfig != null) { + setTracker(trackerEngineConfig); } } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java index 58ead17c123..1867004296b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboNamespaceHandler.java @@ -45,7 +45,6 @@ public void init() { registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); - registerBeanDefinitionParser("tracker", new DubboBeanDefinitionParser(TrackerConfig.class, true)); + registerBeanDefinitionParser("tracker", new DubboBeanDefinitionParser(RpcTrackerEngineConfig.class, true)); } - } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 1680899406c..847b1e67ef4 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -591,6 +591,11 @@ + + + + + diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 1784ce09f71..ff315646e8f 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -9,7 +9,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 41d7808623c..1060899d556 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,7 +24,9 @@ - + + + @@ -61,10 +63,10 @@ - + - @@ -84,4 +86,11 @@ + + + + + + + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 116ac2b531b..1dd2aacd6a0 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -44,10 +44,10 @@ dubbo-tracker-api ${project.parent.version} - - com.alibaba - dubbo-tracker-zipkin - ${project.parent.version} - + + + + + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 752a7064b61..21acf807e04 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -24,11 +24,8 @@ import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.transport.DecodeHandler; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerManager; import com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder; import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboServerRequestResponseInterceptor; /** * DefaultMessenger @@ -57,7 +54,7 @@ public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingE public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeHandler exchangeHandler = new HeaderExchangeHandler(handler); Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); - if (interceptor != null){ + if (interceptor != null) { exchangeHandler.addInterceptor(interceptor); } return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(exchangeHandler))); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java index 15b15739870..cdf7ad73430 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java @@ -44,7 +44,6 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) -// .setAttachments(attachments) // modified by lishen .setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TimeoutFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TimeoutFilter.java index b63ff232e26..45578261fc1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TimeoutFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TimeoutFilter.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.rpc.filter; - +package com.alibaba.dubbo.rpc.filter; + import java.util.Arrays; import com.alibaba.dubbo.common.Constants; @@ -26,13 +26,13 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; - -/** - * 如果执行timeout,则log记录下,不干涉服务的运行 - * - * @author chao.liuc + +/** + * 如果执行timeout,则log记录下,不干涉服务的运行 + * + * @author chao.liuc */ -@Activate(group = Constants.PROVIDER) +@Activate(group = Constants.PROVIDER) public class TimeoutFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(TimeoutFilter.class); @@ -52,5 +52,4 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept } return result; } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TokenFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TokenFilter.java index 5ff698eb666..27bad1d0b00 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/TokenFilter.java @@ -15,38 +15,32 @@ */ package com.alibaba.dubbo.rpc.filter; -import java.util.Map; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.ConfigUtils; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.*; + +import java.util.Map; /** * TokenInvokerFilter - * + * * @author william.liangf */ @Activate(group = Constants.PROVIDER, value = Constants.TOKEN_KEY) public class TokenFilter implements Filter { - public Result invoke(Invoker invoker, Invocation inv) - throws RpcException { - String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY); - if (ConfigUtils.isNotEmpty(token)) { - Class serviceType = invoker.getInterface(); - Map attachments = inv.getAttachments(); - String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY); - if (! token.equals(remoteToken)) { - throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider " + RpcContext.getContext().getLocalHost()); - } - } - return invoker.invoke(inv); - } - + public Result invoke(Invoker invoker, Invocation inv) + throws RpcException { + String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY); + if (ConfigUtils.isNotEmpty(token)) { + Class serviceType = invoker.getInterface(); + Map attachments = inv.getAttachments(); + String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY); + if (!token.equals(remoteToken)) { + throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider " + RpcContext.getContext().getLocalHost()); + } + } + return invoker.invoke(inv); + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index adf8f9fcda6..42c4494c456 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -14,54 +14,49 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-rpc - 3.0.0 - - dubbo-rpc-hessian - jar - ${project.artifactId} - The hessian rpc module of dubbo project - - true - - - - com.alibaba - dubbo-rpc-api - ${project.parent.version} - - - com.alibaba - dubbo-remoting-http - ${project.parent.version} - - - com.caucho - hessian - - - org.apache.httpcomponents - httpclient - provided - true - - - com.squareup.okhttp3 - okhttp - - - com.alibaba - dubbo-tracker-api - ${project.parent.version} - - - com.alibaba - dubbo-tracker-zipkin - ${project.parent.version} - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.alibaba + dubbo-rpc + 3.0.0 + + dubbo-rpc-hessian + jar + ${project.artifactId} + The hessian rpc module of dubbo project + + true + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + com.alibaba + dubbo-remoting-http + ${project.parent.version} + + + com.caucho + hessian + + + org.apache.httpcomponents + httpclient + provided + true + + + com.squareup.okhttp3 + okhttp + + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index 372e8d58329..949bcc56825 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -1,9 +1,7 @@ package com.alibaba.dubbo.rpc.protocol.hessian; import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.tracker.RpcTrackerManager; import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; -import com.alibaba.dubbo.tracker.zipkin.http.AttachMethodNameInterceptor; import com.caucho.hessian.client.HessianConnection; import com.caucho.hessian.client.HessianConnectionFactory; import com.caucho.hessian.client.HessianProxyFactory; @@ -28,9 +26,6 @@ public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url, HttpRequestResp Interceptor interceptor = requestResponseInterceptorBuilder.build(url); if (interceptor != null) { builder.addInterceptor(interceptor); - if (RpcTrackerManager.getRpcTracker(url) != null) { - builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); - } } client = builder.build(); } diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 77b549d1e0b..893bd8afa96 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -14,52 +14,47 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-rpc - 3.0.0 - - dubbo-rpc-http - jar - ${project.artifactId} - The http rpc module of dubbo project - - true - - - - com.alibaba - dubbo-rpc-api - ${project.parent.version} - - - com.alibaba - dubbo-remoting-http - ${project.parent.version} - - - org.springframework - spring-context - - - org.springframework - spring-web - - - com.squareup.okhttp3 - okhttp - - - com.alibaba - dubbo-tracker-api - ${project.parent.version} - - - com.alibaba - dubbo-tracker-zipkin - ${project.parent.version} - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.alibaba + dubbo-rpc + 3.0.0 + + dubbo-rpc-http + jar + ${project.artifactId} + The http rpc module of dubbo project + + true + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + com.alibaba + dubbo-remoting-http + ${project.parent.version} + + + org.springframework + spring-context + + + org.springframework + spring-web + + + com.squareup.okhttp3 + okhttp + + + com.alibaba + dubbo-tracker-api + ${project.parent.version} + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java index f02a8e3d1b0..2b64f9e0497 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java @@ -5,9 +5,6 @@ import com.alibaba.dubbo.tracker.RpcTracker; import com.alibaba.dubbo.tracker.RpcTrackerManager; import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; -import com.alibaba.dubbo.tracker.zipkin.http.AttachMethodNameInterceptor; -import com.alibaba.dubbo.tracker.zipkin.http.BraveOkHttpRequestResponseInterceptor; -import com.alibaba.dubbo.tracker.zipkin.http.HttpSpanNameProvider; import okhttp3.*; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; @@ -28,17 +25,17 @@ public OkHttpInvokerRequestExecutor(URL url, HttpRequestResponseInterceptorBuild builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); - if (rpcTracker != null) { - builder.addInterceptor(new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance())); - builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); - } - Interceptor interceptor = requestResponseInterceptorBuilder.build(url); - if (interceptor != null) { - builder.addInterceptor(interceptor); - if (RpcTrackerManager.getRpcTracker(url) != null) { - builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); - } - } +// if (rpcTracker != null) { +// builder.addInterceptor(new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance())); +// builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); +// } +// Interceptor interceptor = requestResponseInterceptorBuilder.build(url); +// if (interceptor != null) { +// builder.addInterceptor(interceptor); +// if (RpcTrackerManager.getRpcTracker(url) != null) { +// builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); +// } +// } client = builder.build(); } diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index e64e24ea107..2e1237dbb1e 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -30,10 +30,12 @@ dubbo-rpc-api 3.0.0 + javax.servlet javax.servlet-api + com.squareup.okhttp3 okhttp diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java index da87314f5e6..dcb7913a7de 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java @@ -35,6 +35,10 @@ public static synchronized RpcTrackerEngine createRpcTrackerEngine(RpcTrackerEng return rpcTrackerEngine; } + public static synchronized void setRpcTrackerEngine(RpcTrackerEngine engine) { + rpcTrackerEngine = engine; + } + public static synchronized RpcTracker createRpcTracker(URL url) { String protocol = url.getProtocol(); if (rpcTrackerEngine == null || rpcTrackerFactory == null) { diff --git a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml b/dubbo-tracker/dubbo-tracker-zipkin/pom.xml deleted file mode 100644 index 6f70237f1c8..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - dubbo-tracker - com.alibaba - 3.0.0 - - 4.0.0 - - dubbo-tracker-zipkin - - - - com.alibaba - dubbo-tracker-api - ${project.version} - - - - io.zipkin.brave - brave-core - - - - io.zipkin.brave - brave-http - - - - io.zipkin.brave - brave-web-servlet-filter - - - - io.zipkin.brave - brave-okhttp - - - - io.zipkin.brave - brave-spancollector-http - - - - io.zipkin.brave - brave-spancollector-kafka - - - - io.zipkin.brave - brave-spancollector-scribe - - - - com.google.auto.value - auto-value - - - - io.zipkin.brave - brave-core-spring - 3.9.0 - - - - io.zipkin.brave - brave-mysql - 3.9.0 - - - \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java deleted file mode 100644 index 77554ba3324..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngine.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.github.kristofa.brave.*; -import com.github.kristofa.brave.http.HttpSpanCollector; -import com.github.kristofa.brave.kafka.KafkaSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollector; -import com.github.kristofa.brave.scribe.ScribeSpanCollectorParams; - -import java.net.URLDecoder; - -/** - * 基于Zipkin的RpcTracker引擎 - * - * @author Xs - */ -public class BraveRpcTrackerEngine implements RpcTrackerEngine { - - private static final SpanCollectorMetricsHandler DEFAULT_HANDLER = new LoggingSpanCollectorMetricsHandler(); - - private final Brave brave; - - BraveRpcTrackerEngine(URL url) { - Brave.Builder builder = new Brave.Builder(url.getParameter("application")); - builder.spanCollector(createSpanCollector(url)); - builder.traceSampler(createSampler(url)); - brave = builder.build(); - } - - private SpanCollector createSpanCollector(URL url) { - String transport = url.getParameter("transport", "http"); - Integer flushInterval = url.getParameter("flushiterval", 1); - if (transport.equals("http")) { - HttpSpanCollector.Config.Builder builder = HttpSpanCollector.Config.builder(); - builder.flushInterval(flushInterval); - String baseUrl = "http://" + url.getHost() + ":" + url.getPort(); - return HttpSpanCollector.create(baseUrl, builder.build(), DEFAULT_HANDLER); - } else if (transport.equals("kafka")) { - String address = url.getParameter("address"); - if (StringUtils.isEmpty(address)) { - throw new IllegalArgumentException("transport address must not be null"); - } - KafkaSpanCollector.Config.Builder builder = KafkaSpanCollector.Config.builder(address); - builder.flushInterval(flushInterval); - return KafkaSpanCollector.create(builder.build(), DEFAULT_HANDLER); - } else if (transport.equals("scribe")) { - ScribeSpanCollectorParams params = new ScribeSpanCollectorParams(); - params.setMetricsHandler(DEFAULT_HANDLER); - return new ScribeSpanCollector(url.getHost(), url.getPort(), params); - } else { - throw new IllegalArgumentException("unknown transport type, transport: " + transport); - } - } - - private Sampler createSampler(URL url) { - String sampler = url.getParameter("sampler"); - if (StringUtils.isEmpty(sampler)) { - return Sampler.ALWAYS_SAMPLE; - } else { - String rate = url.getParameter("rate"); - if (StringUtils.isEmpty(rate)) { - return Sampler.ALWAYS_SAMPLE; - } - if (sampler.equals("counting")) { - return CountingSampler.create(Float.valueOf(rate)); - } else if (sampler.equals("boundary")) { - return BoundarySampler.create(Float.valueOf(rate)); - } else { - throw new IllegalArgumentException("unknown sampler type, sampler: " + sampler); - } - } - } - - public static BraveRpcTrackerEngine create(URL url) { - return new BraveRpcTrackerEngine(url); - } - - @Override - public ClientRequestInterceptor clientRequestInterceptor() { - return brave.clientRequestInterceptor(); - } - - @Override - public ClientResponseInterceptor clientResponseInterceptor() { - return brave.clientResponseInterceptor(); - } - - @Override - public ServerRequestInterceptor serverRequestInterceptor() { - return brave.serverRequestInterceptor(); - } - - @Override - public ServerResponseInterceptor serverResponseInterceptor() { - return brave.serverResponseInterceptor(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java deleted file mode 100644 index 46ee855c5dc..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerEngineFactory.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.RpcTrackerEngineFactory; - -/** - * @author Xs - */ -public class BraveRpcTrackerEngineFactory implements RpcTrackerEngineFactory { - - @Override - public RpcTrackerEngine createRpcTrackerEngine(URL url) { - return BraveRpcTrackerEngine.create(url); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java deleted file mode 100644 index 0f5c5675e23..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/BraveRpcTrackerFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.*; -import com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboRpcTracker; -import com.alibaba.dubbo.tracker.zipkin.http.BraveHttpRpcTracker; - -/** - * @author Xs. - */ -public class BraveRpcTrackerFactory implements RpcTrackerFactory { - - @Override - public RpcTracker createRpcTracker(URL url) { - RpcTrackerEngine rpcTrackerEngine = RpcTrackerManager.getRpcTrackerEngine(); - if (rpcTrackerEngine == null) { - return null; - } - RpcTracker rpcTracker = null; - RpcProtocol rpcProtocol = RpcProtocol.valueOf(url.getProtocol()); - if (rpcProtocol.equals(RpcProtocol.DUBBO)) { - rpcTracker = new BraveDubboRpcTracker((BraveRpcTrackerEngine) rpcTrackerEngine); - } else if (rpcProtocol.equals(RpcProtocol.HTTP) || rpcProtocol.equals(RpcProtocol.HESSIAN)) { - rpcTracker = new BraveHttpRpcTracker(rpcTrackerEngine); - } - return rpcTracker; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java deleted file mode 100644 index 7a42f6b2608..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/LoggingSpanCollectorMetricsHandler.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin; - -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.github.kristofa.brave.SpanCollectorMetricsHandler; - -/** - * @author Xs - */ -public class LoggingSpanCollectorMetricsHandler implements SpanCollectorMetricsHandler { - - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - @Override - public void incrementAcceptedSpans(int quantity) { - // NOP - } - - @Override - public void incrementDroppedSpans(int quantity) { - LOGGER.warn(quantity + " spans were dropped !"); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java deleted file mode 100644 index fd9618bf099..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestAdapter.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.dubbo.DubboRequest; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.TrackerKeys; -import com.github.kristofa.brave.ClientRequestAdapter; -import com.github.kristofa.brave.IdConversion; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.SpanId; -import com.twitter.zipkin.gen.Endpoint; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * @author Xs - */ -public class BraveDubboClientRequestAdapter implements ClientRequestAdapter, com.alibaba.dubbo.tracker.ClientRequestAdapter { - - private final DubboRequest request; - - private final DubboRequestSpanNameProvider spanNameProvider; - - public BraveDubboClientRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { - this.request = request; - this.spanNameProvider = spanNameProvider; - } - - public boolean isTraceable() { - return request.isTraceable(); - } - - @Override - public String getSpanName() { - return spanNameProvider.spanName(request); - } - - @Override - public void addSpanIdToRequest(SpanId spanId) { - if (spanId == null) { - request.addAttachment(RpcAttachment.Sampled.getName(), "0"); - } else { - request.addAttachment(RpcAttachment.Sampled.getName(), "1"); - request.addAttachment(RpcAttachment.TraceId.getName(), IdConversion.convertToString(spanId.traceId)); - request.addAttachment(RpcAttachment.SpanId.getName(), IdConversion.convertToString(spanId.spanId)); - if (spanId.nullableParentId() != null) { - request.addAttachment(RpcAttachment.ParentSpanId.getName(), IdConversion.convertToString(spanId.parentId)); - } - request.addAttachment(RpcAttachment.SpanName.getName(), getSpanName()); - } - } - - @Override - public Collection requestAnnotations() { - List requestAnnotations = new ArrayList(); - KeyValueAnnotation annotation = KeyValueAnnotation.create(TrackerKeys.PROVIDER_ADDRESS, request.providerAddress()); - requestAnnotations.add(annotation); - annotation = KeyValueAnnotation.create(TrackerKeys.REMOTE_METHOD, request.remoteMethod()); - requestAnnotations.add(annotation); - annotation = KeyValueAnnotation.create(TrackerKeys.SERVICE_VERSION, request.serviceVersion()); - requestAnnotations.add(annotation); - return requestAnnotations; - } - - @Override - public Endpoint serverAddress() { - return null; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java deleted file mode 100644 index 36ca7a6dc4d..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestInterceptor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.ClientRequestAdapter; -import com.alibaba.dubbo.tracker.ClientRequestInterceptor; - -/** - * @author Xs. - */ -public class BraveDubboClientRequestInterceptor implements ClientRequestInterceptor { - - private final com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor; - - public BraveDubboClientRequestInterceptor(com.github.kristofa.brave.ClientRequestInterceptor clientRequestInterceptor) { - this.clientRequestInterceptor = clientRequestInterceptor; - } - - @Override - public void handle(ClientRequestAdapter clientRequestAdapter) { - if (clientRequestAdapter.isTraceable()) { - clientRequestInterceptor.handle((com.github.kristofa.brave.ClientRequestAdapter) clientRequestAdapter); - } - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java deleted file mode 100644 index e3f2e5ce547..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientRequestResponseInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - - -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.message.Interceptor; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.dubbo.DubboRequest; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.dubbo.DubboResponse; -import com.alibaba.dubbo.tracker.RpcTracker; - -/** - * dubbo协议client request拦截器 - * - * @author Xs - */ -public class BraveDubboClientRequestResponseInterceptor implements Interceptor { - - private final RpcTracker rpcTracker; - - private final DubboRequestSpanNameProvider spanNameProvider; - - public BraveDubboClientRequestResponseInterceptor(RpcTracker rpcTracker, DubboRequestSpanNameProvider spanNameProvider) { - this.rpcTracker = rpcTracker; - this.spanNameProvider = spanNameProvider; - } - - @Override - public Response intercept(Chain chain) throws RemotingException { - Request request = chain.request(); - rpcTracker.trackClientRequest(new BraveDubboClientRequestAdapter(new DubboRequest(request), spanNameProvider)); - Response response = chain.proceed(request, chain.timeout()); - rpcTracker.trackClientResponse(new BraveDubboClientResponseAdapter(new DubboResponse(response))); - return response; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java deleted file mode 100644 index e713af8722c..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseAdapter.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.dubbo.DubboResponse; -import com.alibaba.dubbo.tracker.TrackerKeys; -import com.github.kristofa.brave.ClientResponseAdapter; -import com.github.kristofa.brave.KeyValueAnnotation; - -import java.util.Collection; -import java.util.Collections; - -/** - * @author Xs. - */ -public class BraveDubboClientResponseAdapter implements ClientResponseAdapter, com.alibaba.dubbo.tracker.ClientResponseAdapter { - - private final DubboResponse response; - - public BraveDubboClientResponseAdapter(DubboResponse response) { - this.response = response; - } - - public boolean isTraceable() { - return response.isTraceable(); - } - - @Override - public Collection responseAnnotations() { - KeyValueAnnotation statusAnnotation; - if (response.returnOK()) { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, "OK"); - } else { - statusAnnotation = KeyValueAnnotation.create(TrackerKeys.RETURN_STATUS, response.exceptionMessage()); - } - return Collections.singletonList(statusAnnotation); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java deleted file mode 100644 index c4f71f0d558..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboClientResponseInterceptor.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - - -import com.alibaba.dubbo.tracker.ClientResponseAdapter; -import com.alibaba.dubbo.tracker.ClientResponseInterceptor; - -/** - * @author Xs. - */ -public class BraveDubboClientResponseInterceptor implements ClientResponseInterceptor { - - private final com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor; - - public BraveDubboClientResponseInterceptor(com.github.kristofa.brave.ClientResponseInterceptor clientResponseInterceptor) { - this.clientResponseInterceptor = clientResponseInterceptor; - } - - - @Override - public void handle(ClientResponseAdapter clientResponseAdapter) { - if (clientResponseAdapter.isTraceable()) { - clientResponseInterceptor.handle((com.github.kristofa.brave.ClientResponseAdapter) clientResponseAdapter); - } - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java deleted file mode 100644 index a7c33cf09b5..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRequestInterceptorBuilder.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.message.Interceptor; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; - -/** - * @author Xs. - */ -public class BraveDubboRequestInterceptorBuilder implements DubboRequestInterceptorBuilder { - - @Override - public Interceptor build(URL url, DubboRequestSpanNameProvider spanNameProvider) { - RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); - if (rpcTracker == null) { - return null; - } - if (url.getParameter(Constants.SIDE_KEY).equals("provider")) { - return new BraveDubboServerRequestResponseInterceptor(rpcTracker, spanNameProvider); - } else if (url.getParameter(Constants.SIDE_KEY).equals("consumer")) { - return new BraveDubboClientRequestResponseInterceptor(rpcTracker, spanNameProvider); - } else { - throw new IllegalArgumentException("URL doesn't contain side key, " + url); - } - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java deleted file mode 100644 index 3ee9726184f..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboRpcTracker.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.*; -import com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngine; - -/** - * 追踪dubbo协议同步调用 - * - * @author Xs - */ -public class BraveDubboRpcTracker implements RpcTracker { - - private final ClientRequestInterceptor clientRequestInterceptor; - - private final ClientResponseInterceptor clientResponseInterceptor; - - private final ServerRequestInterceptor serverRequestInterceptor; - - private final ServerResponseInterceptor serverResponseInterceptor; - - private final BraveRpcTrackerEngine trackerEngine; - - public BraveDubboRpcTracker(BraveRpcTrackerEngine trackerEngine) { - this.trackerEngine = trackerEngine; - this.clientRequestInterceptor = new BraveDubboClientRequestInterceptor(trackerEngine.clientRequestInterceptor()); - this.clientResponseInterceptor = new BraveDubboClientResponseInterceptor( - trackerEngine.clientResponseInterceptor()); - this.serverRequestInterceptor = new BraveDubboServerRequestInterceptor( - trackerEngine.serverRequestInterceptor()); - this.serverResponseInterceptor = new BraveDubboServerResponseInterceptor( - trackerEngine.serverResponseInterceptor()); - } - - @Override - public void trackClientRequest(ClientRequestAdapter clientRequestAdapter) { - clientRequestInterceptor.handle(clientRequestAdapter); - } - - @Override - public void trackClientResponse(ClientResponseAdapter clientResponseAdapter) { - clientResponseInterceptor.handle(clientResponseAdapter); - } - - @Override - public void trackServerRequest(ServerRequestAdapter serverRequestAdapter) { - serverRequestInterceptor.handle(serverRequestAdapter); - } - - @Override - public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { - serverResponseInterceptor.handle(serverResponseAdapter); - } - - @Override - public RpcTrackerEngine trackerEngine() { - return trackerEngine; - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java deleted file mode 100644 index 583c1ff687f..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestAdapter.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.dubbo.DubboRequest; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.ServerRequestAdapter; -import com.github.kristofa.brave.SpanId; -import com.github.kristofa.brave.TraceData; - -import java.util.Collection; -import java.util.Collections; - -import static com.github.kristofa.brave.IdConversion.convertToLong; - -/** - * @author Xs - */ -public class BraveDubboServerRequestAdapter implements ServerRequestAdapter, com.alibaba.dubbo.tracker.ServerRequestAdapter { - - private final DubboRequest request; - - private final DubboRequestSpanNameProvider spanNameProvider; - - public BraveDubboServerRequestAdapter(DubboRequest request, DubboRequestSpanNameProvider spanNameProvider) { - this.request = request; - this.spanNameProvider = spanNameProvider; - } - - public boolean isTraceable() { - return request.isTraceable(); - } - - @Override - public TraceData getTraceData() { - final String sampled = request.getAttachment(RpcAttachment.Sampled.getName()); - if (sampled != null) { - if (sampled.equals("0") || sampled.toLowerCase().equals("false")) { - return TraceData.builder().sample(false).build(); - } else { - final String parentSpanId = request.getAttachment(RpcAttachment.ParentSpanId.getName()); - final String traceId = request.getAttachment(RpcAttachment.TraceId.getName()); - final String spanId = request.getAttachment(RpcAttachment.SpanId.getName()); - - if (traceId != null && spanId != null) { - SpanId span = getSpanId(traceId, spanId, parentSpanId); - return TraceData.builder().sample(true).spanId(span).build(); - } - } - } - return TraceData.builder().build(); - } - - @Override - public String getSpanName() { - return spanNameProvider.spanName(request); - } - - @Override - public Collection requestAnnotations() { - return Collections.emptyList(); - } - - private SpanId getSpanId(String traceId, String spanId, String parentSpanId) { - return SpanId.builder() - .traceId(convertToLong(traceId)) - .spanId(convertToLong(spanId)) - .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java deleted file mode 100644 index d972a607a92..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestInterceptor.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - - -import com.alibaba.dubbo.tracker.ServerRequestAdapter; -import com.alibaba.dubbo.tracker.ServerRequestInterceptor; - -/** - * @author Xs - */ -public class BraveDubboServerRequestInterceptor implements ServerRequestInterceptor { - - private final com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor; - - public BraveDubboServerRequestInterceptor(com.github.kristofa.brave.ServerRequestInterceptor serverRequestInterceptor) { - this.serverRequestInterceptor = serverRequestInterceptor; - } - - @Override - public void handle(ServerRequestAdapter serverRequestAdapter) { - if (serverRequestAdapter.isTraceable()) { - serverRequestInterceptor.handle((com.github.kristofa.brave.ServerRequestAdapter) serverRequestAdapter); - } - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java deleted file mode 100644 index ce740ef2ff9..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerRequestResponseInterceptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.message.Interceptor; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.tracker.dubbo.DubboRequest; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; -import com.alibaba.dubbo.tracker.dubbo.DubboResponse; -import com.alibaba.dubbo.tracker.RpcTracker; - -/** - * @author Xs. - */ -public class BraveDubboServerRequestResponseInterceptor implements Interceptor { - - private final RpcTracker rpcTracker; - - private final DubboRequestSpanNameProvider spanNameProvider; - - public BraveDubboServerRequestResponseInterceptor(RpcTracker rpcTracker, DubboRequestSpanNameProvider spanNameProvider) { - this.rpcTracker = rpcTracker; - this.spanNameProvider = spanNameProvider; - } - - @Override - public Response intercept(Chain chain) throws RemotingException { - Request request = chain.request(); - rpcTracker.trackServerRequest(new BraveDubboServerRequestAdapter(new DubboRequest(request), spanNameProvider)); - Response response = chain.proceed(request); - rpcTracker.trackServerResponse(new BraveDubboServerResponseAdapter(new DubboResponse(response))); - return response; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java deleted file mode 100644 index 06461665eae..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - -import com.alibaba.dubbo.tracker.dubbo.DubboResponse; -import com.github.kristofa.brave.KeyValueAnnotation; -import com.github.kristofa.brave.ServerResponseAdapter; - -import java.util.Collection; -import java.util.Collections; - -/** - * @author Xs - */ -public class BraveDubboServerResponseAdapter implements ServerResponseAdapter, com.alibaba.dubbo.tracker.ServerResponseAdapter { - - private final DubboResponse response; - - public BraveDubboServerResponseAdapter(DubboResponse response) { - this.response = response; - } - - public boolean isTraceable() { - return response.isTraceable(); - } - - @Override - public Collection responseAnnotations() { - return Collections.emptyList(); - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java deleted file mode 100644 index 6848093cbdd..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/dubbo/BraveDubboServerResponseInterceptor.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.dubbo; - - -import com.alibaba.dubbo.tracker.ServerResponseAdapter; -import com.alibaba.dubbo.tracker.ServerResponseInterceptor; - -/** - * @author Xs - */ -public class BraveDubboServerResponseInterceptor implements ServerResponseInterceptor { - - private final com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor; - - public BraveDubboServerResponseInterceptor(com.github.kristofa.brave.ServerResponseInterceptor serverResponseInterceptor) { - this.serverResponseInterceptor = serverResponseInterceptor; - } - - @Override - public void handle(ServerResponseAdapter serverResponseAdapter) { - if (serverResponseAdapter.isTraceable()) { - serverResponseInterceptor.handle((com.github.kristofa.brave.ServerResponseAdapter) serverResponseAdapter); - } - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java deleted file mode 100644 index 95f6b47d15a..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/filter/BraveHttpServletFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.filter; - -import com.alibaba.dubbo.tracker.http.ServletFilter; -import com.github.kristofa.brave.servlet.BraveServletFilter; - -import javax.servlet.*; -import java.io.IOException; - -/** - * @author Xs. - */ -public class BraveHttpServletFilter implements ServletFilter { - - private final BraveServletFilter servletFilter; - - public BraveHttpServletFilter(BraveServletFilter servletFilter) { - this.servletFilter = servletFilter; - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - servletFilter.init(filterConfig); - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletFilter.doFilter(servletRequest, servletResponse, filterChain); - } - - @Override - public void destroy() { - servletFilter.destroy(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java deleted file mode 100644 index e7cfba3f2e0..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/AttachMethodNameInterceptor.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.tracker.RpcAttachment; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -import java.io.IOException; - -/** - * @author Xs. - */ -public class AttachMethodNameInterceptor implements Interceptor { - - private static final AttachMethodNameInterceptor instance = new AttachMethodNameInterceptor(); - - private AttachMethodNameInterceptor() { - } - - public static AttachMethodNameInterceptor getInstance() { - return instance; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - Request.Builder builder = request.newBuilder(); - builder.addHeader(RpcAttachment.SpanName.getName(), RpcContext.getContext().getMethodName()); - return chain.proceed(builder.build()); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java deleted file mode 100644 index bc56e035b9e..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveHttpRpcTracker.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngine; - -/** - * @author Xs - */ -public class BraveHttpRpcTracker extends FacadeHttpRpcTracker { - - private final RpcTrackerEngine trackerEngine; - - public BraveHttpRpcTracker(RpcTrackerEngine trackerEngine) { - this.trackerEngine = trackerEngine; - } - - @Override - public RpcTrackerEngine trackerEngine() { - return trackerEngine; - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java deleted file mode 100644 index 444e7877018..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptor.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.github.kristofa.brave.ClientRequestInterceptor; -import com.github.kristofa.brave.ClientResponseInterceptor; -import com.github.kristofa.brave.http.SpanNameProvider; -import okhttp3.Interceptor; -import okhttp3.Response; - -import java.io.IOException; - -/** - * @author Xs. - */ -public class BraveOkHttpRequestResponseInterceptor implements Interceptor { - - private Interceptor delegate; - - public BraveOkHttpRequestResponseInterceptor(RpcTracker rpcTracker, SpanNameProvider spanNameProvider) { - RpcTrackerEngine trackerEngine = rpcTracker.trackerEngine(); - delegate = new com.github.kristofa.brave.okhttp.BraveOkHttpRequestResponseInterceptor((ClientRequestInterceptor) trackerEngine.clientRequestInterceptor(), - (ClientResponseInterceptor) trackerEngine.clientResponseInterceptor(), spanNameProvider); - } - - @Override - public Response intercept(Chain chain) throws IOException { - return delegate.intercept(chain); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java deleted file mode 100644 index 3d8ba8c0734..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveOkHttpRequestResponseInterceptorBuilder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; -import okhttp3.Interceptor; - -/** - * @author Xs. - */ -public class BraveOkHttpRequestResponseInterceptorBuilder implements HttpRequestResponseInterceptorBuilder { - - @Override - public Interceptor build(URL url) { - RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); - if (rpcTracker == null) { - return null; - } - return new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance()); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java deleted file mode 100644 index cf541ea7a2d..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.http.ServletFilter; -import com.github.kristofa.brave.ServerRequestInterceptor; -import com.github.kristofa.brave.ServerResponseInterceptor; -import com.github.kristofa.brave.http.SpanNameProvider; - -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; - -public class BraveServletFilter implements ServletFilter { - - private final Filter delegate; - - public BraveServletFilter(RpcTracker rpcTracker, SpanNameProvider spanNameProvider) { - RpcTrackerEngine trackerEngine = rpcTracker.trackerEngine(); - delegate = new com.github.kristofa.brave.servlet.BraveServletFilter((ServerRequestInterceptor) trackerEngine.serverRequestInterceptor(), - (ServerResponseInterceptor) trackerEngine.serverResponseInterceptor(), spanNameProvider); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - delegate.init(filterConfig); - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (isSampleNeeded(request)) { - delegate.doFilter(request, response, chain); - } else { - chain.doFilter(request, response); - } - } - - private boolean isSampleNeeded(ServletRequest request) { - return ((HttpServletRequest) request).getHeader(RpcAttachment.Sampled.getName()) != null; - } - - @Override - public void destroy() { - delegate.destroy(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java deleted file mode 100644 index d0314870e90..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/BraveServletFilterBuilder.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerManager; -import com.alibaba.dubbo.tracker.http.ServletFilter; -import com.alibaba.dubbo.tracker.http.ServletFilterBuilder; - -public class BraveServletFilterBuilder implements ServletFilterBuilder { - - @Override - public ServletFilter build(URL url) { - RpcTracker rpcTracker = RpcTrackerManager.getRpcTracker(url); - if (rpcTracker == null) { - return null; - } - return new BraveServletFilter(rpcTracker, HttpSpanNameProvider.getInstance()); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java deleted file mode 100644 index d3b61b5def4..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/FacadeHttpRpcTracker.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.*; - -/** - * @author Xs. - */ -public abstract class FacadeHttpRpcTracker implements RpcTracker { - - @Override - public void trackClientRequest(ClientRequestAdapter clientRequestAdapter) { - // NOP - } - - @Override - public void trackClientResponse(ClientResponseAdapter clientResponseAdapter) { - // NOP - } - - @Override - public void trackServerRequest(ServerRequestAdapter serverRequestAdapter) { - // NOP - } - - @Override - public void trackServerResponse(ServerResponseAdapter serverResponseAdapter) { - // NOP - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java deleted file mode 100644 index 631f45f601b..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/java/com/alibaba/dubbo/tracker/zipkin/http/HttpSpanNameProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.http; - -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.RpcContextMethodNameProvider; -import com.github.kristofa.brave.http.HttpClientRequest; -import com.github.kristofa.brave.http.HttpRequest; -import com.github.kristofa.brave.http.HttpServerRequest; -import com.github.kristofa.brave.http.SpanNameProvider; - -/** - * @author Xs. - */ -public class HttpSpanNameProvider extends RpcContextMethodNameProvider implements SpanNameProvider { - - private static final HttpSpanNameProvider instance = new HttpSpanNameProvider(); - - private HttpSpanNameProvider() { - } - - public static HttpSpanNameProvider getInstance() { - return instance; - } - - @Override - public String spanName(HttpRequest request) { - String spanName; - if (request instanceof HttpClientRequest) { - spanName = getMethodNameFromContext(); - } else if (request instanceof HttpServerRequest) { - spanName = getSpanNameFromHeader((HttpServerRequest) request); - } else { - throw new IllegalArgumentException("wrong type http request, " + request); - } - return spanName; - } - - - private String getSpanNameFromHeader(HttpServerRequest httpServerRequest) { - return httpServerRequest.getHttpHeaderValue(RpcAttachment.SpanName.getName()); - } - -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory deleted file mode 100644 index 7c3398aefc3..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngineFactory \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory deleted file mode 100644 index b6f04f98e64..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerFactory \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder deleted file mode 100644 index a1f918dec88..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.dubbo.BraveDubboRequestInterceptorBuilder \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder deleted file mode 100644 index a559e923109..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.http.BraveOkHttpRequestResponseInterceptorBuilder \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder b/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder deleted file mode 100644 index e9a3ceb4b66..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.tracker.http.ServletFilterBuilder +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.http.BraveServletFilterBuilder \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java b/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java deleted file mode 100644 index 37882c131a9..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/java/com/alibaba/dubbo/tracker/zipkin/test/ExtensionTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.alibaba.dubbo.tracker.zipkin.test; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerEngine; -import com.alibaba.dubbo.tracker.RpcTrackerFactory; -import com.alibaba.dubbo.tracker.RpcTrackerManager; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -public class ExtensionTest { - - private static RpcTrackerEngine trackerEngine; - - @BeforeClass - public static void before(){ - URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); -// trackerEngine = RpcTrackerManager.createRpcTrackerEngine(url); - } - - @Test - public void test_rpc_factory() { - RpcTrackerFactory factory = RpcTrackerManager.getTrackerFactory(); - RpcTrackerFactory factory1 = RpcTrackerManager.getTrackerFactory(); - Assert.assertEquals(factory, factory1); - } - - @Test - public void test_create_tracker() { - URL url = URL.valueOf("dubbo://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); - RpcTracker rpcTracker1 = RpcTrackerManager.createRpcTracker(url); - Assert.assertEquals(rpcTracker, rpcTracker1); - } - - @Test - public void test_create_engine(){ - URL url = URL.valueOf("zipkin://localhost:9411?application=test&collector=http&sampler=counting&rate=0.2"); - RpcTrackerEngine trackerEngine = RpcTrackerManager.getRpcTrackerEngine(); - } -} diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter deleted file mode 100644 index 4667af8ec8a..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.rpc.Filter +++ /dev/null @@ -1,2 +0,0 @@ -clientTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveClientRpcTrackerFilter -serverTracker=com.alibaba.dubbo.tracker.zipkin.filter.BraveServerRpcTrackerFilter \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory deleted file mode 100644 index 7c3398aefc3..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerEngineFactory \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory b/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory deleted file mode 100644 index b6f04f98e64..00000000000 --- a/dubbo-tracker/dubbo-tracker-zipkin/src/test/resources/internal/com.alibaba.dubbo.tracker.RpcTrackerFactory +++ /dev/null @@ -1 +0,0 @@ -zipkin=com.alibaba.dubbo.tracker.zipkin.BraveRpcTrackerFactory \ No newline at end of file diff --git a/dubbo-tracker/pom.xml b/dubbo-tracker/pom.xml index fe0cd97f9ee..256aa503e0d 100644 --- a/dubbo-tracker/pom.xml +++ b/dubbo-tracker/pom.xml @@ -13,7 +13,7 @@ pom dubbo-tracker-api - dubbo-tracker-zipkin + \ No newline at end of file diff --git a/dubbo/pom.xml b/dubbo/pom.xml index d6de7ca64bd..10d671fb266 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -321,11 +321,11 @@ - - com.alibaba - dubbo-tracker-zipkin - ${project.parent.version} - + + + + + @@ -420,7 +420,7 @@ com.alibaba:dubbo-container-logback com.alibaba:dubbo-tracker-api - com.alibaba:dubbo-tracker-zipkin + diff --git a/pom.xml b/pom.xml index 912dd1cf3da..534a6bda8c5 100644 --- a/pom.xml +++ b/pom.xml @@ -496,6 +496,12 @@ 3.9.0 + + com.squareup.retrofit2 + retrofit + 2.1.0 + + io.zipkin.brave brave-spancollector-http @@ -514,6 +520,18 @@ 3.9.0 + + io.zipkin.brave + brave-jaxrs2 + 3.9.0 + + + + io.zipkin.brave + brave-jersey2 + 3.9.0 + + com.google.auto.value auto-value From ac44a8fadb157b35f120c0c0ef50e709770e415e Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 22 Feb 2017 23:40:38 +0800 Subject: [PATCH 27/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9RpcTrackerManager?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/config/AbstractInterfaceConfig.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java index 9966fe5fed8..6a22b3d73b7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractInterfaceConfig.java @@ -245,14 +245,14 @@ protected void initRpcTrackerManagerIfNeeded() { URL url = loadTracker(); if (url != null) { tracker.setProtocol(url.getProtocol() == null ? "zipkin" : url.getProtocol()); - RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); - RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); - RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); if (tracker.getRef() != null) { RpcTrackerManager.setRpcTrackerEngine((RpcTrackerEngine) tracker.getRef()); } else { + RpcTrackerEngineFactory rpcTrackerEngineFactory = ExtensionLoader.getExtensionLoader(RpcTrackerEngineFactory.class).getExtension(url.getProtocol()); RpcTrackerManager.createRpcTrackerEngine(rpcTrackerEngineFactory, url); } + RpcTrackerFactory rpcTrackerFactory = ExtensionLoader.getExtensionLoader(RpcTrackerFactory.class).getExtension(url.getProtocol()); + RpcTrackerManager.setRpcTrackerFactory(rpcTrackerFactory); } } From 549e320e69bb439ecfa3cf88a3cf8b76178575c6 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 25 Feb 2017 15:57:02 +0800 Subject: [PATCH 28/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9README.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 60 ++++++++++++++----------------------------------------- 1 file changed, 15 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 55c803936c7..a26e23d4ad4 100644 --- a/README.md +++ b/README.md @@ -42,63 +42,33 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 ```xml -## 依赖 - -服务链路追踪主要基于Zipkin的[brave](https://github.com/openzipkin/brave) - -```xml - - com.squareup.okhttp3 - okhttp - 3.2.0 - - - io.zipkin.brave - brave-core - 3.9.0 - +## 依赖 - - io.zipkin.brave - brave-http - 3.9.0 - +服务链路追踪主要基于Zipkin的[brave] (https://github.com/openzipkin/brave), - - io.zipkin.brave - brave-web-servlet-filter - 3.9.0 - +链路追踪功能分离到另一个项目中[nightawk] (https://github.com/YanXs/nighthawk)中,项目中需要引用 +```xml - io.zipkin.brave - brave-okhttp - 3.9.0 + com.alibaba + dubbo + 3.0.0 - io.zipkin.brave - brave-spancollector-http - 3.9.0 + xs + nightawk-core + x.x.x - io.zipkin.brave - brave-spancollector-kafka - 3.9.0 + xs + nightawk-dubbo + x.x.x +``` +以上依赖需要自己使用maven编译打包 - - io.zipkin.brave - brave-spancollector-scribe - 3.9.0 - - - com.google.auto.value - auto-value - 1.3 - -``` From 807d46d2808e48aa985e06060da3b98d5e92f2c3 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 1 Apr 2017 23:33:35 +0800 Subject: [PATCH 29/69] README.md --- README.md | 19 ++++++++++--------- pom.xml | 3 --- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a26e23d4ad4..77bf3267851 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # dubbo3 -dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) +dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) , 具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) ## dubbo3修改和增加的功能 @@ -28,6 +28,7 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 方式二: 使用方式一在dubbo内部创建tracker对象,因为目前只支持zipkin,tracker对应Brave,没有办法同其他系统,比如数据库的监控结合起来,推荐使用下面的方式 配置 + ```xml @@ -40,14 +41,13 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 -```xml +``` ## 依赖 -服务链路追踪主要基于Zipkin的[brave] (https://github.com/openzipkin/brave), - -链路追踪功能分离到另一个项目中[nightawk] (https://github.com/YanXs/nighthawk)中,项目中需要引用 +服务链路追踪主要基于Zipkin的 [brave] (https://github.com/openzipkin/brave),链路追踪功能分离到另一个项目中[nightawk] (https://github.com/YanXs/nighthawk), +项目中需要引用 ```xml @@ -57,17 +57,18 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox),具体 - xs + net.nightawk nightawk-core - x.x.x + 1.0.0.RELEASE - xs + net.nightawk nightawk-dubbo - x.x.x + 1.0.0.RELEASE ``` + 以上依赖需要自己使用maven编译打包 diff --git a/pom.xml b/pom.xml index 534a6bda8c5..f5a3619a593 100644 --- a/pom.xml +++ b/pom.xml @@ -723,9 +723,6 @@ unpack - - - From d860ed18f9e401d42c6ade7f4bb4af7556e539f0 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 1 Apr 2017 23:37:08 +0800 Subject: [PATCH 30/69] README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 77bf3267851..72d989938b9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # dubbo3 -dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) , 具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) +dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) +具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) ## dubbo3修改和增加的功能 @@ -46,7 +47,8 @@ dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) , 具体 ## 依赖 -服务链路追踪主要基于Zipkin的 [brave] (https://github.com/openzipkin/brave),链路追踪功能分离到另一个项目中[nightawk] (https://github.com/YanXs/nighthawk), +服务链路追踪主要基于Zipkin的 [brave] (https://github.com/openzipkin/brave) +链路追踪功能分离到另一个项目 [nightawk] (https://github.com/YanXs/nighthawk) 项目中需要引用 ```xml From 0c625a120c5a02f740c8daa8d84979f7968a5ea2 Mon Sep 17 00:00:00 2001 From: YanXs Date: Fri, 7 Apr 2017 20:25:46 +0800 Subject: [PATCH 31/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9bug=EF=BC=8C=E6=B2=A1?= =?UTF-8?q?=E6=9C=89=E9=85=8D=E7=BD=AE=E9=93=BE=E8=B7=AF=E8=BF=BD=E8=B8=AA?= =?UTF-8?q?=E6=97=B6=E4=BC=9A=E5=87=BA=E7=8E=B0=E7=A9=BA=E6=8C=87=E9=92=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../registry/support/AbstractRegistry.java | 131 ++++++++---------- .../support/header/HeaderExchanger.java | 16 ++- .../hessian/OkHttpConnectionFactory.java | 8 +- .../http/OkHttpInvokerRequestExecutor.java | 20 +-- 4 files changed, 82 insertions(+), 93 deletions(-) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java index f83256fa19c..89914dbf1e4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java @@ -15,28 +15,6 @@ */ package com.alibaba.dubbo.registry.support; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -48,9 +26,20 @@ import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; +import java.io.*; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + /** * AbstractRegistry. (SPI, Prototype, ThreadSafe) - * + * * @author chao.liuc * @author william.liangf */ @@ -77,8 +66,8 @@ public abstract class AbstractRegistry implements Registry { private final ExecutorService registryCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveRegistryCache", true)); //是否是同步保存文件 - private final boolean syncSaveFile ; - + private final boolean syncSaveFile; + private final AtomicLong lastCacheChanged = new AtomicLong(); private final Set registered = new ConcurrentHashSet(); @@ -95,8 +84,8 @@ public AbstractRegistry(URL url) { File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); - if(! file.exists() && file.getParentFile() != null && ! file.getParentFile().exists()){ - if(! file.getParentFile().mkdirs()){ + if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { + if (!file.getParentFile().mkdirs()) { throw new IllegalArgumentException("Invalid registry store file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!"); } } @@ -137,22 +126,24 @@ public Properties getCacheProperties() { return properties; } - public AtomicLong getLastCacheChanged(){ + public AtomicLong getLastCacheChanged() { return lastCacheChanged; } - private class SaveProperties implements Runnable{ + private class SaveProperties implements Runnable { private long version; - private SaveProperties(long version){ + + private SaveProperties(long version) { this.version = version; } + public void run() { doSaveProperties(version); } } - + public void doSaveProperties(long version) { - if(version < lastCacheChanged.get()){ + if (version < lastCacheChanged.get()) { return; } if (file == null) { @@ -176,35 +167,35 @@ public void doSaveProperties(long version) { logger.warn(e.getMessage(), e); } } - } - // 保存 + } + // 保存 try { - newProperties.putAll(properties); + newProperties.putAll(properties); File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { - lockfile.createNewFile(); + lockfile.createNewFile(); } RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); try { FileChannel channel = raf.getChannel(); try { FileLock lock = channel.tryLock(); - if (lock == null) { + if (lock == null) { throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } - // 保存 + // 保存 try { - if (! file.exists()) { + if (!file.exists()) { file.createNewFile(); } - FileOutputStream outputFile = new FileOutputStream(file); + FileOutputStream outputFile = new FileOutputStream(file); try { newProperties.store(outputFile, "Dubbo Registry Cache"); } finally { - outputFile.close(); + outputFile.close(); } } finally { - lock.release(); + lock.release(); } } finally { channel.close(); @@ -269,7 +260,7 @@ public List lookup(URL url) { if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List urls : notifiedUrls.values()) { for (URL u : urls) { - if (! Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { + if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } @@ -285,7 +276,7 @@ public void notify(List urls) { List urls = reference.get(); if (urls != null && urls.size() > 0) { for (URL u : urls) { - if (! Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { + if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } @@ -298,7 +289,7 @@ public void register(URL url) { if (url == null) { throw new IllegalArgumentException("register url == null"); } - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info("Register: " + url); } registered.add(url); @@ -308,7 +299,7 @@ public void unregister(URL url) { if (url == null) { throw new IllegalArgumentException("unregister url == null"); } - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info("Unregister: " + url); } registered.remove(url); @@ -321,7 +312,7 @@ public void subscribe(URL url, NotifyListener listener) { if (listener == null) { throw new IllegalArgumentException("subscribe listener == null"); } - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info("Subscribe: " + url); } Set listeners = subscribed.get(url); @@ -339,7 +330,7 @@ public void unsubscribe(URL url, NotifyListener listener) { if (listener == null) { throw new IllegalArgumentException("unsubscribe listener == null"); } - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info("Unsubscribe: " + url); } Set listeners = subscribed.get(url); @@ -351,7 +342,7 @@ public void unsubscribe(URL url, NotifyListener listener) { protected void recover() throws Exception { // register Set recoverRegistered = new HashSet(getRegistered()); - if (! recoverRegistered.isEmpty()) { + if (!recoverRegistered.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover register url " + recoverRegistered); } @@ -361,7 +352,7 @@ protected void recover() throws Exception { } // subscribe Map> recoverSubscribed = new HashMap>(getSubscribed()); - if (! recoverSubscribed.isEmpty()) { + if (!recoverSubscribed.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover subscribe url " + recoverSubscribed.keySet()); } @@ -384,22 +375,22 @@ protected static List filterEmpty(URL url, List urls) { } protected void notify(List urls) { - if(urls == null || urls.isEmpty()) return; - + if (urls == null || urls.isEmpty()) return; + for (Map.Entry> entry : getSubscribed().entrySet()) { URL url = entry.getKey(); - - if(! UrlUtils.isMatch(url, urls.get(0))) { + + if (!UrlUtils.isMatch(url, urls.get(0))) { continue; } - + Set listeners = entry.getValue(); if (listeners != null) { for (NotifyListener listener : listeners) { try { notify(url, listener, filterEmpty(url, urls)); } catch (Throwable t) { - logger.error("Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t); + logger.error("Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t); } } } @@ -413,8 +404,8 @@ protected void notify(URL url, NotifyListener listener, List urls) { if (listener == null) { throw new IllegalArgumentException("notify listener == null"); } - if ((urls == null || urls.size() == 0) - && ! Constants.ANY_VALUE.equals(url.getServiceInterface())) { + if ((urls == null || urls.size() == 0) + && !Constants.ANY_VALUE.equals(url.getServiceInterface())) { logger.warn("Ignore empty notify urls for subscribe url " + url); return; } @@ -424,13 +415,13 @@ protected void notify(URL url, NotifyListener listener, List urls) { Map> result = new HashMap>(); for (URL u : urls) { if (UrlUtils.isMatch(url, u)) { - String category = u.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); - List categoryList = result.get(category); - if (categoryList == null) { - categoryList = new ArrayList(); - result.put(category, categoryList); - } - categoryList.add(u); + String category = u.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); + List categoryList = result.get(category); + if (categoryList == null) { + categoryList = new ArrayList(); + result.put(category, categoryList); + } + categoryList.add(u); } } if (result.size() == 0) { @@ -454,7 +445,7 @@ private void saveProperties(URL url) { if (file == null) { return; } - + try { StringBuilder buf = new StringBuilder(); Map> categoryNotified = notified.get(url); @@ -481,11 +472,11 @@ private void saveProperties(URL url) { } public void destroy() { - if (logger.isInfoEnabled()){ + if (logger.isInfoEnabled()) { logger.info("Destroy registry:" + getUrl()); } Set destroyRegistered = new HashSet(getRegistered()); - if (! destroyRegistered.isEmpty()) { + if (!destroyRegistered.isEmpty()) { for (URL url : new HashSet(getRegistered())) { if (url.getParameter(Constants.DYNAMIC_KEY, true)) { try { @@ -500,7 +491,7 @@ public void destroy() { } } Map> destroySubscribed = new HashMap>(getSubscribed()); - if (! destroySubscribed.isEmpty()) { + if (!destroySubscribed.isEmpty()) { for (Map.Entry> entry : destroySubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { @@ -510,7 +501,7 @@ public void destroy() { logger.info("Destroy unsubscribe url " + url); } } catch (Throwable t) { - logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " +t.getMessage(), t); + logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 21acf807e04..50106df1c56 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -44,18 +44,22 @@ public void setDubboRequestInterceptorBuilder(DubboRequestInterceptorBuilder dub public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); - Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); - if (interceptor != null) { - headerExchangeClient.addInterceptor(interceptor); + if (dubboRequestInterceptorBuilder != null) { + Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); + if (interceptor != null) { + headerExchangeClient.addInterceptor(interceptor); + } } return headerExchangeClient; } public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { HeaderExchangeHandler exchangeHandler = new HeaderExchangeHandler(handler); - Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); - if (interceptor != null) { - exchangeHandler.addInterceptor(interceptor); + if (dubboRequestInterceptorBuilder != null) { + Interceptor interceptor = dubboRequestInterceptorBuilder.build(url, DubboRequestSpanNameProvider.getInstance()); + if (interceptor != null) { + exchangeHandler.addInterceptor(interceptor); + } } return new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(exchangeHandler))); } diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java index 949bcc56825..db56e12e85d 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java +++ b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/com/alibaba/dubbo/rpc/protocol/hessian/OkHttpConnectionFactory.java @@ -23,9 +23,11 @@ public OkHttpConnectionFactory(com.alibaba.dubbo.common.URL url, HttpRequestResp OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); - Interceptor interceptor = requestResponseInterceptorBuilder.build(url); - if (interceptor != null) { - builder.addInterceptor(interceptor); + if (requestResponseInterceptorBuilder != null) { + Interceptor interceptor = requestResponseInterceptorBuilder.build(url); + if (interceptor != null) { + builder.addInterceptor(interceptor); + } } client = builder.build(); } diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java index 2b64f9e0497..13ca3b53469 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/OkHttpInvokerRequestExecutor.java @@ -2,8 +2,6 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.tracker.RpcTracker; -import com.alibaba.dubbo.tracker.RpcTrackerManager; import com.alibaba.dubbo.tracker.http.HttpRequestResponseInterceptorBuilder; import okhttp3.*; import org.springframework.context.i18n.LocaleContext; @@ -24,18 +22,12 @@ public OkHttpInvokerRequestExecutor(URL url, HttpRequestResponseInterceptorBuild OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); builder.connectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); - RpcTracker rpcTracker = RpcTrackerManager.createRpcTracker(url); -// if (rpcTracker != null) { -// builder.addInterceptor(new BraveOkHttpRequestResponseInterceptor(rpcTracker, HttpSpanNameProvider.getInstance())); -// builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); -// } -// Interceptor interceptor = requestResponseInterceptorBuilder.build(url); -// if (interceptor != null) { -// builder.addInterceptor(interceptor); -// if (RpcTrackerManager.getRpcTracker(url) != null) { -// builder.addInterceptor(AttachMethodNameInterceptor.getInstance()); -// } -// } + if (requestResponseInterceptorBuilder != null) { + Interceptor interceptor = requestResponseInterceptorBuilder.build(url); + if (interceptor != null) { + builder.addInterceptor(interceptor); + } + } client = builder.build(); } From 51816193363b84cfc602c4144a2601fe5204b734 Mon Sep 17 00:00:00 2001 From: YanXs Date: Thu, 13 Apr 2017 19:16:36 +0800 Subject: [PATCH 32/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9InvokerInvocationHandle?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/proxy/InvokerInvocationHandler.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java index 1049ade7d76..c12eb5b62b7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -17,9 +17,14 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; /** * InvokerHandler @@ -28,13 +33,16 @@ */ public class InvokerInvocationHandler implements InvocationHandler { + private static final ListeningExecutorService asyncExecutor = + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32)); + private final Invoker invoker; public InvokerInvocationHandler(Invoker handler) { this.invoker = handler; } - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); if (method.getDeclaringClass() == Object.class) { @@ -49,7 +57,26 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl if ("equals".equals(methodName) && parameterTypes.length == 1) { return invoker.equals(args[0]); } - return invoker.invoke(new RpcInvocation(method, args)).recreate(); + if (isAsyncMethod(method)) { + return asyncExecutor.submit(new Callable() { + @Override + public Object call() throws Exception { + return getCorrespondingSyncMethod(proxy.getClass(), method).invoke(proxy, args); + } + }); + } else { + return invoker.invoke(new RpcInvocation(method, args)).recreate(); + } + } + + private boolean isAsyncMethod(Method method) { + return Future.class.isAssignableFrom(method.getReturnType()); } + private Method getCorrespondingSyncMethod(Class clazz, Method method) throws Exception { + String methodName = method.getName(); + Class[] parameterTypes = method.getParameterTypes(); + String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); + return clazz.getDeclaredMethod(syncMethodName, parameterTypes); + } } \ No newline at end of file From cbbd606bb3b2e98ec29a82ed8a1407194615cfcd Mon Sep 17 00:00:00 2001 From: YanXs Date: Fri, 14 Apr 2017 11:04:27 +0800 Subject: [PATCH 33/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9dubbo=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=96=B9=E5=BC=8F=EF=BC=8C=E5=88=A0=E6=8E=89?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E7=9A=84=E7=B1=BB=EF=BC=8CDefuture,ResponseF?= =?UTF-8?q?uture.java,=20ResponseCallback.java,=20FutureFilter.java,=20Fut?= =?UTF-8?q?ureAdapter.java=E7=AD=89=20=E5=8E=BB=E6=8E=89rpc-thrift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../support/FailSafeClusterInvokerTest.java | 1 - .../support/FailbackClusterInvokerTest.java | 2 - .../support/FailfastClusterInvokerTest.java | 125 +- .../alibaba/dubbo/config/ReferenceConfig.java | 49 +- .../alibaba/dubbo/demo/bid/BidService.java | 11 +- .../dubbo/demo/consumer/DemoAction.java | 25 +- .../META-INF/spring/dubbo-demo-consumer.xml | 12 +- .../dubbo/demo/bid/BidServiceImpl.java | 8 +- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../dubbo/demo/provider/DemoProvider.java | 4 +- .../dubbo/registry/dubbo/MockChannel.java | 17 +- .../dubbo/registry/dubbo/MockedClient.java | 40 +- .../remoting/exchange/ExchangeChannel.java | 25 +- .../remoting/exchange/ResponseCallback.java | 39 - .../remoting/exchange/ResponseFuture.java | 61 - .../exchange/support/DefaultFuture.java | 321 -- .../exchange/support/SimpleFuture.java | 56 - .../support/header/HeaderExchangeChannel.java | 42 +- .../support/header/HeaderExchangeClient.java | 17 +- .../support/header/HeaderExchangeHandler.java | 12 +- .../support/header/HeaderExchangeServer.java | 15 +- .../java/com/alibaba/dubbo/remoting/Main.java | 133 - .../remoting/PerformanceClientFixedTest.java | 136 - .../dubbo/remoting/PerformanceClientMain.java | 28 - .../dubbo/remoting/PerformanceClientTest.java | 230 - .../transport/codec/CodecAdapterTest.java | 17 - .../codec/DeprecatedExchangeCodec.java | 388 -- .../transport/mina/ClientToServerTest.java | 49 +- .../transport/netty/ClientToServerTest.java | 49 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 5 + .../com/alibaba/dubbo/rpc/RpcContext.java | 194 - .../com/alibaba/dubbo/rpc/StaticContext.java | 74 +- .../rpc/filter/ConsumerContextFilterTest.java | 2 - .../dubbo/rpc/filter/ContextFilterTest.java | 2 - .../protocol/dubbo/ChannelWrappedInvoker.java | 4 +- .../rpc/protocol/dubbo/DubboInvoker.java | 9 +- .../rpc/protocol/dubbo/FutureAdapter.java | 83 - .../dubbo/LazyConnectExchangeClient.java | 26 +- .../dubbo/ReferenceCountExchangeClient.java | 20 +- .../protocol/dubbo/filter/FutureFilter.java | 201 - .../rpc/protocol/dubbo/FutureFilterTest.java | 83 - .../protocol/dubbo/ImplicitCallBackTest.java | 373 -- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 79 - .../protocol/thrift/ClassNameGenerator.java | 28 - .../thrift/DubboClassNameGenerator.java | 31 - .../thrift/ThriftClassNameGenerator.java | 31 - .../rpc/protocol/thrift/ThriftCodec.java | 693 --- .../rpc/protocol/thrift/ThriftConstants.java | 15 - .../rpc/protocol/thrift/ThriftInvoker.java | 126 - .../protocol/thrift/ThriftNativeCodec.java | 79 - .../rpc/protocol/thrift/ThriftProtocol.java | 213 - .../dubbo/rpc/protocol/thrift/ThriftType.java | 34 - .../rpc/protocol/thrift/ThriftUtils.java | 132 - .../thrift/ext/MultiServiceProcessor.java | 122 - .../thrift/io/InputStreamWrapper.java | 75 - .../io/RandomAccessByteArrayOutputStream.java | 107 - .../com.alibaba.dubbo.remoting.Codec2 | 1 - .../internal/com.alibaba.dubbo.rpc.Protocol | 1 - ...bbo.rpc.protocol.thrift.ClassNameGenerator | 2 - .../test/java/$__ClassNameTestDubboStub.java | 658 --- .../src/test/java/ClassNameTest.java | 45 - .../src/test/java/ClassNameTestDubbo.java | 27 - .../src/test/java/ClassNameTestThrift.java | 757 --- .../dubbo/rpc/gen/dubbo/$__DemoStub.java | 4376 --------------- .../com/alibaba/dubbo/rpc/gen/dubbo/Demo.java | 41 - .../alibaba/dubbo/rpc/gen/thrift/Demo.java | 4805 ----------------- .../rpc/protocol/thrift/AbstractTest.java | 137 - .../dubbo/rpc/protocol/thrift/DemoImpl.java | 56 - .../rpc/protocol/thrift/DubboDemoImpl.java | 22 - .../thrift/FramedTransportFactory.java | 30 - .../rpc/protocol/thrift/MockedChannel.java | 97 - .../protocol/thrift/ServerExceptionTest.java | 99 - .../thrift/ServiceMethodNotFoundTest.java | 151 - .../rpc/protocol/thrift/ThriftCodecTest.java | 453 -- .../rpc/protocol/thrift/ThriftDemoImpl.java | 22 - .../protocol/thrift/ThriftProtocolTest.java | 90 - .../rpc/protocol/thrift/ThriftUtilsTest.java | 88 - .../thrift/examples/DubboDemoConsumer.java | 24 - .../thrift/examples/DubboDemoProvider.java | 18 - .../test/resources/dubbo-demo-consumer.xml | 17 - .../test/resources/dubbo-demo-provider.xml | 19 - .../src/test/thrift/ClassNameTestDubbo.thrift | 3 - .../test/thrift/ClassNameTestThrift.thrift | 3 - .../src/test/thrift/Demo.thrift | 16 - dubbo-rpc/pom.xml | 1 - ...impleProcessorBenchmarkClientRunnable.java | 1 - .../dubbo/examples/async/AsyncConsumer.java | 58 - .../heartbeat/HeartBeatExchangeHandler.java | 4 +- dubbo/pom.xml | 8 - pom.xml | 3 +- 90 files changed, 206 insertions(+), 16682 deletions(-) delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientFixedTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientMain.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java delete mode 100644 dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java delete mode 100644 dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java delete mode 100644 dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureFilterTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift delete mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java index 5d96da77c03..ad582b54a15 100644 --- a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java @@ -94,7 +94,6 @@ public void testInvokeExceptoin() { resetInvokerToException(); FailsafeClusterInvoker invoker = new FailsafeClusterInvoker(dic); invoker.invoke(invocation); - Assert.assertNull(RpcContext.getContext().getInvoker()); } @Test() diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java index 8ad9065c6eb..4c48fd22d59 100644 --- a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java @@ -98,7 +98,6 @@ public void testInvokeExceptoin() { FailbackClusterInvoker invoker = new FailbackClusterInvoker( dic); invoker.invoke(invocation); - Assert.assertNull(RpcContext.getContext().getInvoker()); } @Test() @@ -143,7 +142,6 @@ public void testRetryFailed() { FailbackClusterInvoker invoker = new FailbackClusterInvoker( dic); invoker.invoke(invocation); - Assert.assertNull(RpcContext.getContext().getInvoker()); invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked invoker,so // it can be invoke successfully } diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java index 72fdb8a6b14..52fca7ff0bb 100644 --- a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java @@ -1,42 +1,42 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.cluster.support; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.Assert; - -import org.easymock.EasyMock; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.cluster.Directory; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcContext; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.cluster.Directory; /** * FailfastClusterInvokerTest @@ -95,7 +95,6 @@ public void testInvokeExceptoin() { resetInvoker1ToException(); FailfastClusterInvoker invoker = new FailfastClusterInvoker(dic); invoker.invoke(invocation); - Assert.assertSame(invoker1, RpcContext.getContext().getInvoker()); } @Test() @@ -106,30 +105,30 @@ public void testInvokeNoExceptoin() { FailfastClusterInvoker invoker = new FailfastClusterInvoker(dic); Result ret = invoker.invoke(invocation); Assert.assertSame(result, ret); - } - - @Test() - public void testNoInvoke() { - dic = EasyMock.createMock(Directory.class); - - EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes(); - EasyMock.expect(dic.list(invocation)).andReturn(null).anyTimes(); - EasyMock.expect(dic.getInterface()).andReturn(FailfastClusterInvokerTest.class).anyTimes(); - - invocation.setMethodName("method1"); - EasyMock.replay(dic); - - invokers.add(invoker1); - - resetInvoker1ToNoException(); - - FailfastClusterInvoker invoker = new FailfastClusterInvoker(dic); - try { - invoker.invoke(invocation); - fail(); - } catch (RpcException expected) { - assertFalse(expected.getCause() instanceof RpcException); - } - } + } + + @Test() + public void testNoInvoke() { + dic = EasyMock.createMock(Directory.class); + + EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes(); + EasyMock.expect(dic.list(invocation)).andReturn(null).anyTimes(); + EasyMock.expect(dic.getInterface()).andReturn(FailfastClusterInvokerTest.class).anyTimes(); + + invocation.setMethodName("method1"); + EasyMock.replay(dic); + + invokers.add(invoker1); + + resetInvoker1ToNoException(); + + FailfastClusterInvoker invoker = new FailfastClusterInvoker(dic); + try { + invoker.invoke(invocation); + fail(); + } catch (RpcException expected) { + assertFalse(expected.getCause() instanceof RpcException); + } + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index a801279685b..bc17178af99 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -22,14 +22,12 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.ConfigUtils; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Protocol; import com.alibaba.dubbo.rpc.ProxyFactory; -import com.alibaba.dubbo.rpc.StaticContext; import com.alibaba.dubbo.rpc.cluster.Cluster; import com.alibaba.dubbo.rpc.cluster.directory.StaticDirectory; import com.alibaba.dubbo.rpc.cluster.support.AvailableCluster; @@ -41,7 +39,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.lang.reflect.Method; import java.util.*; /** @@ -290,59 +287,19 @@ private void init() { } } appendAttributes(attributes, method, prifix + "." + method.getName()); - checkAndConvertImplicitConfig(method, map, attributes); } } - //attributes通过系统context进行存储. - StaticContext.getSystemContext().putAll(attributes); ref = createProxy(map); } - private static void checkAndConvertImplicitConfig(MethodConfig method, Map map, Map attributes) { - //check config conflict - if (Boolean.FALSE.equals(method.isReturn()) && (method.getOnreturn() != null || method.getOnthrow() != null)) { - throw new IllegalStateException("method config error : return attribute must be set true when onreturn or onthrow has been setted."); - } - //convert onreturn methodName to Method - String onReturnMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_RETURN_METHOD_KEY); - Object onReturnMethod = attributes.get(onReturnMethodKey); - if (onReturnMethod != null && onReturnMethod instanceof String) { - attributes.put(onReturnMethodKey, getMethodByName(method.getOnreturn().getClass(), onReturnMethod.toString())); - } - //convert onthrow methodName to Method - String onThrowMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_THROW_METHOD_KEY); - Object onThrowMethod = attributes.get(onThrowMethodKey); - if (onThrowMethod != null && onThrowMethod instanceof String) { - attributes.put(onThrowMethodKey, getMethodByName(method.getOnthrow().getClass(), onThrowMethod.toString())); - } - //convert oninvoke methodName to Method - String onInvokeMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_INVOKE_METHOD_KEY); - Object onInvokeMethod = attributes.get(onInvokeMethodKey); - if (onInvokeMethod != null && onInvokeMethod instanceof String) { - attributes.put(onInvokeMethodKey, getMethodByName(method.getOninvoke().getClass(), onInvokeMethod.toString())); - } - } - - private static Method getMethodByName(Class clazz, String methodName) { - try { - return ReflectUtils.findMethodByMethodName(clazz, methodName); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) private T createProxy(Map map) { URL tmpUrl = new URL("temp", "localhost", 0, map); final boolean isJvmRefer; if (isInjvm() == null) { - if (url != null && url.length() > 0) { - //指定URL的情况下,不做本地引用 - isJvmRefer = false; - } else { - //默认情况下如果本地有服务暴露,则引用本地服务. - isJvmRefer = InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl); - } + //指定URL的情况下,不做本地引用 + isJvmRefer = !(url != null && url.length() > 0) && InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl); + //默认情况下如果本地有服务暴露,则引用本地服务. } else { isJvmRefer = isInjvm(); } diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java index 31ed65d0ad4..ad6bbc974c6 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,8 @@ public interface BidService { - BidResponse bid(BidRequest request); + BidResponse bid(BidRequest request); void throwNPE() throws NullPointerException; + } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java index 9a617b7a78f..2984a9dd9e9 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java @@ -15,13 +15,11 @@ */ package com.alibaba.dubbo.demo.consumer; -import java.util.ArrayList; -import java.util.List; - import com.alibaba.dubbo.demo.bid.*; -import com.alibaba.dubbo.demo.user.User; import com.alibaba.dubbo.demo.user.facade.AnotherUserRestService; -import com.alibaba.dubbo.rpc.RpcContext; + +import java.util.ArrayList; +import java.util.List; public class DemoAction { @@ -38,7 +36,7 @@ public void setAnotherUserRestService(AnotherUserRestService anotherUserRestServ } public void start() throws Exception { - BidRequest request = new BidRequest(); + final BidRequest request = new BidRequest(); Impression imp = new Impression(); imp.setBidFloor(1.1); @@ -62,14 +60,7 @@ public void start() throws Exception { device.setGeo(geo); request.setDevice(device); -// long start = System.currentTimeMillis(); - -// for (int i = 0; i < 10000; i ++) { -// System.out.println(bidService.bid(request).getId()); System.out.println("SUCCESS: got bid response id: " + bidService.bid(request).getId()); -// } - -// System.out.println(">>>>> Total time consumed:" + (System.currentTimeMillis() - start)); try { bidService.throwNPE(); @@ -77,13 +68,7 @@ public void start() throws Exception { } catch (NullPointerException e) { System.out.println("SUCCESS: caught exception " + e.getClass()); } - -// User user = new User(1L, "larrypage"); -// System.out.println("SUCCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); -// -// RpcContext.getContext().setAttachment("clientName", "demo"); -// RpcContext.getContext().setAttachment("clientImpl", "dubbox"); -// System.out.println("SUCCESS: got user " + anotherUserRestService.getUser(1L)); + Thread.sleep(2000); } } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index ff315646e8f..a00fa6ee8c9 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -1,20 +1,22 @@ - + - + + + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java index 391ffbc3a81..4ebcdd7ef2c 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java @@ -1,12 +1,12 @@ /** * Copyright 1999-2014 dangdang.com. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 1060899d556..fd7d26db8e5 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,7 +24,7 @@ - + diff --git a/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java b/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java index b00688c9efc..d884a1dde25 100644 --- a/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java +++ b/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java @@ -15,11 +15,9 @@ */ package com.alibaba.dubbo.demo.provider; -import com.alibaba.dubbo.config.ProtocolConfig; - public class DemoProvider { - public static void main(String[] args) { + public static void main(String[] args) { // new Thread(new Runnable() { // public void run() { // try { diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java index d2fa33993ab..5c33053bcd4 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockChannel.java @@ -64,29 +64,18 @@ public URL getUrl() { return null; } - public ResponseFuture send(Object request, int timeout) throws RemotingException { - return null; - } - + @Override public ChannelHandler getChannelHandler() { return null; } - public ResponseFuture request(Object request) throws RemotingException { - return null; - } - - public ResponseFuture request(Object request, int timeout) throws RemotingException { - return null; - } - @Override - public Response execute(Request request) throws RemotingException { + public Response request(Request request) throws RemotingException { return null; } @Override - public Response execute(Request request, int timeout) throws RemotingException { + public Response request(Request request, int timeout) throws RemotingException { return null; } diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java index ae43f392f5d..3c4ef04a1fa 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/MockedClient.java @@ -16,15 +16,16 @@ package com.alibaba.dubbo.registry.dubbo; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.support.Replier; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import java.net.InetSocketAddress; import java.util.Map; @@ -77,42 +78,13 @@ public void send(Object msg) throws RemotingException { this.sent = msg; } - public ResponseFuture request(Object msg) throws RemotingException { - return request(msg, 0); - } - - public ResponseFuture request(Object msg, int timeout) throws RemotingException { - this.invoked = msg; - return new ResponseFuture() { - public Object get() throws RemotingException { - return received; - } - - public Object get(int timeoutInMillis) throws RemotingException { - return received; - } - - public boolean isDone() { - return true; - } - - @Override - public void cancel() { - - } - - public void setCallback(ResponseCallback callback) { - } - }; - } - @Override - public Response execute(Request request) throws RemotingException { + public Response request(Request request) throws RemotingException { return null; } @Override - public Response execute(Request request, int timeout) throws RemotingException { + public Response request(Request request, int timeout) throws RemotingException { return null; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java index 7ff157ad0fc..3181accc28b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ExchangeChannel.java @@ -15,10 +15,10 @@ */ package com.alibaba.dubbo.remoting.exchange; -import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.Channel; /** * ExchangeChannel. (API/SPI, Prototype, ThreadSafe) @@ -27,25 +27,6 @@ */ public interface ExchangeChannel extends Channel { - /** - * send request and receive response async - * - * @param request - * @return response future - * @throws RemotingException - */ - ResponseFuture request(Object request) throws RemotingException; - - /** - * send request and receive response async - * - * @param request - * @param timeout - * @return response future - * @throws RemotingException - */ - ResponseFuture request(Object request, int timeout) throws RemotingException; - /** * send request and receive response sync * @@ -53,7 +34,7 @@ public interface ExchangeChannel extends Channel { * @return * @throws RemotingException */ - Response execute(Request request) throws RemotingException; + Response request(Request request) throws RemotingException; /** * send request and receive response sync @@ -63,7 +44,7 @@ public interface ExchangeChannel extends Channel { * @return * @throws RemotingException */ - Response execute(Request request, int timeout) throws RemotingException; + Response request(Request request, int timeout) throws RemotingException; /** * get message handler. diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java deleted file mode 100644 index efe3d8b5168..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.exchange; - -/** - * Callback - * - * @author william.liangf - */ -public interface ResponseCallback { - - /** - * done. - * - * @param response - */ - void done(Object response); - - /** - * caught exception. - * - * @param exception - */ - void caught(Throwable exception); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java deleted file mode 100644 index 7f39ef6721e..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.exchange; - -import com.alibaba.dubbo.remoting.exception.RemotingException; - -/** - * Future. (API/SPI, Prototype, ThreadSafe) - * - * @see com.alibaba.dubbo.remoting.exchange.ExchangeChannel#request(Object) - * @see com.alibaba.dubbo.remoting.exchange.ExchangeChannel#request(Object, int) - * @author qian.lei - * @author william.liangf - */ -public interface ResponseFuture { - - /** - * get result. - * - * @return result. - */ - Object get() throws RemotingException; - - /** - * get result with the specified timeout. - * - * @param timeoutInMillis timeout. - * @return result. - */ - Object get(int timeoutInMillis) throws RemotingException; - - /** - * set callback. - * - * @param callback - */ - void setCallback(ResponseCallback callback); - - /** - * check is done. - * - * @return done or not. - */ - boolean isDone(); - - void cancel(); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java deleted file mode 100644 index cc300159687..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/DefaultFuture.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.exchange.support; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exception.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * DefaultFuture. - * - * @author qian.lei - * @author chao.liuc - */ -public class DefaultFuture implements ResponseFuture { - - private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class); - - private static final Map CHANNELS = new ConcurrentHashMap(); - - private static final Map FUTURES = new ConcurrentHashMap(); - // invoke id. - private final long id; - - private final Channel channel; - - private final Request request; - - private final int timeout; - - private final Lock lock = new ReentrantLock(); - - private final Condition done = lock.newCondition(); - - private final long start = System.currentTimeMillis(); - - private volatile long sent; - - private volatile Response response; - - private volatile ResponseCallback callback; - - public DefaultFuture(Channel channel, Request request, int timeout) { - this.channel = channel; - this.request = request; - this.id = request.getId(); - this.timeout = timeout > 0 ? timeout : channel.getUrl(). - getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - // put into waiting map. - FUTURES.put(id, this); - CHANNELS.put(id, channel); - } - - /** - * 同步等待结果 - * - * @return - * @throws RemotingException - */ - @Deprecated - public Object get() throws RemotingException { - return get(timeout); - } - - @Deprecated - public Object get(int timeout) throws RemotingException { - if (timeout <= 0) { - timeout = Constants.DEFAULT_TIMEOUT; - } - if (!isDone()) { - long start = System.currentTimeMillis(); - lock.lock(); - try { - while (!isDone()) { - done.await(timeout, TimeUnit.MILLISECONDS); - if (isDone() || System.currentTimeMillis() - start > timeout) { - break; - } - } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } finally { - lock.unlock(); - } - if (!isDone()) { - throw new TimeoutException(channel, getTimeoutMessage(false)); - } - } - return returnFromResponse(); - } - - public void cancel() { - response = response.newBuilder().errorMsg("request future has been canceled.").build(); - FUTURES.remove(id); - CHANNELS.remove(id); - } - - public boolean isDone() { - return response != null; - } - - public void setCallback(ResponseCallback callback) { - if (isDone()) { - invokeCallback(callback); - } else { - boolean isDone = false; - lock.lock(); - try { - if (!isDone()) { - this.callback = callback; - } else { - isDone = true; - } - } finally { - lock.unlock(); - } - if (isDone) { - invokeCallback(callback); - } - } - } - - private void invokeCallback(ResponseCallback c) { - ResponseCallback callbackCopy = c; - if (callbackCopy == null) { - throw new NullPointerException("callback cannot be null."); - } - c = null; - Response res = response; - if (res == null) { - throw new IllegalStateException("response cannot be null. url:" + channel.getUrl()); - } - - if (res.getStatus() == Response.OK) { - try { - callbackCopy.done(res.getResult()); - } catch (Exception e) { - logger.error("callback invoke error .reasult:" + res.getResult() + ",url:" + channel.getUrl(), e); - } - } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - try { - TimeoutException te = new TimeoutException(channel, res.getErrorMessage()); - callbackCopy.caught(te); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } - } else { - try { - RuntimeException re = new RuntimeException(res.getErrorMessage()); - callbackCopy.caught(re); - } catch (Exception e) { - logger.error("callback invoke error ,url:" + channel.getUrl(), e); - } - } - } - - private Object returnFromResponse() throws RemotingException { - Response res = response; - if (res == null) { - throw new IllegalStateException("response cannot be null"); - } - if (res.getStatus() == Response.OK) { - return res.getResult(); - } - if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - throw new TimeoutException(channel, res.getErrorMessage()); - } - throw new RemotingException(channel, res.getErrorMessage()); - } - - private long getId() { - return id; - } - - private Channel getChannel() { - return channel; - } - - private boolean isSent() { - return sent > 0; - } - - public Request getRequest() { - return request; - } - - private int getTimeout() { - return timeout; - } - - private long getStartTimestamp() { - return start; - } - - public static DefaultFuture getFuture(long id) { - return FUTURES.get(id); - } - - public static boolean hasFuture(Channel channel) { - return CHANNELS.containsValue(channel); - } - - public static void sent(Channel channel, Request request) { - DefaultFuture future = FUTURES.get(request.getId()); - if (future != null) { - future.doSent(); - } - } - - private void doSent() { - sent = System.currentTimeMillis(); - } - - public static void received(Channel channel, Response response) { - try { - DefaultFuture future = FUTURES.remove(response.getId()); - if (future != null) { - future.doReceived(response); - } else { - logger.warn("The timeout response finally returned at " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) - + ", response " + response - + (channel == null ? "" : ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress())); - } - } finally { - CHANNELS.remove(response.getId()); - } - } - - private void doReceived(Response res) { - lock.lock(); - try { - response = res; - if (done != null) { - done.signal(); - } - } finally { - lock.unlock(); - } - if (callback != null) { - invokeCallback(callback); - } - } - - private String getTimeoutMessage(boolean scan) { - long nowTimestamp = System.currentTimeMillis(); - return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side") - + (scan ? " by scan timer" : "") + ". start time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + "," - + (sent > 0 ? " client elapsed: " + (sent - start) - + " ms, server elapsed: " + (nowTimestamp - sent) - : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " - + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress(); - } - - private static class RemotingInvocationTimeoutScan implements Runnable { - - public void run() { - while (true) { - try { - for (DefaultFuture future : FUTURES.values()) { - if (future == null || future.isDone()) { - continue; - } - if (System.currentTimeMillis() - future.getStartTimestamp() > future.getTimeout()) { - // create exception response. - Response.Builder builder = new Response.Builder(future.getId()); - builder.status(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); - builder.errorMsg(future.getTimeoutMessage(true)); - Response timeoutResponse = builder.build(); - // handle response. - DefaultFuture.received(future.getChannel(), timeoutResponse); - } - } - Thread.sleep(30); - } catch (Throwable e) { - logger.error("Exception when scan the timeout invocation of remoting.", e); - } - } - } - } - - static { - Thread th = new Thread(new RemotingInvocationTimeoutScan(), "DubboResponseTimeoutScanTimer"); - th.setDaemon(true); - th.start(); - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java deleted file mode 100644 index 5a3d7ea619f..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/SimpleFuture.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.exchange.support; - -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; - -/** - * SimpleFuture - * - * @author william.liangf - */ -public class SimpleFuture implements ResponseFuture { - - private final Object value; - - public SimpleFuture(Object value){ - this.value = value; - } - - public Object get() throws RemotingException { - return value; - } - - public Object get(int timeoutInMillis) throws RemotingException { - return value; - } - - public void setCallback(ResponseCallback callback) { - callback.done(value); - } - - public boolean isDone() { - return true; - } - - @Override - public void cancel() { - - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index a76d81ef74b..7fd939c6d1a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -20,14 +20,14 @@ import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exception.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.*; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; @@ -45,7 +45,7 @@ final class HeaderExchangeChannel implements ExchangeChannel { private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; - private static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); + public static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); private final Channel channel; @@ -99,36 +99,13 @@ public void send(Object message, boolean sent) throws RemotingException { } } - public ResponseFuture request(Object request) throws RemotingException { - return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - } - - public ResponseFuture request(Object request, int timeout) throws RemotingException { - if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + - ", cause: The channel " + this + " is closed!"); - } - // create request. - Request.Builder builder = new Request.Builder(); - builder.newId().version(Version.getVersion()).twoWay(true).data(request); - Request req = builder.build(); - ResponseFuture future = new DefaultFuture(channel, req, timeout); - try { - channel.send(req); - } catch (RemotingException e) { - future.cancel(); - throw e; - } - return future; - } - @Override - public Response execute(Request request) throws RemotingException { - return execute(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + public Response request(Request request) throws RemotingException { + return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); } @Override - public Response execute(Request request, int timeout) throws RemotingException { + public Response request(Request request, int timeout) throws RemotingException { if (closed) { throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); @@ -215,8 +192,7 @@ public void close(int timeout) { } private boolean shouldWait(long start, long timeout) { - return (System.currentTimeMillis() - start < timeout) && - (DefaultFuture.hasFuture(HeaderExchangeChannel.this) || !REPLY_HOLDER.isEmpty()); + return (System.currentTimeMillis() - start < timeout) && !REPLY_HOLDER.isEmpty(); } public InetSocketAddress getLocalAddress() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index dab1f38cbcd..f0b33da30c0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -24,7 +24,6 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; @@ -184,21 +183,13 @@ private void stopHeartbeatTimer() { heartbeatTimer = null; } - public ResponseFuture request(Object request) throws RemotingException { - return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - } - - public ResponseFuture request(Object request, int timeout) throws RemotingException { - return channel.request(request, timeout); - } - @Override - public Response execute(Request request) throws RemotingException { - return execute(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + public Response request(Request request) throws RemotingException { + return request(request, channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); } @Override - public Response execute(Request request, int timeout) throws RemotingException { + public Response request(Request request, int timeout) throws RemotingException { Interceptor.Chain chain = new ExchangeClientInterceptorChain(0, request, timeout); return chain.proceed(request, timeout); } @@ -245,7 +236,7 @@ public Response proceed(Request request, int timeout) throws RemotingException { } return response; } - return channel.execute(request, timeout); + return channel.request(request, timeout); } @Override diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index a7cd811ca40..8089a3a7466 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -21,15 +21,15 @@ import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.exception.ExecutionException; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate; import java.net.InetSocketAddress; @@ -133,10 +133,6 @@ public void sent(Channel channel, Object message) throws RemotingException { } catch (Throwable t) { exception = t; } - if (message instanceof Request) { - Request request = (Request) message; - DefaultFuture.sent(channel, request); - } if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index bdd93fe7e80..c25c1ffe024 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -21,14 +21,13 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.transport.Server; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.transport.Channel; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; +import com.alibaba.dubbo.remoting.transport.Server; import java.net.InetSocketAddress; import java.util.ArrayList; @@ -87,13 +86,7 @@ public boolean isClosed() { } private boolean isRunning() { - Collection channels = getChannels(); - for (Channel channel : channels) { - if (DefaultFuture.hasFuture(channel)) { - return true; - } - } - return false; + return !HeaderExchangeChannel.REPLY_HOLDER.isEmpty(); } public void close() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java deleted file mode 100644 index 59433cda032..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/Main.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.remoting.exchange.support.Replier; -import com.alibaba.dubbo.remoting.exchange.support.ReplierDispatcher; - -import java.io.Serializable; -import java.util.Random; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -/** - * Main - */ - -public class Main { - public static void main(String[] args) throws Exception { - startServer(9010); - mutliThreadTest(10, 9010); - dataPackageTest(9010); - } - - private static void startServer(int port) throws Exception { - ReplierDispatcher dispatcher = new ReplierDispatcher(); - dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); - dispatcher.addReplier(Object.class, new Replier() { - public Object reply(ExchangeChannel channel, Object msg) { - for (int i = 0; i < 10000; i++) - System.currentTimeMillis(); - System.out.println("handle:" + msg + ";thread:" + Thread.currentThread().getName()); - return new StringMessage("hello world"); - } - }); - Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); - } - - static void dataPackageTest(int port) throws Exception { - ExchangeChannel client = Exchangers.connect(URL.valueOf("dubbo://localhost:" + port)); - Random random = new Random(); - for (int i = 5; i < 100; i++) { - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < i * 100; j++) - sb.append("(" + random.nextLong() + ")"); - Main.Data d = new Main.Data(); - d.setData(sb.toString()); - client.request(d).get(); - } - System.out.println("send finished."); - } - - static void mutliThreadTest(int tc, final int port) throws Exception { - Executor exec = Executors.newFixedThreadPool(tc); - for (int i = 0; i < tc; i++) - exec.execute(new Runnable() { - public void run() { - try { - test(port); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - private static void test(int port) throws Exception { - ExchangeChannel client = Exchangers.connect(URL.valueOf("dubbo://localhost:" + port)); - MockResult result = (MockResult) client.request(new RpcMessage(DemoService.class.getName(), "plus", new Class[]{int.class, int.class}, new Object[]{55, 25})).get(); - System.out.println("55+25=" + result.getResult()); - - for (int i = 0; i < 100; i++) - client.request(new RpcMessage(DemoService.class.getName(), "sayHello", new Class[]{String.class}, new Object[]{"qianlei" + i})); - - for (int i = 0; i < 100; i++) - client.request(new Main.Data()); - - System.out.println("=====test invoke====="); - for (int i = 0; i < 100; i++) { - ResponseFuture future = client.request(new Main.Data()); - System.out.println("invoke and get"); - System.out.println("invoke result:" + future.get()); - } - System.out.println("=====the end====="); - } - - static class Data implements Serializable { - private static final long serialVersionUID = -4666580993978548778L; - - private String mData = ""; - - public Data() { - } - - public String getData() { - return mData; - } - - public void setData(String data) { - mData = data; - } - } - - static class StringMessage implements Serializable { - private static final long serialVersionUID = 7193122183120113947L; - - private String mText; - - StringMessage(String msg) { - mText = msg; - } - - public String toString() { - return mText; - } - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientFixedTest.java deleted file mode 100644 index 6b93ca686d0..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientFixedTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import java.util.ArrayList; -import java.util.Random; - -import junit.framework.TestCase; - -import org.junit.Test; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.Exchangers; - -public class PerformanceClientFixedTest extends TestCase { - - private static final Logger logger = LoggerFactory.getLogger(PerformanceClientTest.class); - - @Test - public void testClient() throws Exception { - // 读取参数 - if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); - return; - } - final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - //final int length = PerformanceUtils.getIntProperty("length", 1024); - final int connectionCount = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); - //final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); - //int r = PerformanceUtils.getIntProperty("runs", 10000); - //final int runs = r > 0 ? r : Integer.MAX_VALUE; - //final String onerror = PerformanceUtils.getProperty("onerror", "continue"); - final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; - - //int idx = server.indexOf(':'); - Random rd = new Random(connectionCount); - ArrayList arrays = new ArrayList(); - String oneKBlock = null; - String messageBlock = null; - int s = 0; - int f = 0; - System.out.println("initialize arrays " + url); - while (s < connectionCount) { - ExchangeClient client = null; - try { - System.out.println("open connection " + s + " " + url + arrays.size()); - - client = Exchangers.connect(url); - - System.out.println("run after open"); - - if (client.isConnected()) { - arrays.add(client); - s++; - System.out.println("open client success " + s); - } else { - System.out.println("open client failed, try again."); - } - } catch (Throwable t) { - t.printStackTrace(); - } finally { - if (client != null && client.isConnected() == false) { - f++; - System.out.println("open client failed, try again " + f); - client.close(); - } - } - } - - StringBuilder sb1 = new StringBuilder(); - Random rd2 = new Random(); - char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); - int size1 = numbersAndLetters.length; - for (int j = 0; j < 1024; j++) { - sb1.append(numbersAndLetters[rd2.nextInt(size1)]); - } - oneKBlock = sb1.toString(); - - for (int j = 0; j < Integer.MAX_VALUE; j++) { - try { - String size = "10"; - - int request_size = 10; - try { - request_size = Integer.parseInt(size); - } catch (Throwable t) { - request_size = 10; - } - - if (messageBlock == null) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < request_size; i++) { - sb.append(oneKBlock); - } - messageBlock = sb.toString(); - - System.out.println("set messageBlock to " + messageBlock); - } - int index = rd.nextInt(connectionCount); - ExchangeClient client = arrays.get(index); - // ExchangeClient client = arrays.get(0); - String output = (String) client.request(messageBlock).get(); - - if (output.lastIndexOf(messageBlock) < 0) { - System.out.println("send messageBlock;get " + output); - throw new Throwable("return results invalid"); - } else { - if (j % 100 == 0) - System.out.println("OK: " + j); - } - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientMain.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientMain.java deleted file mode 100644 index 18196015ddf..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientMain.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - - -/** - * PerformanceClientMain - */ -public class PerformanceClientMain { - - public static void main(String[] args) throws Throwable { - new PerformanceClientTest().testClient(); - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java deleted file mode 100644 index 442a3ff5fef..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceClientTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting; - -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import junit.framework.TestCase; - -import org.junit.Test; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; - -/** - * PerformanceClientTest - * - * mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911 - * - * @author william.liangf - */ -public class PerformanceClientTest extends TestCase { - - private static final Logger logger = LoggerFactory.getLogger(PerformanceClientTest.class); - - @Test - @SuppressWarnings("unchecked") - public void testClient() throws Throwable { - // 读取参数 - if (PerformanceUtils.getProperty("server", null) == null) { - logger.warn("Please set -Dserver=127.0.0.1:9911"); - return; - } - final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION); - final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - final int length = PerformanceUtils.getIntProperty("length", 1024); - final int connections = PerformanceUtils.getIntProperty(Constants.CONNECTIONS_KEY, 1); - final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); - int r = PerformanceUtils.getIntProperty("runs", 10000); - final int runs = r > 0 ? r : Integer.MAX_VALUE; - final String onerror = PerformanceUtils.getProperty("onerror", "continue"); - - final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; - // 创建客户端 - final ExchangeClient[] exchangeClients = new ExchangeClient[connections]; - for (int i = 0; i < connections; i ++) { - //exchangeClients[i] = Exchangers.connect(url,handler); - exchangeClients[i] = Exchangers.connect(url); - } - - List serverEnvironment = (List) exchangeClients[0].request("environment").get(); - List serverScene = (List) exchangeClients[0].request("scene").get(); - - // 制造数据 - StringBuilder buf = new StringBuilder(length); - for (int i = 0; i < length; i ++) { - buf.append("A"); - } - final String data = buf.toString(); - - // 计数器 - final AtomicLong count = new AtomicLong(); - final AtomicLong error = new AtomicLong(); - final AtomicLong time = new AtomicLong(); - final AtomicLong all = new AtomicLong(); - - // 并发调用 - final CountDownLatch latch = new CountDownLatch(concurrent); - for (int i = 0; i < concurrent; i ++) { - new Thread(new Runnable() { - public void run() { - try { - AtomicInteger index = new AtomicInteger(); - long init = System.currentTimeMillis(); - for (int i = 0; i < runs; i++) { - try { - count.incrementAndGet(); - ExchangeClient client = exchangeClients[index.getAndIncrement() % connections]; - long start = System.currentTimeMillis(); - String result = (String) client.request(data).get(); - long end = System.currentTimeMillis(); - if (! data.equals(result)) { - throw new IllegalStateException("Invalid result " + result); - } - time.addAndGet(end - start); - } catch (Exception e) { - error.incrementAndGet(); - e.printStackTrace(); - if ("exit".equals(onerror)) { - System.exit(-1); - } else if ("break".equals(onerror)) { - break; - } else if ("sleep".equals(onerror)) { - try { - Thread.sleep(30000); - } catch (InterruptedException e1) { - } - } - } - } - all.addAndGet(System.currentTimeMillis() - init); - } finally { - latch.countDown(); - } - } - }).start(); - } - - // 输出,tps不精确,但大概反映情况 - new Thread(new Runnable() { - public void run() { - try{ - SimpleDateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss"); - long lastCount = count.get(); - long sleepTime = 2000; - long elapsd = sleepTime/1000; - boolean bfirst = true; - while (latch.getCount() > 0) { - long c = count.get()-lastCount ; - if(! bfirst)//第一次不准 - System.out.println("["+dateFormat.format(new Date()) +"] count: " + count.get() + ", error: " + error.get() + ",tps:"+(c/elapsd)); - - bfirst = false; - lastCount = count.get(); - Thread.sleep(sleepTime); - } - } catch(Exception e) { - e.printStackTrace(); - } - } - }).start(); - - latch.await(); - - for(ExchangeClient client:exchangeClients){ - if(client.isConnected()){ - client.close(); - } - } - - long total = count.get(); - long failed = error.get(); - long succeeded = total - failed; - long elapsed = time.get(); - long allElapsed = all.get(); - long clientElapsed = allElapsed - elapsed; - long art = 0; - long qps = 0; - long throughput = 0; - if (elapsed > 0) { - art = elapsed / succeeded; - qps = concurrent * succeeded * 1000 / elapsed; - throughput = concurrent * succeeded * length * 2 * 1000 / elapsed; - } - - PerformanceUtils.printBorder(); - PerformanceUtils.printHeader("Dubbo Remoting Performance Test Report"); - PerformanceUtils.printBorder(); - PerformanceUtils.printHeader("Test Environment"); - PerformanceUtils.printSeparator(); - for (String item: serverEnvironment) { - PerformanceUtils.printBody("Server " + item); - } - PerformanceUtils.printSeparator(); - List clientEnvironment = PerformanceUtils.getEnvironment(); - for (String item: clientEnvironment) { - PerformanceUtils.printBody("Client " + item); - } - PerformanceUtils.printSeparator(); - PerformanceUtils.printHeader("Test Scene"); - PerformanceUtils.printSeparator(); - for (String item: serverScene) { - PerformanceUtils.printBody("Server " + item); - } - PerformanceUtils.printBody("Client Transporter: " + transporter); - PerformanceUtils.printBody("Serialization: " + serialization); - PerformanceUtils.printBody("Response Timeout: " + timeout + " ms"); - PerformanceUtils.printBody("Data Length: " + length + " bytes"); - PerformanceUtils.printBody("Client Shared Connections: " + connections); - PerformanceUtils.printBody("Client Concurrent Threads: " + concurrent); - PerformanceUtils.printBody("Run Times Per Thread: " + runs); - PerformanceUtils.printSeparator(); - PerformanceUtils.printHeader("Test Result"); - PerformanceUtils.printSeparator(); - PerformanceUtils.printBody("Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded)); - PerformanceUtils.printBody("Failed Requests: " + failed); - PerformanceUtils.printBody("Client Elapsed Time: " + clientElapsed + " ms"); - PerformanceUtils.printBody("Average Response Time: " + art + " ms"); - PerformanceUtils.printBody("Requests Per Second: " + qps + "/s"); - PerformanceUtils.printBody("Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s"); - PerformanceUtils.printBorder(); - } - - static class PeformanceTestHandler extends ExchangeHandlerAdapter{ - - public void connected(Channel channel) throws RemotingException { - System.out.println("connected event,chanel;"+channel); - } - - public void disconnected(Channel channel) throws RemotingException { - System.out.println("disconnected event,chanel;"+channel); - } - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java deleted file mode 100644 index 18250bb7579..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.alibaba.dubbo.remoting.transport.codec; - -import org.junit.Before; - -import com.alibaba.dubbo.remoting.codec.ExchangeCodecTest; - -/** - * @author kimi - */ -public class CodecAdapterTest extends ExchangeCodecTest { - - @Before - public void setUp() throws Exception { - codec = new CodecAdapter(new DeprecatedExchangeCodec()); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java deleted file mode 100644 index 51fc51fbfe2..00000000000 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java +++ /dev/null @@ -1,388 +0,0 @@ -package com.alibaba.dubbo.remoting.transport.codec; - -import com.alibaba.dubbo.common.Version; -import com.alibaba.dubbo.common.io.Bytes; -import com.alibaba.dubbo.common.io.StreamUtils; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.serialize.ObjectInput; -import com.alibaba.dubbo.common.serialize.ObjectOutput; -import com.alibaba.dubbo.common.serialize.Serialization; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.remoting.transport.CodecSupport; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * @author kimi - */ -final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec { - - private static final Logger logger = LoggerFactory.getLogger(DeprecatedExchangeCodec.class); - // header length. - protected static final int HEADER_LENGTH = 16; - // magic header. - protected static final short MAGIC = (short) 0xdabb; - - protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; - - protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; - // message flag. - protected static final byte FLAG_REQUEST = (byte) 0x80; - - protected static final byte FLAG_TWOWAY = (byte) 0x40; - - protected static final byte FLAG_EVENT = (byte) 0x20; - - protected static final int SERIALIZATION_MASK = 0x1f; - - public Short getMagicCode() { - return MAGIC; - } - - public void encode(Channel channel, OutputStream os, Object msg) throws IOException { - if (msg instanceof Request) { - encodeRequest(channel, os, (Request) msg); - } else if (msg instanceof Response) { - encodeResponse(channel, os, (Response) msg); - } else { - super.encode(channel, os, msg); - } - } - - public Object decode(Channel channel, InputStream is) throws IOException { - int readable = is.available(); - byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; - is.read(header); - return decode(channel, is, readable, header); - } - - protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { - // check magic number. - if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { - int length = header.length; - if (header.length < readable) { - header = Bytes.copyOf(header, readable); - is.read(header, length, readable - length); - } - for (int i = 1; i < header.length - 1; i++) { - if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { - UnsafeByteArrayInputStream bis = ((UnsafeByteArrayInputStream) is); - bis.position(bis.position() - header.length + i); - header = Bytes.copyOf(header, i); - break; - } - } - return super.decode(channel, is, readable, header); - } - // check length. - if (readable < HEADER_LENGTH) { - return NEED_MORE_INPUT; - } - // get data length. - int len = Bytes.bytes2int(header, 12); - checkPayload(channel, len); - int tt = len + HEADER_LENGTH; - if (readable < tt) { - return NEED_MORE_INPUT; - } - // limit input stream. - if (readable != tt) { - is = StreamUtils.limitedInputStream(is, len); - } - try { - return decodeBody(channel, is, header); - } finally { - if (is.available() > 0) { - try { - if (logger.isWarnEnabled()) { - logger.warn("Skip input stream " + is.available()); - } - StreamUtils.skipUnusedStream(is); - } catch (IOException e) { - logger.warn(e.getMessage(), e); - } - } - } - } - - protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { - byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); - Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto); - ObjectInput in = s.deserialize(channel.getUrl(), is); - // get request id. - long id = Bytes.bytes2long(header, 4); - if ((flag & FLAG_REQUEST) == 0) { - // decode response. - Response.Builder builder = new Response.Builder(id); - boolean isEvent = (flag & FLAG_EVENT) != 0; - builder.isEvent(isEvent); - if (isEvent) { - builder.result(Response.HEARTBEAT_EVENT); - } - // get status. - byte status = header[3]; - builder.status(status); - Response res = builder.build(); - if (status == Response.OK) { - try { - Object data; - if (isEvent) { - data = decodeEventData(channel, in); - } else { - data = decodeResponseData(channel, in, getRequestData(id)); - } - res = res.newBuilder().result(data).build(); - } catch (Throwable t) { - res = res.newBuilder().status(Response.CLIENT_ERROR).errorMsg(StringUtils.toString(t)).build(); - } - } else { - res = res.newBuilder().errorMsg(in.readUTF()).build(); - } - return res; - } else { - // decode request. - Request.Builder builder = new Request.Builder(id); - builder.version(Version.getVersion()); - builder.twoWay((flag & FLAG_TWOWAY) != 0); - boolean isEvent = (flag & FLAG_EVENT) != 0; - if (isEvent) { - builder.isEvent(true).data(Request.HEARTBEAT_EVENT); - } - try { - Object data; - if (isEvent) { - data = decodeEventData(channel, in); - } else { - data = decodeRequestData(channel, in); - } - builder.data(data); - } catch (Throwable t) { - // bad request - builder.broken(true).data(t); - } - return builder.build(); - } - } - - protected Object getRequestData(long id) { - DefaultFuture future = DefaultFuture.getFuture(id); - if (future == null) - return null; - Request req = future.getRequest(); - if (req == null) - return null; - return req.getData(); - } - - protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException { - Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); - // header. - byte[] header = new byte[HEADER_LENGTH]; - // set magic number. - Bytes.short2bytes(MAGIC, header); - - // set request and serialization flag. - header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); - - if (req.isTwoWay()) header[2] |= FLAG_TWOWAY; - if (req.isEvent()) header[2] |= FLAG_EVENT; - - // set request id. - Bytes.long2bytes(req.getId(), header, 4); - - // encode request data. - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); - ObjectOutput out = serialization.serialize(channel.getUrl(), bos); - if (req.isEvent()) { - encodeEventData(channel, out, req.getData()); - } else { - encodeRequestData(channel, out, req.getData()); - } - out.flushBuffer(); - bos.flush(); - bos.close(); - byte[] data = bos.toByteArray(); - checkPayload(channel, data.length); - Bytes.int2bytes(data.length, header, 12); - - // write - os.write(header); // write header. - os.write(data); // write data. - } - - protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException { - try { - Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); - // header. - byte[] header = new byte[HEADER_LENGTH]; - // set magic number. - Bytes.short2bytes(MAGIC, header); - // set request and serialization flag. - header[2] = serialization.getContentTypeId(); - if (res.isHeartbeat()) header[2] |= FLAG_EVENT; - // set response status. - byte status = res.getStatus(); - header[3] = status; - // set request id. - Bytes.long2bytes(res.getId(), header, 4); - - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); - ObjectOutput out = serialization.serialize(channel.getUrl(), bos); - // encode response data or error message. - if (status == Response.OK) { - if (res.isHeartbeat()) { - encodeEventData(channel, out, res.getResult()); - } else { - encodeResponseData(channel, out, res.getResult()); - } - } else out.writeUTF(res.getErrorMessage()); - out.flushBuffer(); - bos.flush(); - bos.close(); - - byte[] data = bos.toByteArray(); - checkPayload(channel, data.length); - Bytes.int2bytes(data.length, header, 12); - // write - os.write(header); // write header. - os.write(data); // write data. - } catch (Throwable t) { - // 发送失败信息给Consumer,否则Consumer只能等超时了 - if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { - try { - // FIXME 在Codec中打印出错日志?在IoHanndler的caught中统一处理? - logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); - Response r = res.newBuilder(). - status(Response.BAD_RESPONSE). - errorMsg("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)). - build(); - channel.send(r); - return; - } catch (RemotingException e) { - logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); - } - } - - // 重新抛出收到的异常 - if (t instanceof IOException) { - throw (IOException) t; - } else if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else { - throw (Error) t; - } - } - } - - protected Object decodeData(ObjectInput in) throws IOException { - return decodeRequestData(in); - } - - @Deprecated - protected Object decodeHeartbeatData(ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - - protected Object decodeRequestData(ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - - protected Object decodeResponseData(ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - - protected void encodeData(ObjectOutput out, Object data) throws IOException { - encodeRequestData(out, data); - } - - private void encodeEventData(ObjectOutput out, Object data) throws IOException { - out.writeObject(data); - } - - @Deprecated - protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { - encodeEventData(out, data); - } - - protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { - out.writeObject(data); - } - - protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { - out.writeObject(data); - } - - protected Object decodeData(Channel channel, ObjectInput in) throws IOException { - return decodeRequestData(channel, in); - } - - protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - - @Deprecated - protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { - try { - return in.readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(StringUtils.toString("Read object failed.", e)); - } - } - - protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { - return decodeRequestData(in); - } - - protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException { - return decodeResponseData(in); - } - - protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { - return decodeResponseData(channel, in); - } - - protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeRequestData(channel, out, data); - } - - private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeEventData(out, data); - } - - protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeRequestData(out, data); - } - - protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { - encodeResponseData(out, data); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java index 13360386458..0e273fc781f 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/test/java/com/alibaba/remoting/transport/mina/ClientToServerTest.java @@ -15,36 +15,31 @@ */ package com.alibaba.remoting.transport.mina; -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.junit.Test; - import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.remoting.exchange.support.Replier; +import junit.framework.TestCase; /** * ClientToServer - * + * * @author william.liangf */ public abstract class ClientToServerTest extends TestCase { - + protected static final String LOCALHOST = "127.0.0.1"; - + protected ExchangeServer server; - + protected ExchangeChannel client; - + protected WorldHandler handler = new WorldHandler(); - + protected abstract ExchangeServer newServer(int port, Replier receiver) throws RemotingException; - + protected abstract ExchangeChannel newClient(int port) throws RemotingException; - + @Override protected void setUp() throws Exception { super.setUp(); @@ -64,30 +59,4 @@ protected void tearDown() throws Exception { client.close(); } } - - @Test - public void testFuture() throws Exception { - ResponseFuture future = client.request(new World("world")); - Hello result = (Hello)future.get(); - Assert.assertEquals("hello,world", result.getName()); - } - -// @Test -// public void testCallback() throws Exception { -// final Object waitter = new Object(); -// client.invoke(new World("world"), new InvokeCallback() { -// public void callback(Hello result) { -// Assert.assertEquals("hello,world", result.getName()); -// synchronized (waitter) { -// waitter.notifyAll(); -// } -// } -// public void onException(Throwable exception) { -// } -// }); -// synchronized (waitter) { -// waitter.wait(); -// } -// } - } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java index e3306bdf83f..e27d081772c 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ClientToServerTest.java @@ -15,36 +15,31 @@ */ package com.alibaba.dubbo.remoting.transport.netty; -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.junit.Test; - import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.remoting.exchange.support.Replier; +import junit.framework.TestCase; /** * ClientToServer - * + * * @author william.liangf */ public abstract class ClientToServerTest extends TestCase { - + protected static final String LOCALHOST = "127.0.0.1"; - + protected ExchangeServer server; - + protected ExchangeChannel client; - + protected WorldHandler handler = new WorldHandler(); - + protected abstract ExchangeServer newServer(int port, Replier receiver) throws RemotingException; - + protected abstract ExchangeChannel newClient(int port) throws RemotingException; - + @Override protected void setUp() throws Exception { super.setUp(); @@ -64,30 +59,4 @@ protected void tearDown() throws Exception { client.close(); } } - - @Test - public void testFuture() throws Exception { - ResponseFuture future = client.request(new World("world")); - Hello result = (Hello)future.get(); - Assert.assertEquals("hello,world", result.getName()); - } - -// @Test -// public void testCallback() throws Exception { -// final Object waitter = new Object(); -// client.invoke(new World("world"), new InvokeCallback() { -// public void callback(Hello result) { -// Assert.assertEquals("hello,world", result.getName()); -// synchronized (waitter) { -// waitter.notifyAll(); -// } -// } -// public void onException(Throwable exception) { -// } -// }); -// synchronized (waitter) { -// waitter.wait(); -// } -// } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 9dc31083291..dfb857ffdd2 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -34,5 +34,10 @@ dubbo-common ${project.parent.version} + + com.google.guava + guava + 16.0.1 + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index f24d21c094a..5779cc649c2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -42,7 +42,6 @@ protected RpcContext initialValue() { return new RpcContext(); } }; - /** * get context. * @@ -61,8 +60,6 @@ public static void removeContext() { LOCAL.remove(); } - private Future future; - private List urls; private URL url; @@ -86,14 +83,6 @@ public static void removeContext() { private Object request; private Object response; - @Deprecated - private List> invokers; - - @Deprecated - private Invoker invoker; - - @Deprecated - private Invocation invocation; protected RpcContext() { } @@ -145,74 +134,6 @@ public void setResponse(Object response) { this.response = response; } - /** - * is provider side. - * - * @return provider side. - */ - public boolean isProviderSide() { - URL url = getUrl(); - if (url == null) { - return false; - } - InetSocketAddress address = getRemoteAddress(); - if (address == null) { - return false; - } - String host; - if (address.getAddress() == null) { - host = address.getHostName(); - } else { - host = address.getAddress().getHostAddress(); - } - return url.getPort() != address.getPort() || - !NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host)); - } - - /** - * is consumer side. - * - * @return consumer side. - */ - public boolean isConsumerSide() { - URL url = getUrl(); - if (url == null) { - return false; - } - InetSocketAddress address = getRemoteAddress(); - if (address == null) { - return false; - } - String host; - if (address.getAddress() == null) { - host = address.getHostName(); - } else { - host = address.getAddress().getHostAddress(); - } - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host)); - } - - /** - * get future. - * - * @param - * @return future - */ - @SuppressWarnings("unchecked") - public Future getFuture() { - return (Future) future; - } - - /** - * set future. - * - * @param future - */ - public void setFuture(Future future) { - this.future = future; - } - public List getUrls() { return urls == null && url != null ? (List) Collections.singletonList(url) : urls; } @@ -528,7 +449,6 @@ public Object get(String key) { } public RpcContext setInvokers(List> invokers) { - this.invokers = invokers; if (invokers != null && invokers.size() > 0) { List urls = new ArrayList(invokers.size()); for (Invoker invoker : invokers) { @@ -540,7 +460,6 @@ public RpcContext setInvokers(List> invokers) { } public RpcContext setInvoker(Invoker invoker) { - this.invoker = invoker; if (invoker != null) { setUrl(invoker.getUrl()); } @@ -548,7 +467,6 @@ public RpcContext setInvoker(Invoker invoker) { } public RpcContext setInvocation(Invocation invocation) { - this.invocation = invocation; if (invocation != null) { setMethodName(invocation.getMethodName()); setParameterTypes(invocation.getParameterTypes()); @@ -557,116 +475,4 @@ public RpcContext setInvocation(Invocation invocation) { return this; } - /** - * @deprecated Replace to isProviderSide() - */ - @Deprecated - public boolean isServerSide() { - return isProviderSide(); - } - - /** - * @deprecated Replace to isConsumerSide() - */ - @Deprecated - public boolean isClientSide() { - return isConsumerSide(); - } - - /** - * @deprecated Replace to getUrls() - */ - @Deprecated - @SuppressWarnings({"unchecked", "rawtypes"}) - public List> getInvokers() { - return invokers == null && invoker != null ? (List) Collections.singletonList(invoker) : invokers; - } - - /** - * @deprecated Replace to getUrl() - */ - @Deprecated - public Invoker getInvoker() { - return invoker; - } - - /** - * @deprecated Replace to getMethodName(), getParameterTypes(), getArguments() - */ - @Deprecated - public Invocation getInvocation() { - return invocation; - } - - /** - * 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题. - * - * @param callable - * @return 通过future.get()获取返回结果. - */ - @SuppressWarnings("unchecked") - public Future asyncCall(Callable callable) { - try { - try { - setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); - final T o = callable.call(); - //local调用会直接返回结果. - if (o != null) { - FutureTask f = new FutureTask(new Callable() { - public T call() throws Exception { - return o; - } - }); - f.run(); - return f; - } - } catch (Exception e) { - throw new RpcException(e); - } finally { - removeAttachment(Constants.ASYNC_KEY); - } - } catch (final RpcException e) { - return new Future() { - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - public boolean isCancelled() { - return false; - } - - public boolean isDone() { - return true; - } - - public T get() throws InterruptedException, ExecutionException { - throw new ExecutionException(e.getCause()); - } - - public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, - TimeoutException { - return get(); - } - }; - } - return ((Future) getContext().getFuture()); - } - - /** - * oneway调用,只发送请求,不接收返回结果. - * - * @param runnable - */ - public void asyncCall(Runnable runnable) { - try { - setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString()); - runnable.run(); - } catch (Throwable e) { - //FIXME 异常是否应该放在future中? - throw new RpcException("oneway call error ." + e.getMessage(), e); - } finally { - removeAttachment(Constants.RETURN_KEY); - } - } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java index 14825b7fa1f..9a58aee0d3f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java @@ -1,37 +1,38 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; + import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; - /** * 系统存储,内部类. */ -public class StaticContext extends ConcurrentHashMap{ +@Deprecated +public class StaticContext extends ConcurrentHashMap { private static final long serialVersionUID = 1L; private static final String SYSTEMNAME = "system"; - private String name ; - - private static final ConcurrentMap context_map = new ConcurrentHashMap() ; - + private String name; + + private static final ConcurrentMap context_map = new ConcurrentHashMap(); + private StaticContext(String name) { super(); this.name = name; @@ -40,31 +41,34 @@ private StaticContext(String name) { public String getName() { return name; } - + public static StaticContext getSystemContext() { return getContext(SYSTEMNAME); } public static StaticContext getContext(String name) { - StaticContext appContext = context_map.get(name); - if (appContext == null){ - appContext = context_map.putIfAbsent(name, new StaticContext(name)); - if (appContext == null){ - appContext = context_map.get(name); - } - } - return appContext; - } - public static StaticContext remove(String name){ + StaticContext appContext = context_map.get(name); + if (appContext == null) { + appContext = context_map.putIfAbsent(name, new StaticContext(name)); + if (appContext == null) { + appContext = context_map.get(name); + } + } + return appContext; + } + + public static StaticContext remove(String name) { return context_map.remove(name); } - + public static String getKey(URL url, String methodName, String suffix) { return getKey(url.getServiceKey(), methodName, suffix); } + public static String getKey(Map paras, String methodName, String suffix) { return getKey(StringUtils.getServiceKey(paras), methodName, suffix); } + private static String getKey(String servicekey, String methodName, String suffix) { StringBuffer sb = new StringBuffer().append(servicekey).append(".").append(methodName).append(".").append(suffix); return sb.toString(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilterTest.java index 136a6732797..7709f737bcf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ConsumerContextFilterTest.java @@ -41,8 +41,6 @@ public void testSetContext(){ Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); consumerContextFilter.invoke(invoker, invocation); - assertEquals(invoker,RpcContext.getContext().getInvoker()); - assertEquals(invocation,RpcContext.getContext().getInvocation()); assertEquals(NetUtils.getLocalHost() + ":0",RpcContext.getContext().getLocalAddressString()); assertEquals("test:11",RpcContext.getContext().getRemoteAddressString()); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ContextFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ContextFilterTest.java index 3a8017560b6..77dbdbe4595 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ContextFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/ContextFilterTest.java @@ -61,7 +61,6 @@ public void testSetContext() { EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); contextFilter.invoke(invoker, invocation); - assertNull(RpcContext.getContext().getInvoker()); } @Test @@ -70,6 +69,5 @@ public void testWithAttachments() { Invoker invoker = new MyInvoker(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); - assertNull(RpcContext.getContext().getInvoker()); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index edc5043b07a..7031d46a965 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -66,9 +66,9 @@ protected Result doInvoke(Invocation invocation) throws Throwable { Request request = new Request.Builder().newId().version(Version.getVersion()).data(inv).build(); Response response; if (timeout > 0) { - response = currentClient.execute(request, timeout); + response = currentClient.request(request, timeout); } else { - response = currentClient.execute(request); + response = currentClient.request(request); } return (Result) response.getResult(); } catch (RpcException e) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 352fd7a3dc0..92ce7f37721 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -21,7 +21,6 @@ import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exception.TimeoutException; import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.*; @@ -81,16 +80,10 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); currentClient.send(inv, isSent); - RpcContext.getContext().setFuture(null); - return new RpcResult(); - } else if (isAsync) { - ResponseFuture future = currentClient.request(inv, timeout); - RpcContext.getContext().setFuture(new FutureAdapter(future)); return new RpcResult(); } else { - RpcContext.getContext().setFuture(null); Request request = new Request.Builder().newId().data(inv).build(); - Response response = currentClient.execute(request, timeout); + Response response = currentClient.request(request, timeout); return (Result) response.getResult(); } } catch (TimeoutException e) { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java deleted file mode 100644 index 9e24103e3e7..00000000000 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc.protocol.dubbo; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; - -/** - * FutureAdapter - * - * @author william.liangf - */ -public class FutureAdapter implements Future { - - private final ResponseFuture future; - - public FutureAdapter(ResponseFuture future){ - this.future = future; - } - - public ResponseFuture getFuture() { - return future; - } - - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - public boolean isCancelled() { - return false; - } - - public boolean isDone() { - return future.isDone(); - } - - @SuppressWarnings("unchecked") - public V get() throws InterruptedException, ExecutionException { - try { - return (V) (((Result) future.get()).recreate()); - } catch (RemotingException e) { - throw new ExecutionException(e.getMessage(), e); - } catch (Throwable e) { - throw new RpcException(e); - } - } - - @SuppressWarnings("unchecked") - public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - int timeoutInMillis = (int) unit.convert(timeout, TimeUnit.MILLISECONDS); - try { - return (V) (((Result) future.get(timeoutInMillis)).recreate()); - } catch (com.alibaba.dubbo.remoting.exception.TimeoutException e) { - throw new TimeoutException(StringUtils.toString(e)); - } catch (RemotingException e) { - throw new ExecutionException(e.getMessage(), e); - } catch (Throwable e) { - throw new RpcException(e); - } - } - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 1160d84589d..67d3eed7b9c 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -21,12 +21,14 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; +import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicLong; @@ -82,12 +84,6 @@ private void initClient() throws RemotingException { } } - public ResponseFuture request(Object request) throws RemotingException { - warning(request); - initClient(); - return client.request(request); - } - public URL getUrl() { return url; } @@ -100,20 +96,14 @@ public InetSocketAddress getRemoteAddress() { } } - public ResponseFuture request(Object request, int timeout) throws RemotingException { - warning(request); - initClient(); - return client.request(request, timeout); - } - @Override - public Response execute(Request request) throws RemotingException { - return client.execute(request); + public Response request(Request request) throws RemotingException { + return client.request(request); } @Override - public Response execute(Request request, int timeout) throws RemotingException { - return client.execute(request, timeout); + public Response request(Request request, int timeout) throws RemotingException { + return client.request(request, timeout); } /** diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index 64ad9b0f6be..def511dda59 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -18,12 +18,13 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.Parameters; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exchange.*; +import com.alibaba.dubbo.remoting.exchange.ExchangeClient; +import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.message.Request; import com.alibaba.dubbo.remoting.message.Response; +import com.alibaba.dubbo.remoting.transport.ChannelHandler; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentMap; @@ -59,9 +60,6 @@ public void reset(URL url) { client.reset(url); } - public ResponseFuture request(Object request) throws RemotingException { - return client.request(request); - } public URL getUrl() { return client.getUrl(); @@ -75,18 +73,14 @@ public ChannelHandler getChannelHandler() { return client.getChannelHandler(); } - public ResponseFuture request(Object request, int timeout) throws RemotingException { - return client.request(request, timeout); - } - @Override - public Response execute(Request request) throws RemotingException { - return client.execute(request); + public Response request(Request request) throws RemotingException { + return client.request(request); } @Override - public Response execute(Request request, int timeout) throws RemotingException { - return client.execute(request, timeout); + public Response request(Request request, int timeout) throws RemotingException { + return client.request(request, timeout); } public boolean isConnected() { diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java deleted file mode 100644 index 0bb309a3465..00000000000 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc.protocol.dubbo.filter; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.rpc.*; -import com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter; -import com.alibaba.dubbo.rpc.support.RpcUtils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.Future; - -/** - * EventFilter - * - * @author chao.liuc - * @author william.liangf - */ -@Activate(group = Constants.CONSUMER) -public class FutureFilter implements Filter { - - protected static final Logger logger = LoggerFactory.getLogger(FutureFilter.class); - - public Result invoke(final Invoker invoker, final Invocation invocation) throws RpcException { - final boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation); - - fireInvokeCallback(invoker, invocation); - //需要在调用前配置好是否有返回值,已供invoker判断是否需要返回future. - Result result = invoker.invoke(invocation); - if (isAsync) { - asyncCallback(invoker, invocation); - } else { - syncCallback(invoker, invocation, result); - } - return result; - } - - private void syncCallback(final Invoker invoker, final Invocation invocation, final Result result) { - if (result.hasException()) { - fireThrowCallback(invoker, invocation, result.getException()); - } else { - fireReturnCallback(invoker, invocation, result.getValue()); - } - } - - private void asyncCallback(final Invoker invoker, final Invocation invocation) { - Future f = RpcContext.getContext().getFuture(); - if (f instanceof FutureAdapter) { - ResponseFuture future = ((FutureAdapter) f).getFuture(); - future.setCallback(new ResponseCallback() { - public void done(Object rpcResult) { - if (rpcResult == null) { - logger.error(new IllegalStateException("invalid result value : null, expected " + Result.class.getName())); - return; - } - ///must be rpcResult - if (!(rpcResult instanceof Result)) { - logger.error(new IllegalStateException("invalid result type :" + rpcResult.getClass() + ", expected " + Result.class.getName())); - return; - } - Result result = (Result) rpcResult; - if (result.hasException()) { - fireThrowCallback(invoker, invocation, result.getException()); - } else { - fireReturnCallback(invoker, invocation, result.getValue()); - } - } - - public void caught(Throwable exception) { - fireThrowCallback(invoker, invocation, exception); - } - }); - } - } - - private void fireInvokeCallback(final Invoker invoker, final Invocation invocation) { - final Method onInvokeMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_METHOD_KEY)); - final Object onInvokeInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_INVOKE_INSTANCE_KEY)); - - if (onInvokeMethod == null && onInvokeInst == null) { - return; - } - if (onInvokeMethod == null || onInvokeInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); - } - if (!onInvokeMethod.isAccessible()) { - onInvokeMethod.setAccessible(true); - } - - Object[] params = invocation.getArguments(); - try { - onInvokeMethod.invoke(onInvokeInst, params); - } catch (InvocationTargetException e) { - fireThrowCallback(invoker, invocation, e.getTargetException()); - } catch (Throwable e) { - fireThrowCallback(invoker, invocation, e); - } - } - - private void fireReturnCallback(final Invoker invoker, final Invocation invocation, final Object result) { - final Method onReturnMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_METHOD_KEY)); - final Object onReturnInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_RETURN_INSTANCE_KEY)); - - //not set onreturn callback - if (onReturnMethod == null && onReturnInst == null) { - return; - } - - if (onReturnMethod == null || onReturnInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); - } - if (!onReturnMethod.isAccessible()) { - onReturnMethod.setAccessible(true); - } - - Object[] args = invocation.getArguments(); - Object[] params; - Class[] rParaTypes = onReturnMethod.getParameterTypes(); - if (rParaTypes.length > 1) { - if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { - params = new Object[2]; - params[0] = result; - params[1] = args; - } else { - params = new Object[args.length + 1]; - params[0] = result; - System.arraycopy(args, 0, params, 1, args.length); - } - } else { - params = new Object[]{result}; - } - try { - onReturnMethod.invoke(onReturnInst, params); - } catch (InvocationTargetException e) { - fireThrowCallback(invoker, invocation, e.getTargetException()); - } catch (Throwable e) { - fireThrowCallback(invoker, invocation, e); - } - } - - private void fireThrowCallback(final Invoker invoker, final Invocation invocation, final Throwable exception) { - final Method onthrowMethod = (Method) StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_METHOD_KEY)); - final Object onthrowInst = StaticContext.getSystemContext().get(StaticContext.getKey(invoker.getUrl(), invocation.getMethodName(), Constants.ON_THROW_INSTANCE_KEY)); - - //没有设置onthrow callback. - if (onthrowMethod == null && onthrowInst == null) { - return; - } - if (onthrowMethod == null || onthrowInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); - } - if (!onthrowMethod.isAccessible()) { - onthrowMethod.setAccessible(true); - } - Class[] rParaTypes = onthrowMethod.getParameterTypes(); - if (rParaTypes[0].isAssignableFrom(exception.getClass())) { - try { - Object[] args = invocation.getArguments(); - Object[] params; - - if (rParaTypes.length > 1) { - if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { - params = new Object[2]; - params[0] = exception; - params[1] = args; - } else { - params = new Object[args.length + 1]; - params[0] = exception; - System.arraycopy(args, 0, params, 1, args.length); - } - } else { - params = new Object[]{exception}; - } - onthrowMethod.invoke(onthrowInst, params); - } catch (Throwable e) { - logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); - } - } else { - logger.error(invocation.getMethodName() + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); - } - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureFilterTest.java deleted file mode 100644 index 15d06a0f893..00000000000 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc.protocol.dubbo; - -import static org.junit.Assert.assertEquals; - -import org.easymock.EasyMock; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.protocol.dubbo.filter.FutureFilter; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService; - -/** - * EventFilterTest.java - * - * @author tony.chenl - * TODO 暂时依赖callback集成测试,后续补充 - */ -public class FutureFilterTest { - Filter eventFilter = new FutureFilter(); - private static RpcInvocation invocation; - - @BeforeClass - public static void setUp() { - invocation = new RpcInvocation(); - invocation.setMethodName("echo"); - invocation.setParameterTypes(new Class[] { Enum.class }); - invocation.setArguments(new Object[] { "hello" }); - } - - @Test - public void testSyncCallback() { - @SuppressWarnings("unchecked") - Invoker invoker = EasyMock.createMock(Invoker.class); - EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); - EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); - RpcResult result = new RpcResult(); - result.setValue("High"); - EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); - EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); - EasyMock.replay(invoker); - Result filterResult = eventFilter.invoke(invoker, invocation); - assertEquals("High", filterResult.getValue()); - } - - @Test(expected = RuntimeException.class) - public void testSyncCallbackHasException() throws RpcException, Throwable { - @SuppressWarnings("unchecked") - Invoker invoker = EasyMock.createMock(Invoker.class); - EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); - EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); - RpcResult result = new RpcResult(); - result.setException(new RuntimeException()); - EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&"+Constants.ON_THROW_METHOD_KEY+"=echo"); - EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); - EasyMock.replay(invoker); - eventFilter.invoke(invoker, invocation).recreate(); - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java deleted file mode 100644 index 936e58261d9..00000000000 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc.protocol.dubbo; - - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import junit.framework.Assert; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.StaticContext; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; - -public class ImplicitCallBackTest{ - - protected Exporter exporter = null; - protected Invoker reference = null; - - protected URL serviceURL = null ; - protected URL consumerUrl = null ; - Method onReturnMethod; - Method onThrowMethod ; - Method onInvokeMethod ; - - @Before - public void setUp() throws SecurityException, NoSuchMethodException{ - onReturnMethod = Nofify.class.getMethod("onreturn", new Class[]{Person.class, Integer.class}); - onThrowMethod = Nofify.class.getMethod("onthrow", new Class[]{Throwable.class, Integer.class}); - onInvokeMethod = Nofify.class.getMethod("oninvoke", new Class[]{Integer.class}); - } - - @After - public void tearDown(){ - ProtocolUtils.closeAll(); - } - - public void initOrResetService(){ - destroyService(); - exportService(); - referService(); - } - public void destroyService(){ - demoProxy = null ; - try { - if (exporter!=null) exporter.unexport(); - if (reference!=null) reference.destroy(); - }catch (Exception e) { - } - } - - void referService() { - demoProxy = (IDemoService)ProtocolUtils.refer(IDemoService.class, consumerUrl); - } - - public void exportService(){ - exporter = ProtocolUtils.export(new NormalDemoService(), IDemoService.class, serviceURL); - } - public void exportExService(){ - exporter = ProtocolUtils.export(new ExceptionDemoExService(), IDemoService.class, serviceURL); - } - - public void initOrResetUrl(boolean isAsync) throws Exception { - int port = NetUtils.getAvailablePort() ; - consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:"+port+"/"+IDemoService.class.getName()+"?group=test&async="+isAsync+"&timeout=100000&reference.filter=future" ); - StaticContext.getSystemContext().clear(); - } - - public void initImplicitCallBackURL_onlyOnthrow() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_METHOD_KEY),onThrowMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_INSTANCE_KEY),notify); - } - public void initImplicitCallBackURL_onlyOnreturn() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_METHOD_KEY),onReturnMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_INSTANCE_KEY),notify); - - } - public void initImplicitCallBackURL_onlyOninvoke() throws Exception { - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_METHOD_KEY),onInvokeMethod); - StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_INSTANCE_KEY),notify); - } - - //================================================================================================ - - NofifyImpl notify = new NofifyImpl(); - - interface Nofify { - public void onreturn(Person msg, Integer id); - public void onthrow(Throwable ex, Integer id); - public void oninvoke(Integer id); - } - class NofifyImpl implements Nofify{ - public List inv = new ArrayList (); - public Map ret = new HashMap (); - public Map errors = new HashMap (); - public boolean exd = false; - public void onreturn(Person msg, Integer id) { - System.out.println("onNotify:"+msg); - ret.put(id, msg); - } - public void onthrow(Throwable ex, Integer id) { - errors.put(id, ex); -// ex.printStackTrace(); - } - public void oninvoke(Integer id) { - inv.add(id); - } - } - - interface IDemoService{ - public Person get(int id); - } - - class NormalDemoService implements IDemoService { - public Person get(int id){ - return new Person(id, "charles", 4); - } - } - class ExceptionDemoExService implements IDemoService { - public Person get(int id){ - throw new RuntimeException("request persion id is :"+ id); - } - } - - public static class Person implements Serializable{ - private static final long serialVersionUID = 1L; - public Person(int id, String name, int age) { - this.id = id; - this.name = name; - this.age = age; - } - private int id; - private String name ; - private int age; - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public int getAge() { - return age; - } - public void setAge(int age) { - this.age = age; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - @Override - public String toString() { - return "Person [name=" + name + ", age=" + age + "]"; - } - } - //================================================================================================ - IDemoService demoProxy = null; - - @Test - public void test_CloseCallback() throws Exception { - initOrResetUrl(false); - initOrResetService() ; - Person ret = demoProxy.get(1); - Assert.assertEquals(1, ret.getId()); - destroyService(); - } - - @Test - public void test_Sync_Onreturn() throws Exception { - initOrResetUrl(false); - initImplicitCallBackURL_onlyOnreturn(); - initOrResetService() ; - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(requestId, ret.getId()); - for (int i = 0; i < 10; i++) { - if (! notify.ret.containsKey(requestId)){ - Thread.sleep(200); - }else { - break; - } - } - Assert.assertEquals(requestId, notify.ret.get(requestId).getId()); - destroyService(); - } - - @Test - public void test_Ex_OnReturn() throws Exception { - initOrResetUrl(true); - initImplicitCallBackURL_onlyOnreturn(); - - destroyService(); - exportExService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(null, ret); - for (int i = 0; i < 10; i++) { - if (! notify.errors.containsKey(requestId)){ - Thread.sleep(200); - }else { - break; - } - } - Assert.assertTrue(! notify.errors.containsKey(requestId)); - destroyService(); - } - - @Test - public void test_Ex_OnInvoke() throws Exception { - initOrResetUrl(true); - initImplicitCallBackURL_onlyOninvoke(); - - destroyService(); - exportExService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(null, ret); - for (int i = 0; i < 10; i++) { - if (! notify.inv.contains(requestId)){ - Thread.sleep(200); - }else { - break; - } - } - Assert.assertTrue(notify.inv.contains(requestId)); - destroyService(); - } - - @Test - public void test_Ex_Onthrow() throws Exception { - initOrResetUrl(true); - initImplicitCallBackURL_onlyOnthrow(); - - destroyService(); - exportExService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(null, ret); - for (int i = 0; i < 10; i++) { - if (! notify.errors.containsKey(requestId)){ - Thread.sleep(200); - }else { - break; - } - } - Assert.assertTrue(notify.errors.containsKey(requestId)); - Assert.assertTrue(notify.errors.get(requestId) instanceof Throwable); - destroyService(); - } - - @Test - public void test_Sync_NoFuture() throws Exception { - initOrResetUrl(false); - initImplicitCallBackURL_onlyOnreturn(); - destroyService(); - exportService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(requestId, ret.getId()); - Future pFuture = RpcContext.getContext().getFuture(); - Assert.assertEquals(null, pFuture); - destroyService(); - } - - @Test - public void test_Async_Future() throws Exception { - initOrResetUrl(true); - destroyService(); - exportService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(null, ret); - Future pFuture = RpcContext.getContext().getFuture(); - ret = pFuture.get(1000, TimeUnit.MICROSECONDS); - Assert.assertEquals(requestId, ret.getId()); - destroyService(); - } - - @Test - public void test_Async_Future_Multi() throws Exception { - initOrResetUrl(true); - destroyService(); - exportService(); - referService(); - - int requestId1 = 1; - Person ret = demoProxy.get(requestId1); - Assert.assertEquals(null, ret); - Future p1Future = RpcContext.getContext().getFuture(); - - int requestId2 = 1; - Person ret2 = demoProxy.get(requestId2); - Assert.assertEquals(null, ret2); - Future p2Future = RpcContext.getContext().getFuture(); - - ret = p1Future.get(1000, TimeUnit.MICROSECONDS); - ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS); - Assert.assertEquals(requestId1, ret.getId()); - Assert.assertEquals(requestId2, ret.getId()); - destroyService(); - } - - @Test(expected = RuntimeException.class) - public void test_Async_Future_Ex() throws Exception { - try{ - initOrResetUrl(true); - destroyService(); - exportExService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(null, ret); - Future pFuture = RpcContext.getContext().getFuture(); - ret = pFuture.get(1000, TimeUnit.MICROSECONDS); - Assert.assertEquals(requestId, ret.getId()); - }finally{ - destroyService(); - } - } - - @Test(expected = RuntimeException.class) - public void test_Normal_Ex() throws Exception { - initOrResetUrl(false); - destroyService(); - exportExService(); - referService(); - - int requestId = 2; - Person ret = demoProxy.get(requestId); - Assert.assertEquals(requestId, ret.getId()); - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml deleted file mode 100644 index 3fafc6e227a..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-rpc - 3.0.0 - - dubbo-rpc-thrift - jar - ${project.artifactId} - The thrift rpc module of dubbo project - - true - - - - com.alibaba - dubbo-rpc-api - ${project.parent.version} - - - com.alibaba - dubbo-rpc-default - ${project.parent.version} - - - com.alibaba - dubbo-remoting-api - ${project.parent.version} - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - - - org.apache.thrift - libthrift - - - org.apache.httpcomponents - httpcore - - - - - org.apache.httpcomponents - httpclient - - - com.alibaba - dubbo-config-spring - ${project.parent.version} - test - - - com.alibaba - dubbo-registry-multicast - ${project.parent.version} - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java deleted file mode 100644 index 36e5eda2821..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.extension.SPI; - -/** - * @author kimi - */ -@SPI( DubboClassNameGenerator.NAME ) -public interface ClassNameGenerator { - - public String generateArgsClassName( String serviceName, String methodName ); - - public String generateResultClassName( String serviceName, String methodName ); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java deleted file mode 100644 index ab9d70832bc..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author kimi - */ -public class DubboClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "dubbo"; - - public String generateArgsClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodArgsClassName( serviceName, methodName ); - } - - public String generateResultClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodResultClassName( serviceName, methodName ); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java deleted file mode 100644 index 5c34c222f25..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author kimi - */ -public class ThriftClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "thrift"; - - public String generateArgsClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodArgsClassNameThrift( serviceName, methodName ); - } - - public String generateResultClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodResultClassNameThrift( serviceName, methodName ); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java deleted file mode 100644 index b1c2d376503..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ /dev/null @@ -1,693 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - *

- * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - *

- * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.utils.ClassHelper; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.Codec2; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; -import org.apache.commons.lang.StringUtils; -import org.apache.thrift.TApplicationException; -import org.apache.thrift.TBase; -import org.apache.thrift.TException; -import org.apache.thrift.TFieldIdEnum; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Thrift framed protocol codec. - *

- *

- * |<-                                  message header                                  ->|<- message body ->|
- * +----------------+----------------------+------------------+---------------------------+------------------+
- * | magic (2 bytes)|message size (4 bytes)|head size(2 bytes)| version (1 byte) | header |   message body   |
- * +----------------+----------------------+------------------+---------------------------+------------------+
- * |<-                                               message size                                          ->|
- * 
- *

- *

- * header fields in version 1 - *

    - *
  1. string - service name
  2. - *
  3. long - dubbo request id
  4. - *
- *

- * - * @author gang.lvg - */ -public class ThriftCodec implements Codec2 { - - private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger(0); - - private static final ConcurrentMap> cachedClass = - new ConcurrentHashMap>(); - - static final ConcurrentMap cachedRequest = - new ConcurrentHashMap(); - - public static final int MESSAGE_LENGTH_INDEX = 2; - - public static final int MESSAGE_HEADER_LENGTH_INDEX = 6; - - public static final int MESSAGE_SHORTEST_LENGTH = 10; - - public static final String NAME = "thrift"; - - public static final String PARAMETER_CLASS_NAME_GENERATOR = "class.name.generator"; - - public static final byte VERSION = (byte) 1; - - public static final short MAGIC = (short) 0xdabc; - - public void encode(Channel channel, ChannelBuffer buffer, Object message) - throws IOException { - - if (message instanceof Request) { - encodeRequest(channel, buffer, (Request) message); - } else if (message instanceof Response) { - encodeResponse(channel, buffer, (Response) message); - } else { - throw new UnsupportedOperationException( - new StringBuilder(32) - .append("Thrift codec only support encode ") - .append(Request.class.getName()) - .append(" and ") - .append(Response.class.getName()) - .toString()); - } - - } - - public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { - - int available = buffer.readableBytes(); - - if (available < MESSAGE_SHORTEST_LENGTH) { - - return DecodeResult.NEED_MORE_INPUT; - - } else { - - TIOStreamTransport transport = new TIOStreamTransport(new ChannelBufferInputStream(buffer)); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - short magic; - int messageLength; - - try { -// protocol.readI32(); // skip the first message length - byte[] bytes = new byte[4]; - transport.read(bytes, 0, 4); - magic = protocol.readI16(); - messageLength = protocol.readI32(); - - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - - if (MAGIC != magic) { - throw new IOException( - new StringBuilder(32) - .append("Unknown magic code ") - .append(magic) - .toString()); - } - - if (available < messageLength) { - return DecodeResult.NEED_MORE_INPUT; - } - - return decode(protocol); - - } - - } - - private Object decode(TProtocol protocol) - throws IOException { - - // version - String serviceName; - long id; - - TMessage message; - - try { - protocol.readI16(); - protocol.readByte(); - serviceName = protocol.readString(); - id = protocol.readI64(); - message = protocol.readMessageBegin(); - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - - if (message.type == TMessageType.CALL) { - - RpcInvocation result = new RpcInvocation(); - result.setAttachment(Constants.INTERFACE_KEY, serviceName); - result.setMethodName(message.name); - - String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name); - - if (StringUtils.isEmpty(argsClassName)) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, - "The specified interface name incorrect."); - } - - Class clazz = cachedClass.get(argsClassName); - - if (clazz == null) { - try { - - clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName); - - cachedClass.putIfAbsent(argsClassName, clazz); - - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - } - - TBase args; - - try { - args = (TBase) clazz.newInstance(); - } catch (InstantiationException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - try { - args.read(protocol); - protocol.readMessageEnd(); - } catch (TException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - List parameters = new ArrayList(); - List> parameterTypes = new ArrayList>(); - int index = 1; - - while (true) { - - TFieldIdEnum fieldIdEnum = args.fieldForId(index++); - - if (fieldIdEnum == null) { - break; - } - - String fieldName = fieldIdEnum.getFieldName(); - - String getMethodName = ThriftUtils.generateGetMethodName(fieldName); - - Method getMethod; - - try { - getMethod = clazz.getMethod(getMethodName); - } catch (NoSuchMethodException e) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - parameterTypes.add(getMethod.getReturnType()); - try { - parameters.add(getMethod.invoke(args)); - } catch (IllegalAccessException e) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - result.setArguments(parameters.toArray()); - result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); - Request.Builder builder = new Request.Builder(id); - builder.data(result); - Request request = builder.build(); - cachedRequest.putIfAbsent(id, - RequestData.create(message.seqid, serviceName, message.name)); - - return request; - - } else if (message.type == TMessageType.EXCEPTION) { - - TApplicationException exception; - - try { - exception = TApplicationException.read(protocol); - protocol.readMessageEnd(); - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - RpcResult result = new RpcResult(); - result.setException(new RpcException(exception.getMessage())); - Response.Builder builder = new Response.Builder(id); - builder.result(result); - return builder.build(); - } else if (message.type == TMessageType.REPLY) { - String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name); - if (StringUtils.isEmpty(resultClassName)) { - throw new IllegalArgumentException( - new StringBuilder(32) - .append("Could not infer service result class name from service name ") - .append(serviceName) - .append(", the service name you specified may not generated by thrift idl compiler") - .toString()); - } - Class clazz = cachedClass.get(resultClassName); - if (clazz == null) { - try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent(resultClassName, clazz); - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - } - - TBase result; - try { - result = (TBase) clazz.newInstance(); - } catch (InstantiationException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - try { - result.read(protocol); - protocol.readMessageEnd(); - } catch (TException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - Object realResult = null; - int index = 0; - while (true) { - TFieldIdEnum fieldIdEnum = result.fieldForId(index++); - if (fieldIdEnum == null) { - break; - } - Field field; - try { - field = clazz.getDeclaredField(fieldIdEnum.getFieldName()); - field.setAccessible(true); - } catch (NoSuchFieldException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - try { - realResult = field.get(result); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - if (realResult != null) { - break; - } - } - Response.Builder builder = new Response.Builder(id); - RpcResult rpcResult = new RpcResult(); - if (realResult instanceof Throwable) { - rpcResult.setException((Throwable) realResult); - } else { - rpcResult.setValue(realResult); - } - builder.result(rpcResult); - return builder.build(); - } else { - // Impossible - throw new IOException(); - } - - } - - private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) - throws IOException { - - RpcInvocation inv = (RpcInvocation) request.getData(); - - int seqId = nextSeqId(); - - String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); - - if (StringUtils.isEmpty(serviceName)) { - throw new IllegalArgumentException( - new StringBuilder(32) - .append("Could not find service name in attachment with key ") - .append(Constants.INTERFACE_KEY) - .toString()); - } - - TMessage message = new TMessage( - inv.getMethodName(), - TMessageType.CALL, - seqId); - - String methodArgs = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateArgsClassName(serviceName, inv.getMethodName()); - - if (StringUtils.isEmpty(methodArgs)) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder(32).append( - "Could not encode request, the specified interface may be incorrect.").toString()); - } - - Class clazz = cachedClass.get(methodArgs); - - if (clazz == null) { - - try { - - clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs); - - cachedClass.putIfAbsent(methodArgs, clazz); - - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - TBase args; - - try { - args = (TBase) clazz.newInstance(); - } catch (InstantiationException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - for (int i = 0; i < inv.getArguments().length; i++) { - - Object obj = inv.getArguments()[i]; - - if (obj == null) { - continue; - } - - TFieldIdEnum field = args.fieldForId(i + 1); - - String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName()); - - Method method; - - try { - method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]); - } catch (NoSuchMethodException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - try { - method.invoke(args, obj); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - - TIOStreamTransport transport = new TIOStreamTransport(bos); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - int headerLength, messageLength; - - byte[] bytes = new byte[4]; - try { - // magic - protocol.writeI16(MAGIC); - // message length placeholder - protocol.writeI32(Integer.MAX_VALUE); - // message header length placeholder - protocol.writeI16(Short.MAX_VALUE); - // version - protocol.writeByte(VERSION); - // service name - protocol.writeString(serviceName); - // dubbo request id - protocol.writeI64(request.getId()); - protocol.getTransport().flush(); - // header size - headerLength = bos.size(); - - // message body - protocol.writeMessageBegin(message); - args.write(protocol); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - // fill in message length and header length - try { - TFramedTransport.encodeFrameSize(messageLength, bytes); - bos.setWriteIndex(MESSAGE_LENGTH_INDEX); - protocol.writeI32(messageLength); - bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX); - protocol.writeI16((short) (0xffff & headerLength)); - } finally { - bos.setWriteIndex(oldIndex); - } - - } catch (TException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - buffer.writeBytes(bytes); - buffer.writeBytes(bos.toByteArray()); - - } - - private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) - throws IOException { - - RpcResult result = (RpcResult) response.getResult(); - - RequestData rd = cachedRequest.get(response.getId()); - - String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension( - channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateResultClassName(rd.serviceName, rd.methodName); - - if (StringUtils.isEmpty(resultClassName)) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder(32).append( - "Could not encode response, the specified interface may be incorrect.").toString()); - } - - Class clazz = cachedClass.get(resultClassName); - - if (clazz == null) { - - try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent(resultClassName, clazz); - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - TBase resultObj; - - try { - resultObj = (TBase) clazz.newInstance(); - } catch (InstantiationException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - TApplicationException applicationException = null; - TMessage message; - - if (result.hasException()) { - Throwable throwable = result.getException(); - int index = 1; - boolean found = false; - while (true) { - TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++); - if (fieldIdEnum == null) { - break; - } - String fieldName = fieldIdEnum.getFieldName(); - String getMethodName = ThriftUtils.generateGetMethodName(fieldName); - String setMethodName = ThriftUtils.generateSetMethodName(fieldName); - Method getMethod; - Method setMethod; - try { - getMethod = clazz.getMethod(getMethodName); - if (getMethod.getReturnType().equals(throwable.getClass())) { - found = true; - setMethod = clazz.getMethod(setMethodName, throwable.getClass()); - setMethod.invoke(resultObj, throwable); - } - } catch (NoSuchMethodException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - } - - if (!found) { - applicationException = new TApplicationException(throwable.getMessage()); - } - - } else { - Object realResult = result.getResult(); - // result field id is 0 - String fieldName = resultObj.fieldForId(0).getFieldName(); - String setMethodName = ThriftUtils.generateSetMethodName(fieldName); - String getMethodName = ThriftUtils.generateGetMethodName(fieldName); - Method getMethod; - Method setMethod; - try { - getMethod = clazz.getMethod(getMethodName); - setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType()); - setMethod.invoke(resultObj, realResult); - } catch (NoSuchMethodException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - if (applicationException != null) { - message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id); - } else { - message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id); - } - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - - TIOStreamTransport transport = new TIOStreamTransport(bos); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - int messageLength; - int headerLength; - - byte[] bytes = new byte[4]; - try { - // magic - protocol.writeI16(MAGIC); - // message length - protocol.writeI32(Integer.MAX_VALUE); - // message header length - protocol.writeI16(Short.MAX_VALUE); - // version - protocol.writeByte(VERSION); - // service name - protocol.writeString(rd.serviceName); - // id - protocol.writeI64(response.getId()); - protocol.getTransport().flush(); - headerLength = bos.size(); - - // message - protocol.writeMessageBegin(message); - switch (message.type) { - case TMessageType.EXCEPTION: - applicationException.write(protocol); - break; - case TMessageType.REPLY: - resultObj.write(protocol); - break; - } - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - TFramedTransport.encodeFrameSize(messageLength, bytes); - bos.setWriteIndex(MESSAGE_LENGTH_INDEX); - protocol.writeI32(messageLength); - bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX); - protocol.writeI16((short) (0xffff & headerLength)); - } finally { - bos.setWriteIndex(oldIndex); - } - - } catch (TException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - buffer.writeBytes(bytes); - buffer.writeBytes(bos.toByteArray()); - - } - - private static int nextSeqId() { - return THRIFT_SEQ_ID.incrementAndGet(); - } - - // just for test - static int getSeqId() { - return THRIFT_SEQ_ID.get(); - } - - static class RequestData { - int id; - String serviceName; - String methodName; - - static RequestData create(int id, String sn, String mn) { - RequestData result = new RequestData(); - result.id = id; - result.serviceName = sn; - result.methodName = mn; - return result; - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java deleted file mode 100644 index 7bf67ad04ae..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author kimi - */ -public final class ThriftConstants { - - public static final String THRIFT_PROTOCOL_KEY = "thrift.protocol"; - public static final String BINARY_THRIFT_PROTOCOL = "binary"; - public static final String CLASS_NAME_GENERATOR_KEY = "class.name.generator"; - public static final String DEFAULT_PROTOCOL = BINARY_THRIFT_PROTOCOL; - - private ThriftConstants() {} - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java deleted file mode 100644 index 3a4b0a21de8..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - *

- * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - *

- * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.exception.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.rpc.*; -import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; - -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * @author gang.lvg - */ -public class ThriftInvoker extends AbstractInvoker { - - private final ExchangeClient[] clients; - - private final AtomicPositiveInteger index = new AtomicPositiveInteger(); - - private final ReentrantLock destroyLock = new ReentrantLock(); - - private final Set> invokers; - - public ThriftInvoker(Class service, URL url, ExchangeClient[] clients) { - this(service, url, clients, null); - } - - public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Set> invokers) { - super(type, url, - new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, - Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); - this.clients = clients; - this.invokers = invokers; - } - - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - RpcInvocation inv = (RpcInvocation) invocation; - final String methodName = invocation.getMethodName(); - inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); - // for thrift codec - inv.setAttachment(ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, getUrl().getParameter( - ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, DubboClassNameGenerator.NAME)); - ExchangeClient currentClient; - if (clients.length == 1) { - currentClient = clients[0]; - } else { - currentClient = clients[index.getAndIncrement() % clients.length]; - } - try { - int timeout = getUrl().getMethodParameter( - methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - RpcContext.getContext().setFuture(null); - Request request = new Request.Builder().newId().data(inv).build(); - Response response = currentClient.execute(request, timeout); - return (Result) response.getResult(); - } catch (TimeoutException e) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e); - } catch (RemotingException e) { - throw new RpcException(RpcException.NETWORK_EXCEPTION, e.getMessage(), e); - } - - } - - @Override - public boolean isAvailable() { - if (!super.isAvailable()) { - return false; - } - for (ExchangeClient client : clients) { - if (client.isConnected() - && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { - //cannot write == not Available ? - return true; - } - } - return false; - } - - public void destroy() { - //防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭 - if (isDestroyed()) { - return; - } - //dubbo check ,避免多次关闭 - destroyLock.lock(); - try { - if (super.isDestroyed()) { - return; - } - super.destroy(); - if (invokers != null) { - invokers.remove(this); - } - for (ExchangeClient client : clients) { - try { - client.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } finally { - destroyLock.unlock(); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java deleted file mode 100644 index 4320db8a487..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TStruct; -import org.apache.thrift.transport.TIOStreamTransport; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.Codec2; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; -import com.alibaba.dubbo.rpc.Invocation; - -/** - * @author kimi - */ -public class ThriftNativeCodec implements Codec2 { - - private final AtomicInteger thriftSeq = new AtomicInteger(0); - - public void encode(Channel channel, ChannelBuffer buffer, Object message) - throws IOException { - if (message instanceof Request) { - encodeRequest(channel, buffer, (Request)message); - } else if (message instanceof Response) { - encodeResponse(channel, buffer, (Response)message); - } else { - throw new IOException("Unsupported message type " - + message.getClass().getName()); - } - } - - protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) - throws IOException { - Invocation invocation = (Invocation) request.getData(); - TProtocol protocol = newProtocol(channel.getUrl(), buffer); - try { - protocol.writeMessageBegin(new TMessage( - invocation.getMethodName(), TMessageType.CALL, - thriftSeq.getAndIncrement())); - protocol.writeStructBegin(new TStruct(invocation.getMethodName() + "_args")); - for(int i = 0; i < invocation.getParameterTypes().length; i++) { - Class type = invocation.getParameterTypes()[i]; - - } - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - - } - - protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) - throws IOException { - - } - - public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { - return null; - } - - protected static TProtocol newProtocol(URL url, ChannelBuffer buffer) throws IOException { - String protocol = url.getParameter(ThriftConstants.THRIFT_PROTOCOL_KEY, - ThriftConstants.DEFAULT_PROTOCOL); - if (ThriftConstants.BINARY_THRIFT_PROTOCOL.equals(protocol)) { - return new TBinaryProtocol(new TIOStreamTransport(new ChannelBufferOutputStream(buffer))); - } - throw new IOException("Unsupported protocol type " + protocol); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java deleted file mode 100644 index ca4cfbc98de..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ /dev/null @@ -1,213 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import java.util.ArrayList; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.exception.RemotingException; -import com.alibaba.dubbo.remoting.transport.Transporter; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProtocol; -import com.alibaba.dubbo.rpc.protocol.dubbo.DubboExporter; - -/** - * @author gang.lvg - */ -public class ThriftProtocol extends AbstractProtocol { - - public static final int DEFAULT_PORT = 40880; - - public static final String NAME = "thrift"; - - // ip:port -> ExchangeServer - private final ConcurrentMap serverMap = - new ConcurrentHashMap(); - - private ExchangeHandler handler = new ExchangeHandlerAdapter() { - - @Override - public Object reply( ExchangeChannel channel, Object msg ) throws RemotingException { - - if ( msg instanceof Invocation ) { - Invocation inv = ( Invocation ) msg; - String serviceName = inv.getAttachments().get(Constants.INTERFACE_KEY); - String serviceKey = serviceKey( channel.getLocalAddress().getPort(), - serviceName, null, null ); - DubboExporter exporter = (DubboExporter) exporterMap.get( serviceKey ); - if (exporter == null) { - throw new RemotingException(channel, - "Not found exported service: " - + serviceKey - + " in " - + exporterMap.keySet() - + ", may be version or group mismatch " - + ", channel: consumer: " - + channel.getRemoteAddress() - + " --> provider: " - + channel.getLocalAddress() - + ", message:"+ msg); - } - - RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress()); - return exporter.getInvoker().invoke( inv ); - - } - - throw new RemotingException(channel, - "Unsupported request: " - + (msg.getClass().getName() + ": " + msg) - + ", channel: consumer: " - + channel.getRemoteAddress() - + " --> provider: " - + channel.getLocalAddress()); - } - - @Override - public void received( Channel channel, Object message ) throws RemotingException { - if ( message instanceof Invocation ) { - reply( ( ExchangeChannel ) channel, message ); - } else { - super.received( channel, message ); - } - } - - }; - - public int getDefaultPort() { - return DEFAULT_PORT; - } - - public Exporter export( Invoker invoker ) throws RpcException { - - // 只能使用 thrift codec - URL url = invoker.getUrl().addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); - // find server. - String key = url.getAddress(); - //client 也可以暴露一个只有server可以调用的服务。 - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY,true); - if (isServer && ! serverMap.containsKey(key)) { - serverMap.put(key, getServer(url)); - } - // export service. - key = serviceKey(url); - DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); - exporterMap.put(key, exporter); - - return exporter; - } - - public void destroy() { - - super.destroy(); - - for (String key : new ArrayList(serverMap.keySet())) { - - ExchangeServer server = serverMap.remove(key); - - if (server != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close dubbo server: " + server.getLocalAddress()); - } - server.close(getServerShutdownTimeout()); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } // ~ end of if ( server != null ) - - } // ~ end of loop serverMap - - } // ~ end of method destroy - - public Invoker refer( Class type, URL url ) throws RpcException { - - ThriftInvoker invoker = new ThriftInvoker(type, url, getClients(url), invokers); - - invokers.add(invoker); - - return invoker; - - } - - private ExchangeClient[] getClients(URL url){ - - int connections = url.getParameter(Constants.CONNECTIONS_KEY, 1); - - ExchangeClient[] clients = new ExchangeClient[connections]; - - for (int i = 0; i < clients.length; i++) { - clients[i] = initClient(url); - } - return clients; - } - - private ExchangeClient initClient(URL url) { - - ExchangeClient client ; - - url = url.addParameter( Constants.CODEC_KEY, ThriftCodec.NAME ); - - try { - client = Exchangers.connect( url ); - } catch ( RemotingException e ) { - throw new RpcException( "Fail to create remoting client for service(" + url - + "): " + e.getMessage(), e ); - } - - return client; - - } - - private ExchangeServer getServer(URL url) { - //默认开启server关闭时发送readonly事件 - url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); - - if (str != null && str.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) - throw new RpcException("Unsupported server type: " + str + ", url: " + url); - - ExchangeServer server; - try { - server = Exchangers.bind(url, handler); - } catch (RemotingException e) { - throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); - } - str = url.getParameter(Constants.CLIENT_KEY); - if (str != null && str.length() > 0) { - Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); - if (!supportedTypes.contains(str)) { - throw new RpcException("Unsupported client type: " + str); - } - } - return server; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java deleted file mode 100644 index f8a44e04794..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author kimi - */ -public enum ThriftType { - - BOOL, BYTE, I16, I32, I64, DOUBLE, STRING; - - public static ThriftType get(Class key) { - if (key != null) { - return types.get(key); - } - throw new NullPointerException("key == null"); - } - - private static final Map, ThriftType> types = - new HashMap, ThriftType>(); - - private static void put(Class key, ThriftType value) { - types.put(key, value); - } - static { - put(boolean.class, BOOL); - put(Boolean.class, BOOL); - put(byte.class, BYTE); - put(Byte.class, BYTE); - put(short.class, I16); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java deleted file mode 100644 index 15f3f622ca0..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author gang.lvg - */ -public class ThriftUtils { - - /** - * Generate class name which represents service arguments. - * - * @param serviceName service name - * @param methodName method name - * @return method args class name or null - */ - public static String generateMethodArgsClassName( String serviceName, String methodName ) { - - int index = serviceName.lastIndexOf( "." ); - - if ( index > 0 ) { - - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( "$__" ) - .append( serviceName.substring( index + 1 ) ) - .append( "Stub$" ) - .append( methodName ) - .append( "_args" ) - .toString(); - - } else { - return new StringBuffer( 32 ) - .append( "$__" ) - .append( serviceName ) - .append( "Stub$" ) - .append( methodName ) - .append( "_args" ) - .toString(); - } - - } - - public static String generateMethodResultClassName( String serviceName, String method ) { - - int index = serviceName.lastIndexOf( "." ); - - if ( index > 0 ) { - - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( "$__" ) - .append( serviceName.substring( index + 1 ) ) - .append( "Stub$" ) - .append( method ) - .append( "_result" ) - .toString(); - - } else { - return new StringBuilder( 32 ) - .append( "$__" ) - .append( serviceName ) - .append( "Stub$" ) - .append( method ) - .append( "_result" ) - .toString(); - } - - } - - public static String generateSetMethodName( String fieldName ) { - - return new StringBuilder( 16 ) - .append( "set" ) - .append( Character.toUpperCase( fieldName.charAt( 0 ) ) ) - .append( fieldName.substring( 1 ) ) - .toString(); - - } - - public static String generateGetMethodName( String fieldName ) { - return new StringBuffer( 16 ) - .append( "get" ) - .append( Character.toUpperCase( fieldName.charAt( 0 ) ) ) - .append( fieldName.substring( 1 ) ) - .toString(); - } - - public static String generateMethodArgsClassNameThrift( String serviceName, String methodName ) { - - int index = serviceName.indexOf( "$" ); - - if ( index > 0 ) { - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( methodName ) - .append( "_args" ) - .toString(); - } - - return null; - - } - - public static String generateMethodResultClassNameThrift( String serviceName, String methodName ) { - - int index = serviceName.indexOf( "$" ); - - if ( index > 0 ) { - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( methodName ) - .append( "_result" ) - .toString(); - } - - return null; - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java deleted file mode 100644 index c4ef07b8b03..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * File Created at 2011-12-26 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift.ext; - -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec; -import org.apache.thrift.TException; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.transport.TIOStreamTransport; - -import java.io.ByteArrayOutputStream; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @author kimi - */ -public class MultiServiceProcessor implements TProcessor { - - private static final Logger logger = LoggerFactory.getLogger( MultiServiceProcessor.class ); - - private ConcurrentMap processorMap = new ConcurrentHashMap(); - - private TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); - - public MultiServiceProcessor() {} - - public boolean process( TProtocol in, TProtocol out ) throws TException { - - short magic = in.readI16(); - - if ( magic != ThriftCodec.MAGIC ) { - logger.error( - new StringBuilder( 24 ) - .append( "Unsupported magic " ) - .append( magic ).toString() ); - return false; - } - - in.readI32(); - in.readI16(); - byte version = in.readByte(); - String serviceName = in.readString(); - long id = in.readI64(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream( 1024 ); - - TIOStreamTransport transport = new TIOStreamTransport( bos ); - - TProtocol protocol = protocolFactory.getProtocol( transport ); - - TProcessor processor = processorMap.get( serviceName ); - - if ( processor == null ) { - logger.error( - new StringBuilder( 32 ) - .append( "Could not find processor for service " ) - .append( serviceName ) - .toString() ); - return false; - } - - // todo if exception - boolean result = processor.process( in, protocol ); - - ByteArrayOutputStream header = new ByteArrayOutputStream( 512 ); - - TIOStreamTransport headerTransport = new TIOStreamTransport( header ); - - TProtocol headerProtocol = protocolFactory.getProtocol( headerTransport ); - - headerProtocol.writeI16( magic ); - headerProtocol.writeI32( Integer.MAX_VALUE ); - headerProtocol.writeI16( Short.MAX_VALUE ); - headerProtocol.writeByte( version ); - headerProtocol.writeString( serviceName ); - headerProtocol.writeI64( id ); - headerProtocol.getTransport().flush(); - - out.writeI16( magic ); - out.writeI32( bos.size() + header.size() ); - out.writeI16( ( short ) ( 0xffff & header.size() ) ); - out.writeByte( version ); - out.writeString( serviceName ); - out.writeI64( id ); - - out.getTransport().write( bos.toByteArray() ); - out.getTransport().flush(); - - return result; - - } - - public TProcessor addProcessor( Class service, TProcessor processor ) { - if ( service != null && processor != null ) { - return processorMap.putIfAbsent( service.getName(), processor ); - } - return processor; - } - - public void setProtocolFactory( TProtocolFactory factory ) { - if ( factory != null ) { - this.protocolFactory = factory; - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java deleted file mode 100644 index 9cdfdc372c4..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @author kimi - */ -public class InputStreamWrapper extends InputStream { - - private InputStream is; - - public InputStreamWrapper(InputStream is) { - if (is == null) { - throw new NullPointerException("is == null"); - } - this.is = is; - } - - @Override - public int read(byte[] b) throws IOException { - if (is.available() >= b.length) { - return is.read(b); - } else { - return -1; - } - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (is.available() >= len) { - return is.read(b, off, len); - } else { - return -1; - } - } - - @Override - public long skip(long n) throws IOException { - return is.skip(n); - } - - @Override - public int available() throws IOException { - return is.available(); - } - - @Override - public void close() throws IOException { - is.close(); - } - - @Override - public void mark(int readlimit) { - is.mark(readlimit); - } - - @Override - public void reset() throws IOException { - is.reset(); - } - - @Override - public boolean markSupported() { - return is.markSupported(); - } - - @Override - public int read() throws IOException { - if (is.available() >= 1) { - return is.read(); - } - return -1; - } -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java deleted file mode 100644 index 4902b4d59cb..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * File Created at 2011-12-22 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift.io; - -import com.alibaba.dubbo.common.io.Bytes; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; - -/** - * @author kimi - */ -public class RandomAccessByteArrayOutputStream extends OutputStream { - - protected byte buffer[]; - - protected int count; - - public RandomAccessByteArrayOutputStream() { - - this( 32 ); - } - - public RandomAccessByteArrayOutputStream( int size ) { - - if ( size < 0 ) - throw new IllegalArgumentException( "Negative initial size: " + size ); - buffer = new byte[size]; - } - - public void write( int b ) { - - int newcount = count + 1; - if ( newcount > buffer.length ) - buffer = Bytes.copyOf( buffer, Math.max( buffer.length << 1, newcount ) ); - buffer[count] = ( byte ) b; - count = newcount; - } - - public void write( byte b[], int off, int len ) { - - if ( ( off < 0 ) || ( off > b.length ) || ( len < 0 ) || ( ( off + len ) > b.length ) || ( ( off + len ) < 0 ) ) - throw new IndexOutOfBoundsException(); - if ( len == 0 ) - return; - int newcount = count + len; - if ( newcount > buffer.length ) - buffer = Bytes.copyOf( buffer, Math.max( buffer.length << 1, newcount ) ); - System.arraycopy( b, off, buffer, count, len ); - count = newcount; - } - - public int size() { - - return count; - } - - public void setWriteIndex( int index ) { - count = index; - } - - public void reset() { - - count = 0; - } - - public byte[] toByteArray() { - - return Bytes.copyOf( buffer, count ); - } - - public ByteBuffer toByteBuffer() { - - return ByteBuffer.wrap( buffer, 0, count ); - } - - public void writeTo( OutputStream out ) throws IOException { - - out.write( buffer, 0, count ); - } - - public String toString() { - - return new String( buffer, 0, count ); - } - - public String toString( String charset ) throws UnsupportedEncodingException { - - return new String( buffer, 0, count, charset ); - } - - public void close() throws IOException {} - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 deleted file mode 100644 index 518ce0ae7a8..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 +++ /dev/null @@ -1 +0,0 @@ -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol deleted file mode 100644 index 85233b7736a..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator deleted file mode 100644 index b2e5598772b..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator +++ /dev/null @@ -1,2 +0,0 @@ -dubbo=com.alibaba.dubbo.rpc.protocol.thrift.DubboClassNameGenerator -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftClassNameGenerator \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java deleted file mode 100644 index b73ee40fc45..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java +++ /dev/null @@ -1,658 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class $__ClassNameTestDubboStub { - - public interface Iface { - - public String echo(String arg); - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echo", new echo()); - return processMap; - } - - private static class echo extends org.apache.thrift.ProcessFunction { - public echo() { - super("echo"); - } - - protected echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { - echo_result result = new echo_result(); - result.success = iface.echo(args.arg); - return result; - } - } - - } - - public static class echo_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_args.class, metaDataMap); - } - - public echo_args() { - } - - public echo_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echo_args(echo_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echo_args deepCopy() { - return new echo_args(this); - } - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echo_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_args) - return this.equals((echo_args)that); - return false; - } - - public boolean equals(echo_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_args typedOther = (echo_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap); - } - - public echo_result() { - } - - public echo_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echo_result(echo_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echo_result deepCopy() { - return new echo_result(this); - } - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echo_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_result) - return this.equals((echo_result)that); - return false; - } - - public boolean equals(echo_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_result typedOther = (echo_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java deleted file mode 100644 index 45de6d30682..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * File Created at 2012-01-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ - -import com.alibaba.dubbo.rpc.protocol.thrift.ThriftUtils; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author kimi - */ -public class ClassNameTest { - - @Test - public void testThriftUtils() { - - Assert.assertEquals( $__ClassNameTestDubboStub.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - ClassNameTestDubbo.class.getName(), "echo" ) ); - - Assert.assertEquals( $__ClassNameTestDubboStub.echo_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - ClassNameTestDubbo.class.getName(), "echo" ) ); - - Assert.assertEquals( ClassNameTestThrift.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - ClassNameTestThrift.Iface.class.getName(), "echo" ) ); - - Assert.assertEquals( ClassNameTestThrift.echo_result.class.getName(), - ThriftUtils.generateMethodResultClassNameThrift( - ClassNameTestThrift.Iface.class.getName(), "echo" )); - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java deleted file mode 100644 index 71741e10571..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public interface ClassNameTestDubbo { - - public String echo(String arg); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java deleted file mode 100644 index 8d48664d46d..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java +++ /dev/null @@ -1,757 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ClassNameTestThrift { - - public interface Iface { - - public String echo(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - public void echo(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - } - - public static class Client extends org.apache.thrift.TServiceClient implements Iface { - public static class Factory implements org.apache.thrift.TServiceClientFactory { - public Factory() {} - public Client getClient(org.apache.thrift.protocol.TProtocol prot) { - return new Client(prot); - } - public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - return new Client(iprot, oprot); - } - } - - public Client(org.apache.thrift.protocol.TProtocol prot) - { - super(prot, prot); - } - - public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - super(iprot, oprot); - } - - public String echo(String arg) throws org.apache.thrift.TException - { - send_echo(arg); - return recv_echo(); - } - - public void send_echo(String arg) throws org.apache.thrift.TException - { - echo_args args = new echo_args(); - args.setArg(arg); - sendBase("echo", args); - } - - public String recv_echo() throws org.apache.thrift.TException - { - echo_result result = new echo_result(); - receiveBase(result, "echo"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echo failed: unknown result"); - } - - } - public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { - private org.apache.thrift.async.TAsyncClientManager clientManager; - private org.apache.thrift.protocol.TProtocolFactory protocolFactory; - public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { - this.clientManager = clientManager; - this.protocolFactory = protocolFactory; - } - public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { - return new AsyncClient(protocolFactory, clientManager, transport); - } - } - - public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { - super(protocolFactory, clientManager, transport); - } - - public void echo(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echo_call method_call = new echo_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echo_call extends org.apache.thrift.async.TAsyncMethodCall { - private String arg; - public echo_call(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echo", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echo_args args = new echo_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echo(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echo", new echo()); - return processMap; - } - - private static class echo extends org.apache.thrift.ProcessFunction { - public echo() { - super("echo"); - } - - protected echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { - echo_result result = new echo_result(); - result.success = iface.echo(args.arg); - return result; - } - } - - } - - public static class echo_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_args.class, metaDataMap); - } - - public echo_args() { - } - - public echo_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echo_args(echo_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echo_args deepCopy() { - return new echo_args(this); - } - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echo_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_args) - return this.equals((echo_args)that); - return false; - } - - public boolean equals(echo_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_args typedOther = (echo_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap); - } - - public echo_result() { - } - - public echo_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echo_result(echo_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echo_result deepCopy() { - return new echo_result(this); - } - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echo_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_result) - return this.equals((echo_result)that); - return false; - } - - public boolean equals(echo_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_result typedOther = (echo_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java deleted file mode 100644 index f29d6b74934..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java +++ /dev/null @@ -1,4376 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.dubbo; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class $__DemoStub { - - public interface Iface { - - public boolean echoBool(boolean arg); - - public byte echoByte(byte arg); - - public short echoI16(short arg); - - public int echoI32(int arg); - - public long echoI64(long arg); - - public double echoDouble(double arg); - - public String echoString(String arg); - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echoBool", new echoBool()); - processMap.put("echoByte", new echoByte()); - processMap.put("echoI16", new echoI16()); - processMap.put("echoI32", new echoI32()); - processMap.put("echoI64", new echoI64()); - processMap.put("echoDouble", new echoDouble()); - processMap.put("echoString", new echoString()); - return processMap; - } - - private static class echoBool extends org.apache.thrift.ProcessFunction { - public echoBool() { - super("echoBool"); - } - - protected echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { - echoBool_result result = new echoBool_result(); - result.success = iface.echoBool(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoByte extends org.apache.thrift.ProcessFunction { - public echoByte() { - super("echoByte"); - } - - protected echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { - echoByte_result result = new echoByte_result(); - result.success = iface.echoByte(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI16 extends org.apache.thrift.ProcessFunction { - public echoI16() { - super("echoI16"); - } - - protected echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { - echoI16_result result = new echoI16_result(); - result.success = iface.echoI16(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI32 extends org.apache.thrift.ProcessFunction { - public echoI32() { - super("echoI32"); - } - - protected echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { - echoI32_result result = new echoI32_result(); - result.success = iface.echoI32(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI64 extends org.apache.thrift.ProcessFunction { - public echoI64() { - super("echoI64"); - } - - protected echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { - echoI64_result result = new echoI64_result(); - result.success = iface.echoI64(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoDouble extends org.apache.thrift.ProcessFunction { - public echoDouble() { - super("echoDouble"); - } - - protected echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { - echoDouble_result result = new echoDouble_result(); - result.success = iface.echoDouble(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoString extends org.apache.thrift.ProcessFunction { - public echoString() { - super("echoString"); - } - - protected echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { - echoString_result result = new echoString_result(); - result.success = iface.echoString(args.arg); - return result; - } - } - - } - - public static class echoBool_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BOOL, (short)1); - - public boolean arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_args.class, metaDataMap); - } - - public echoBool_args() { - } - - public echoBool_args( - boolean arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_args(echoBool_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoBool_args deepCopy() { - return new echoBool_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = false; - } - - public boolean isArg() { - return this.arg; - } - - public echoBool_args setArg(boolean arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Boolean.valueOf(isArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_args) - return this.equals((echoBool_args)that); - return false; - } - - public boolean equals(echoBool_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_args typedOther = (echoBool_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.arg = iprot.readBool(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeBool(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); - - public boolean success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_result.class, metaDataMap); - } - - public echoBool_result() { - } - - public echoBool_result( - boolean success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_result(echoBool_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoBool_result deepCopy() { - return new echoBool_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = false; - } - - public boolean isSuccess() { - return this.success; - } - - public echoBool_result setSuccess(boolean success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Boolean.valueOf(isSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_result) - return this.equals((echoBool_result)that); - return false; - } - - public boolean equals(echoBool_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_result typedOther = (echoBool_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.success = iprot.readBool(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeBool(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BYTE, (short)1); - - public byte arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_args.class, metaDataMap); - } - - public echoByte_args() { - } - - public echoByte_args( - byte arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_args(echoByte_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoByte_args deepCopy() { - return new echoByte_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public byte getArg() { - return this.arg; - } - - public echoByte_args setArg(byte arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Byte.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_args) - return this.equals((echoByte_args)that); - return false; - } - - public boolean equals(echoByte_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_args typedOther = (echoByte_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.arg = iprot.readByte(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeByte(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BYTE, (short)0); - - public byte success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_result.class, metaDataMap); - } - - public echoByte_result() { - } - - public echoByte_result( - byte success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_result(echoByte_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoByte_result deepCopy() { - return new echoByte_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public byte getSuccess() { - return this.success; - } - - public echoByte_result setSuccess(byte success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Byte.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_result) - return this.equals((echoByte_result)that); - return false; - } - - public boolean equals(echoByte_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_result typedOther = (echoByte_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.success = iprot.readByte(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeByte(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I16, (short)1); - - public short arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_args.class, metaDataMap); - } - - public echoI16_args() { - } - - public echoI16_args( - short arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_args(echoI16_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI16_args deepCopy() { - return new echoI16_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public short getArg() { - return this.arg; - } - - public echoI16_args setArg(short arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Short.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_args) - return this.equals((echoI16_args)that); - return false; - } - - public boolean equals(echoI16_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_args typedOther = (echoI16_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.arg = iprot.readI16(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI16(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I16, (short)0); - - public short success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_result.class, metaDataMap); - } - - public echoI16_result() { - } - - public echoI16_result( - short success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_result(echoI16_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI16_result deepCopy() { - return new echoI16_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public short getSuccess() { - return this.success; - } - - public echoI16_result setSuccess(short success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Short.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_result) - return this.equals((echoI16_result)that); - return false; - } - - public boolean equals(echoI16_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_result typedOther = (echoI16_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.success = iprot.readI16(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI16(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I32, (short)1); - - public int arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_args.class, metaDataMap); - } - - public echoI32_args() { - } - - public echoI32_args( - int arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_args(echoI32_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI32_args deepCopy() { - return new echoI32_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public int getArg() { - return this.arg; - } - - public echoI32_args setArg(int arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Integer.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_args) - return this.equals((echoI32_args)that); - return false; - } - - public boolean equals(echoI32_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_args typedOther = (echoI32_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.arg = iprot.readI32(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI32(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I32, (short)0); - - public int success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_result.class, metaDataMap); - } - - public echoI32_result() { - } - - public echoI32_result( - int success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_result(echoI32_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI32_result deepCopy() { - return new echoI32_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public int getSuccess() { - return this.success; - } - - public echoI32_result setSuccess(int success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Integer.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_result) - return this.equals((echoI32_result)that); - return false; - } - - public boolean equals(echoI32_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_result typedOther = (echoI32_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.success = iprot.readI32(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI32(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I64, (short)1); - - public long arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_args.class, metaDataMap); - } - - public echoI64_args() { - } - - public echoI64_args( - long arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_args(echoI64_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI64_args deepCopy() { - return new echoI64_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public long getArg() { - return this.arg; - } - - public echoI64_args setArg(long arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Long.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_args) - return this.equals((echoI64_args)that); - return false; - } - - public boolean equals(echoI64_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_args typedOther = (echoI64_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.arg = iprot.readI64(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI64(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0); - - public long success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_result.class, metaDataMap); - } - - public echoI64_result() { - } - - public echoI64_result( - long success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_result(echoI64_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI64_result deepCopy() { - return new echoI64_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public long getSuccess() { - return this.success; - } - - public echoI64_result setSuccess(long success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Long.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_result) - return this.equals((echoI64_result)that); - return false; - } - - public boolean equals(echoI64_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_result typedOther = (echoI64_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.success = iprot.readI64(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI64(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.DOUBLE, (short)1); - - public double arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_args.class, metaDataMap); - } - - public echoDouble_args() { - } - - public echoDouble_args( - double arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_args(echoDouble_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoDouble_args deepCopy() { - return new echoDouble_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0.0; - } - - public double getArg() { - return this.arg; - } - - public echoDouble_args setArg(double arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Double.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_args) - return this.equals((echoDouble_args)that); - return false; - } - - public boolean equals(echoDouble_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_args typedOther = (echoDouble_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.arg = iprot.readDouble(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeDouble(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.DOUBLE, (short)0); - - public double success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_result.class, metaDataMap); - } - - public echoDouble_result() { - } - - public echoDouble_result( - double success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_result(echoDouble_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoDouble_result deepCopy() { - return new echoDouble_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0.0; - } - - public double getSuccess() { - return this.success; - } - - public echoDouble_result setSuccess(double success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Double.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_result) - return this.equals((echoDouble_result)that); - return false; - } - - public boolean equals(echoDouble_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_result typedOther = (echoDouble_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.success = iprot.readDouble(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeDouble(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_args.class, metaDataMap); - } - - public echoString_args() { - } - - public echoString_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echoString_args(echoString_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echoString_args deepCopy() { - return new echoString_args(this); - } - - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echoString_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_args) - return this.equals((echoString_args)that); - return false; - } - - public boolean equals(echoString_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_args typedOther = (echoString_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_result.class, metaDataMap); - } - - public echoString_result() { - } - - public echoString_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echoString_result(echoString_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echoString_result deepCopy() { - return new echoString_result(this); - } - - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echoString_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_result) - return this.equals((echoString_result)that); - return false; - } - - public boolean equals(echoString_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_result typedOther = (echoString_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java deleted file mode 100644 index 8993ad2cfe2..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.dubbo; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public interface Demo { - - public boolean echoBool(boolean arg); - - public byte echoByte(byte arg); - - public short echoI16(short arg); - - public int echoI32(int arg); - - public long echoI64(long arg); - - public double echoDouble(double arg); - - public String echoString(String arg); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java deleted file mode 100644 index 2be2cfa99f5..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java +++ /dev/null @@ -1,4805 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.thrift; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Demo { - - public interface Iface { - - public boolean echoBool(boolean arg) throws org.apache.thrift.TException; - - public byte echoByte(byte arg) throws org.apache.thrift.TException; - - public short echoI16(short arg) throws org.apache.thrift.TException; - - public int echoI32(int arg) throws org.apache.thrift.TException; - - public long echoI64(long arg) throws org.apache.thrift.TException; - - public double echoDouble(double arg) throws org.apache.thrift.TException; - - public String echoString(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - public void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - } - - public static class Client extends org.apache.thrift.TServiceClient implements Iface { - public static class Factory implements org.apache.thrift.TServiceClientFactory { - public Factory() {} - public Client getClient(org.apache.thrift.protocol.TProtocol prot) { - return new Client(prot); - } - public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - return new Client(iprot, oprot); - } - } - - public Client(org.apache.thrift.protocol.TProtocol prot) - { - super(prot, prot); - } - - public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - super(iprot, oprot); - } - - public boolean echoBool(boolean arg) throws org.apache.thrift.TException - { - send_echoBool(arg); - return recv_echoBool(); - } - - public void send_echoBool(boolean arg) throws org.apache.thrift.TException - { - echoBool_args args = new echoBool_args(); - args.setArg(arg); - sendBase("echoBool", args); - } - - public boolean recv_echoBool() throws org.apache.thrift.TException - { - echoBool_result result = new echoBool_result(); - receiveBase(result, "echoBool"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoBool failed: unknown result"); - } - - public byte echoByte(byte arg) throws org.apache.thrift.TException - { - send_echoByte(arg); - return recv_echoByte(); - } - - public void send_echoByte(byte arg) throws org.apache.thrift.TException - { - echoByte_args args = new echoByte_args(); - args.setArg(arg); - sendBase("echoByte", args); - } - - public byte recv_echoByte() throws org.apache.thrift.TException - { - echoByte_result result = new echoByte_result(); - receiveBase(result, "echoByte"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoByte failed: unknown result"); - } - - public short echoI16(short arg) throws org.apache.thrift.TException - { - send_echoI16(arg); - return recv_echoI16(); - } - - public void send_echoI16(short arg) throws org.apache.thrift.TException - { - echoI16_args args = new echoI16_args(); - args.setArg(arg); - sendBase("echoI16", args); - } - - public short recv_echoI16() throws org.apache.thrift.TException - { - echoI16_result result = new echoI16_result(); - receiveBase(result, "echoI16"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI16 failed: unknown result"); - } - - public int echoI32(int arg) throws org.apache.thrift.TException - { - send_echoI32(arg); - return recv_echoI32(); - } - - public void send_echoI32(int arg) throws org.apache.thrift.TException - { - echoI32_args args = new echoI32_args(); - args.setArg(arg); - sendBase("echoI32", args); - } - - public int recv_echoI32() throws org.apache.thrift.TException - { - echoI32_result result = new echoI32_result(); - receiveBase(result, "echoI32"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI32 failed: unknown result"); - } - - public long echoI64(long arg) throws org.apache.thrift.TException - { - send_echoI64(arg); - return recv_echoI64(); - } - - public void send_echoI64(long arg) throws org.apache.thrift.TException - { - echoI64_args args = new echoI64_args(); - args.setArg(arg); - sendBase("echoI64", args); - } - - public long recv_echoI64() throws org.apache.thrift.TException - { - echoI64_result result = new echoI64_result(); - receiveBase(result, "echoI64"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI64 failed: unknown result"); - } - - public double echoDouble(double arg) throws org.apache.thrift.TException - { - send_echoDouble(arg); - return recv_echoDouble(); - } - - public void send_echoDouble(double arg) throws org.apache.thrift.TException - { - echoDouble_args args = new echoDouble_args(); - args.setArg(arg); - sendBase("echoDouble", args); - } - - public double recv_echoDouble() throws org.apache.thrift.TException - { - echoDouble_result result = new echoDouble_result(); - receiveBase(result, "echoDouble"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoDouble failed: unknown result"); - } - - public String echoString(String arg) throws org.apache.thrift.TException - { - send_echoString(arg); - return recv_echoString(); - } - - public void send_echoString(String arg) throws org.apache.thrift.TException - { - echoString_args args = new echoString_args(); - args.setArg(arg); - sendBase("echoString", args); - } - - public String recv_echoString() throws org.apache.thrift.TException - { - echoString_result result = new echoString_result(); - receiveBase(result, "echoString"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoString failed: unknown result"); - } - - } - public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { - private org.apache.thrift.async.TAsyncClientManager clientManager; - private org.apache.thrift.protocol.TProtocolFactory protocolFactory; - public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { - this.clientManager = clientManager; - this.protocolFactory = protocolFactory; - } - public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { - return new AsyncClient(protocolFactory, clientManager, transport); - } - } - - public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { - super(protocolFactory, clientManager, transport); - } - - public void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoBool_call method_call = new echoBool_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoBool_call extends org.apache.thrift.async.TAsyncMethodCall { - private boolean arg; - public echoBool_call(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoBool", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoBool_args args = new echoBool_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public boolean getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoBool(); - } - } - - public void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoByte_call method_call = new echoByte_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoByte_call extends org.apache.thrift.async.TAsyncMethodCall { - private byte arg; - public echoByte_call(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoByte", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoByte_args args = new echoByte_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public byte getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoByte(); - } - } - - public void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI16_call method_call = new echoI16_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI16_call extends org.apache.thrift.async.TAsyncMethodCall { - private short arg; - public echoI16_call(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI16", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI16_args args = new echoI16_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public short getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI16(); - } - } - - public void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI32_call method_call = new echoI32_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI32_call extends org.apache.thrift.async.TAsyncMethodCall { - private int arg; - public echoI32_call(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI32", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI32_args args = new echoI32_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public int getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI32(); - } - } - - public void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI64_call method_call = new echoI64_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI64_call extends org.apache.thrift.async.TAsyncMethodCall { - private long arg; - public echoI64_call(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI64", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI64_args args = new echoI64_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public long getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI64(); - } - } - - public void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoDouble_call method_call = new echoDouble_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoDouble_call extends org.apache.thrift.async.TAsyncMethodCall { - private double arg; - public echoDouble_call(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoDouble", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoDouble_args args = new echoDouble_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public double getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoDouble(); - } - } - - public void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoString_call method_call = new echoString_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoString_call extends org.apache.thrift.async.TAsyncMethodCall { - private String arg; - public echoString_call(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoString", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoString_args args = new echoString_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoString(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echoBool", new echoBool()); - processMap.put("echoByte", new echoByte()); - processMap.put("echoI16", new echoI16()); - processMap.put("echoI32", new echoI32()); - processMap.put("echoI64", new echoI64()); - processMap.put("echoDouble", new echoDouble()); - processMap.put("echoString", new echoString()); - return processMap; - } - - private static class echoBool extends org.apache.thrift.ProcessFunction { - public echoBool() { - super("echoBool"); - } - - protected echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { - echoBool_result result = new echoBool_result(); - result.success = iface.echoBool(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoByte extends org.apache.thrift.ProcessFunction { - public echoByte() { - super("echoByte"); - } - - protected echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { - echoByte_result result = new echoByte_result(); - result.success = iface.echoByte(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI16 extends org.apache.thrift.ProcessFunction { - public echoI16() { - super("echoI16"); - } - - protected echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { - echoI16_result result = new echoI16_result(); - result.success = iface.echoI16(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI32 extends org.apache.thrift.ProcessFunction { - public echoI32() { - super("echoI32"); - } - - protected echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { - echoI32_result result = new echoI32_result(); - result.success = iface.echoI32(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI64 extends org.apache.thrift.ProcessFunction { - public echoI64() { - super("echoI64"); - } - - protected echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { - echoI64_result result = new echoI64_result(); - result.success = iface.echoI64(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoDouble extends org.apache.thrift.ProcessFunction { - public echoDouble() { - super("echoDouble"); - } - - protected echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { - echoDouble_result result = new echoDouble_result(); - result.success = iface.echoDouble(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoString extends org.apache.thrift.ProcessFunction { - public echoString() { - super("echoString"); - } - - protected echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { - echoString_result result = new echoString_result(); - result.success = iface.echoString(args.arg); - return result; - } - } - - } - - public static class echoBool_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BOOL, (short)1); - - public boolean arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_args.class, metaDataMap); - } - - public echoBool_args() { - } - - public echoBool_args( - boolean arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_args(echoBool_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoBool_args deepCopy() { - return new echoBool_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = false; - } - - public boolean isArg() { - return this.arg; - } - - public echoBool_args setArg(boolean arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Boolean.valueOf(isArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_args) - return this.equals((echoBool_args)that); - return false; - } - - public boolean equals(echoBool_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_args typedOther = (echoBool_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.arg = iprot.readBool(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeBool(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); - - public boolean success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_result.class, metaDataMap); - } - - public echoBool_result() { - } - - public echoBool_result( - boolean success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_result(echoBool_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoBool_result deepCopy() { - return new echoBool_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = false; - } - - public boolean isSuccess() { - return this.success; - } - - public echoBool_result setSuccess(boolean success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Boolean.valueOf(isSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_result) - return this.equals((echoBool_result)that); - return false; - } - - public boolean equals(echoBool_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_result typedOther = (echoBool_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.success = iprot.readBool(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeBool(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BYTE, (short)1); - - public byte arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_args.class, metaDataMap); - } - - public echoByte_args() { - } - - public echoByte_args( - byte arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_args(echoByte_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoByte_args deepCopy() { - return new echoByte_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public byte getArg() { - return this.arg; - } - - public echoByte_args setArg(byte arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Byte.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_args) - return this.equals((echoByte_args)that); - return false; - } - - public boolean equals(echoByte_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_args typedOther = (echoByte_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.arg = iprot.readByte(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeByte(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BYTE, (short)0); - - public byte success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_result.class, metaDataMap); - } - - public echoByte_result() { - } - - public echoByte_result( - byte success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_result(echoByte_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoByte_result deepCopy() { - return new echoByte_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public byte getSuccess() { - return this.success; - } - - public echoByte_result setSuccess(byte success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Byte.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_result) - return this.equals((echoByte_result)that); - return false; - } - - public boolean equals(echoByte_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_result typedOther = (echoByte_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.success = iprot.readByte(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeByte(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I16, (short)1); - - public short arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_args.class, metaDataMap); - } - - public echoI16_args() { - } - - public echoI16_args( - short arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_args(echoI16_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI16_args deepCopy() { - return new echoI16_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public short getArg() { - return this.arg; - } - - public echoI16_args setArg(short arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Short.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_args) - return this.equals((echoI16_args)that); - return false; - } - - public boolean equals(echoI16_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_args typedOther = (echoI16_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.arg = iprot.readI16(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI16(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I16, (short)0); - - public short success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_result.class, metaDataMap); - } - - public echoI16_result() { - } - - public echoI16_result( - short success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_result(echoI16_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI16_result deepCopy() { - return new echoI16_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public short getSuccess() { - return this.success; - } - - public echoI16_result setSuccess(short success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Short.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_result) - return this.equals((echoI16_result)that); - return false; - } - - public boolean equals(echoI16_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_result typedOther = (echoI16_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.success = iprot.readI16(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI16(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I32, (short)1); - - public int arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_args.class, metaDataMap); - } - - public echoI32_args() { - } - - public echoI32_args( - int arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_args(echoI32_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI32_args deepCopy() { - return new echoI32_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public int getArg() { - return this.arg; - } - - public echoI32_args setArg(int arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Integer.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_args) - return this.equals((echoI32_args)that); - return false; - } - - public boolean equals(echoI32_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_args typedOther = (echoI32_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.arg = iprot.readI32(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI32(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I32, (short)0); - - public int success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_result.class, metaDataMap); - } - - public echoI32_result() { - } - - public echoI32_result( - int success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_result(echoI32_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI32_result deepCopy() { - return new echoI32_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public int getSuccess() { - return this.success; - } - - public echoI32_result setSuccess(int success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Integer.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_result) - return this.equals((echoI32_result)that); - return false; - } - - public boolean equals(echoI32_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_result typedOther = (echoI32_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.success = iprot.readI32(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI32(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I64, (short)1); - - public long arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_args.class, metaDataMap); - } - - public echoI64_args() { - } - - public echoI64_args( - long arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_args(echoI64_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI64_args deepCopy() { - return new echoI64_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public long getArg() { - return this.arg; - } - - public echoI64_args setArg(long arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Long.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_args) - return this.equals((echoI64_args)that); - return false; - } - - public boolean equals(echoI64_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_args typedOther = (echoI64_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.arg = iprot.readI64(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI64(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0); - - public long success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_result.class, metaDataMap); - } - - public echoI64_result() { - } - - public echoI64_result( - long success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_result(echoI64_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI64_result deepCopy() { - return new echoI64_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public long getSuccess() { - return this.success; - } - - public echoI64_result setSuccess(long success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Long.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_result) - return this.equals((echoI64_result)that); - return false; - } - - public boolean equals(echoI64_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_result typedOther = (echoI64_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.success = iprot.readI64(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI64(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.DOUBLE, (short)1); - - public double arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_args.class, metaDataMap); - } - - public echoDouble_args() { - } - - public echoDouble_args( - double arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_args(echoDouble_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoDouble_args deepCopy() { - return new echoDouble_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0.0; - } - - public double getArg() { - return this.arg; - } - - public echoDouble_args setArg(double arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Double.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_args) - return this.equals((echoDouble_args)that); - return false; - } - - public boolean equals(echoDouble_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_args typedOther = (echoDouble_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.arg = iprot.readDouble(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeDouble(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.DOUBLE, (short)0); - - public double success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_result.class, metaDataMap); - } - - public echoDouble_result() { - } - - public echoDouble_result( - double success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_result(echoDouble_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoDouble_result deepCopy() { - return new echoDouble_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0.0; - } - - public double getSuccess() { - return this.success; - } - - public echoDouble_result setSuccess(double success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Double.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_result) - return this.equals((echoDouble_result)that); - return false; - } - - public boolean equals(echoDouble_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_result typedOther = (echoDouble_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.success = iprot.readDouble(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeDouble(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_args.class, metaDataMap); - } - - public echoString_args() { - } - - public echoString_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echoString_args(echoString_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echoString_args deepCopy() { - return new echoString_args(this); - } - - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echoString_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_args) - return this.equals((echoString_args)that); - return false; - } - - public boolean equals(echoString_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_args typedOther = (echoString_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_result.class, metaDataMap); - } - - public echoString_result() { - } - - public echoString_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echoString_result(echoString_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echoString_result deepCopy() { - return new echoString_result(this); - } - - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echoString_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_result) - return this.equals((echoString_result)that); - return false; - } - - public boolean equals(echoString_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_result typedOther = (echoString_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java deleted file mode 100644 index 6b68d331b29..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * File Created at 2011-11-25 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TServerTransport; -import org.apache.thrift.transport.TTransportFactory; -import org.junit.After; -import org.junit.Before; - -/** - * @author gang.lvg 2011-11-25 13:05 - */ -public abstract class AbstractTest { - - static final int PORT = 30660; - - protected TServer server; - - protected Protocol protocol; - - protected Invoker invoker; - - protected void init() throws Exception { - TServerTransport serverTransport = new TServerSocket( PORT ); - - TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory(); - - server = new TThreadPoolServer( - new TThreadPoolServer.Args( serverTransport ) - .inputProtocolFactory( bFactory ) - .outputProtocolFactory( bFactory ) - .inputTransportFactory( getTransportFactory() ) - .outputTransportFactory( getTransportFactory() ) - .processor( getProcessor() ) ); - - Thread startTread = new Thread() { - - @Override - public void run() { - server.serve(); - } - - }; - - startTread.setName( "thrift-server" ); - - startTread.start(); - - while( !server.isServing() ) { - Thread.sleep( 100 ); - } - - protocol = ExtensionLoader.getExtensionLoader(Protocol.class) - .getExtension( ThriftProtocol.NAME ); - - invoker = protocol.refer( getInterface(), getUrl() ); - - } - - protected void destroy() throws Exception { - - if ( server != null ) { - server.stop(); - server = null; - } - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - protected TTransportFactory getTransportFactory() { - return new FramedTransportFactory(); - } - - protected $__DemoStub.Iface getServiceImpl() { - return new DubboDemoImpl(); - } - - protected TProcessor getProcessor() { - MultiServiceProcessor result = new MultiServiceProcessor(); - result.addProcessor( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class, - new $__DemoStub.Processor( getServiceImpl() ) ); - return result; - } - - protected Class getInterface() { - return Demo.class; - } - - protected URL getUrl() { - return URL.valueOf( - "thrift://127.0.0.1:" + PORT + "/" + getInterface().getName() ); - } - - @After - public void tearDown() throws Exception{ - destroy(); - } - - @Before - public void setUp() throws Exception { - init(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java deleted file mode 100644 index 983e5799d92..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * File Created at 2011-11-23 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author gang.lvg 2011-11-23 14:17 - */ -public class DemoImpl { - - public boolean echoBool( boolean arg ) { - - return arg; - } - - public byte echoByte( byte arg ) { - - return arg; - } - - public short echoI16( short arg ) { - - return arg; - } - - public int echoI32( int arg ) { - - return arg; - } - - public long echoI64( long arg ) { - - return arg; - } - - public double echoDouble( double arg ) { - - return arg; - } - - public String echoString( String arg ) { - - return arg; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java deleted file mode 100644 index 37c7a056d76..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * File Created at 2011-12-31 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; - -/** - * @author kimi - */ -public class DubboDemoImpl extends DemoImpl implements Demo, $__DemoStub.Iface {} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java deleted file mode 100644 index 2ca4a5b54f6..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TTransport; -import org.apache.thrift.transport.TTransportFactory; - -/** - * @author kimi - */ -public class FramedTransportFactory extends TTransportFactory { - - @Override - public TTransport getTransport( TTransport trans ) { - - return new TFramedTransport( trans ); - } -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java deleted file mode 100644 index a3775fc01f1..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.transport.ChannelHandler; -import com.alibaba.dubbo.remoting.exception.RemotingException; - -import java.net.InetSocketAddress; - -/** - * @author gang.lvg - */ -public class MockedChannel implements Channel { - - private URL url; - - public MockedChannel( URL url ) { - this.url = url; - } - - public InetSocketAddress getRemoteAddress() { - - return null; - } - - public boolean isConnected() { - - return false; - } - - public boolean hasAttribute( String key ) { - - return false; - } - - public Object getAttribute( String key ) { - - return null; - } - - public void setAttribute( String key, Object value ) { - - } - - public void removeAttribute( String key ) { - - } - - public URL getUrl() { - return url; - } - - public ChannelHandler getChannelHandler() { - - return null; - } - - public InetSocketAddress getLocalAddress() { - - return null; - } - - public void send( Object message ) throws RemotingException { - - } - - public void send( Object message, boolean sent ) throws RemotingException { - - } - - public void close() { - - } - - public void close( int timeout ) { - - } - - public boolean isClosed() { - - return false; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java deleted file mode 100644 index 58ecbe1520b..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author kimi - */ -public class ServerExceptionTest extends AbstractTest { - - @Override - protected $__DemoStub.Iface getServiceImpl() { - - return new $__DemoStub.Iface () { - - public boolean echoBool( boolean arg ) { - - return false; - } - - public byte echoByte( byte arg ) { - - return 0; - } - - public short echoI16( short arg ) { - - return 0; - } - - public int echoI32( int arg ) { - - return 0; - } - - public long echoI64( long arg ) { - - return 0; - } - - public double echoDouble( double arg ) { - return 0; - } - - public String echoString( String arg ) { - // 在 server 端,thrift 无法处理 idl 中没有声明的异常 - throw new RuntimeException( "just for test" ); - } - }; - - } - - @Test( expected = RpcException.class ) - public void testServerException() throws Exception { - - Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - Result result = invoker.invoke( invocation ); - - System.out.println( result ); - - } - - @Override - protected URL getUrl() { - URL url = super.getUrl(); -// url = url.addParameter( Constants.TIMEOUT_KEY, Integer.MAX_VALUE ); - return url; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java deleted file mode 100644 index 224e1c8a93c..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TServerTransport; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.util.Map; - -/** - * @author kimi - */ -public class ServiceMethodNotFoundTest extends AbstractTest { - - private URL url; - - protected void init() throws Exception { - - TServerTransport serverTransport = new TServerSocket( PORT ); - - DubboDemoImpl impl = new DubboDemoImpl(); - - $__DemoStub.Processor processor = new $__DemoStub.Processor( impl ); - - // for test - Field field = processor.getClass().getSuperclass().getDeclaredField( "processMap" ); - - field.setAccessible( true ); - - Object obj = field.get( processor ); - - if ( obj instanceof Map ) { - ( ( Map ) obj ).remove( "echoString" ); - } - // ~ - - TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory(); - - MultiServiceProcessor wrapper = new MultiServiceProcessor(); - wrapper.addProcessor( Demo.class, processor ); - - server = new TThreadPoolServer( - new TThreadPoolServer.Args( serverTransport ) - .inputProtocolFactory( bFactory ) - .outputProtocolFactory( bFactory ) - .inputTransportFactory( getTransportFactory() ) - .outputTransportFactory( getTransportFactory() ) - .processor( wrapper ) ); - - Thread startTread = new Thread() { - - @Override - public void run() { - - server.serve(); - } - - }; - - startTread.start(); - - while ( !server.isServing() ) { - Thread.sleep( 100 ); - } - - } - - @Before - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName() ); - - } - - @After - public void tearDown() throws Exception { - - destroy(); - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - @Test - public void testServiceMethodNotFound() throws Exception { - // FIXME - /*url = url.addParameter( "echoString." + Constants.TIMEOUT_KEY, Integer.MAX_VALUE ); - - invoker = protocol.refer( Demo.class, url ); - - org.junit.Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - invocation.setAttachment(Constants.INTERFACE_KEY, DemoImpl.class.getName()); - - Result result = invoker.invoke( invocation ); - - Assert.assertNull( result.getResult() ); - - Assert.assertTrue( result.getException() instanceof RpcException );*/ - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java deleted file mode 100644 index 7306b3bb76f..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ /dev/null @@ -1,453 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - *

- * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - *

- * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.transport.Channel; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; -import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; -import com.alibaba.dubbo.remoting.message.Request; -import com.alibaba.dubbo.remoting.message.Response; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.gen.thrift.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; -import org.apache.thrift.TApplicationException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; -import org.apache.thrift.transport.TTransport; -import org.junit.Assert; -import org.junit.Test; - -import java.io.ByteArrayInputStream; - -/** - * @author gang.lvg - */ -public class ThriftCodecTest { - - private ThriftCodec codec = new ThriftCodec(); - private Channel channel = new MockedChannel(URL.valueOf("thrift://127.0.0.1")); - - @Test - public void testEncodeRequest() throws Exception { - - Request request = createRequest(); - - ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024); - - codec.encode(channel, output, request); - - byte[] bytes = new byte[output.readableBytes()]; - output.readBytes(bytes); - - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - - TTransport transport = new TIOStreamTransport(bis); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - // frame - byte[] length = new byte[4]; - transport.read(length, 0, 4); - - if (bis.markSupported()) { - bis.mark(0); - } - - // magic - Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - - // message length - int messageLength = protocol.readI32(); - Assert.assertEquals(messageLength + 4, bytes.length); - - // header length - short headerLength = protocol.readI16(); - // version - Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - // service name - Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - // dubbo request id - Assert.assertEquals(request.getId(), protocol.readI64()); - - // test message header length - if (bis.markSupported()) { - bis.reset(); - bis.skip(headerLength); - } - - TMessage message = protocol.readMessageBegin(); - - Demo.echoString_args args = new Demo.echoString_args(); - - args.read(protocol); - - protocol.readMessageEnd(); - - Assert.assertEquals("echoString", message.name); - - Assert.assertEquals(TMessageType.CALL, message.type); - - Assert.assertEquals("Hello, World!", args.getArg()); - - } - - @Test - public void testDecodeReplyResponse() throws Exception { - - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); - - Request request = createRequest(); - - DefaultFuture future = new DefaultFuture(channel, request, 10); - - TMessage message = new TMessage("echoString", TMessageType.REPLY, ThriftCodec.getSeqId()); - - Demo.echoString_result methodResult = new Demo.echoString_result(); - - methodResult.success = "Hello, World!"; - - TTransport transport = new TIOStreamTransport(bos); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - int messageLength, headerLength; - // prepare - protocol.writeI16(ThriftCodec.MAGIC); - protocol.writeI32(Integer.MAX_VALUE); - protocol.writeI16(Short.MAX_VALUE); - protocol.writeByte(ThriftCodec.VERSION); - protocol.writeString(Demo.Iface.class.getName()); - protocol.writeI64(request.getId()); - protocol.getTransport().flush(); - headerLength = bos.size(); - - protocol.writeMessageBegin(message); - methodResult.write(protocol); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); - protocol.writeI32(messageLength); - bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); - protocol.writeI16((short) (0xffff & headerLength)); - } finally { - bos.setWriteIndex(oldIndex); - } - // prepare - - byte[] buf = new byte[4 + bos.size()]; - System.arraycopy(bos.toByteArray(), 0, buf, 4, bos.size()); - - ChannelBuffer bis = ChannelBuffers.wrappedBuffer(buf); - - Object obj = codec.decode((Channel) null, bis); - - Assert.assertNotNull(obj); - - Assert.assertEquals(true, obj instanceof Response); - - Response response = (Response) obj; - - Assert.assertEquals(request.getId(), response.getId()); - - Assert.assertTrue(response.getResult() instanceof RpcResult); - - RpcResult result = (RpcResult) response.getResult(); - - Assert.assertTrue(result.getResult() instanceof String); - - Assert.assertEquals(methodResult.success, result.getResult()); - - } - - @Test - public void testDecodeExceptionResponse() throws Exception { - - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName()); - - Channel channel = new MockedChannel(url); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); - - Request request = createRequest(); - - DefaultFuture future = new DefaultFuture(channel, request, 10); - - TMessage message = new TMessage("echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId()); - - TTransport transport = new TIOStreamTransport(bos); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - TApplicationException exception = new TApplicationException(); - - int messageLength, headerLength; - // prepare - protocol.writeI16(ThriftCodec.MAGIC); - protocol.writeI32(Integer.MAX_VALUE); - protocol.writeI16(Short.MAX_VALUE); - protocol.writeByte(ThriftCodec.VERSION); - protocol.writeString(Demo.class.getName()); - protocol.writeI64(request.getId()); - protocol.getTransport().flush(); - headerLength = bos.size(); - - protocol.writeMessageBegin(message); - exception.write(protocol); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); - protocol.writeI32(messageLength); - bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); - protocol.writeI16((short) (0xffff & headerLength)); - } finally { - bos.setWriteIndex(oldIndex); - } - // prepare - - ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray())); - - Object obj = codec.decode((Channel) null, bis); - - Assert.assertNotNull(obj); - - Assert.assertTrue(obj instanceof Response); - - Response response = (Response) obj; - - Assert.assertTrue(response.getResult() instanceof RpcResult); - - RpcResult result = (RpcResult) response.getResult(); - - Assert.assertTrue(result.hasException()); - - Assert.assertTrue(result.getException() instanceof RpcException); - - } - - @Test - public void testEncodeReplyResponse() throws Exception { - - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - Request request = createRequest(); - - RpcResult rpcResult = new RpcResult(); - rpcResult.setResult("Hello, World!"); - - Response response = new Response.Builder(request.getId()).result(rpcResult).build(); - ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); - - ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.cachedRequest.putIfAbsent(request.getId(), rd); - codec.encode(channel, bos, response); - - byte[] buf = new byte[bos.writerIndex() - 4]; - System.arraycopy(bos.array(), 4, buf, 0, bos.writerIndex() - 4); - - ByteArrayInputStream bis = new ByteArrayInputStream(buf); - - if (bis.markSupported()) { - bis.mark(0); - } - - TIOStreamTransport transport = new TIOStreamTransport(bis); - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - Assert.assertEquals(protocol.readI32() + 4, bos.writerIndex()); - int headerLength = protocol.readI16(); - - Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - Assert.assertEquals(request.getId(), protocol.readI64()); - - if (bis.markSupported()) { - bis.reset(); - bis.skip(headerLength); - } - - TMessage message = protocol.readMessageBegin(); - Assert.assertEquals("echoString", message.name); - Assert.assertEquals(TMessageType.REPLY, message.type); - Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid); - Demo.echoString_result result = new Demo.echoString_result(); - result.read(protocol); - protocol.readMessageEnd(); - - Assert.assertEquals(rpcResult.getValue(), result.getSuccess()); - } - - @Test - public void testEncodeExceptionResponse() throws Exception { - - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - Request request = createRequest(); - - RpcResult rpcResult = new RpcResult(); - String exceptionMessage = "failed"; - rpcResult.setException(new RuntimeException(exceptionMessage)); - - Response response = new Response.Builder(request.getId()).result(rpcResult).build(); - ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); - - ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.cachedRequest.put(request.getId(), rd); - codec.encode(channel, bos, response); - - byte[] buf = new byte[bos.writerIndex() - 4]; - System.arraycopy(bos.array(), 4, buf, 0, bos.writerIndex() - 4); - ByteArrayInputStream bis = new ByteArrayInputStream(buf); - - if (bis.markSupported()) { - bis.mark(0); - } - - TIOStreamTransport transport = new TIOStreamTransport(bis); - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - Assert.assertEquals(protocol.readI32() + 4, bos.writerIndex()); - int headerLength = protocol.readI16(); - - Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - Assert.assertEquals(request.getId(), protocol.readI64()); - - if (bis.markSupported()) { - bis.reset(); - bis.skip(headerLength); - } - - TMessage message = protocol.readMessageBegin(); - Assert.assertEquals("echoString", message.name); - Assert.assertEquals(TMessageType.EXCEPTION, message.type); - Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid); - TApplicationException exception = TApplicationException.read(protocol); - protocol.readMessageEnd(); - - Assert.assertEquals(exceptionMessage, exception.getMessage()); - - } - - @Test - public void testDecodeRequest() throws Exception { - Request request = createRequest(); - // encode - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); - - TIOStreamTransport transport = new TIOStreamTransport(bos); - - TBinaryProtocol protocol = new TBinaryProtocol(transport); - - int messageLength, headerLength; - - protocol.writeI16(ThriftCodec.MAGIC); - protocol.writeI32(Integer.MAX_VALUE); - protocol.writeI16(Short.MAX_VALUE); - protocol.writeByte(ThriftCodec.VERSION); - protocol.writeString( - ((RpcInvocation) request.getData()) - .getAttachment(Constants.INTERFACE_KEY)); - protocol.writeI64(request.getId()); - protocol.getTransport().flush(); - headerLength = bos.size(); - - Demo.echoString_args args = new Demo.echoString_args(); - args.setArg("Hell, World!"); - - TMessage message = new TMessage("echoString", TMessageType.CALL, ThriftCodec.getSeqId()); - - protocol.writeMessageBegin(message); - args.write(protocol); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX); - protocol.writeI16((short) (0xffff & headerLength)); - bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX); - protocol.writeI32(messageLength); - } finally { - bos.setWriteIndex(oldIndex); - } - - Object obj = codec.decode((Channel) null, ChannelBuffers.wrappedBuffer( - encodeFrame(bos.toByteArray()))); - - Assert.assertTrue(obj instanceof Request); - - obj = ((Request) obj).getData(); - - Assert.assertTrue(obj instanceof RpcInvocation); - - RpcInvocation invocation = (RpcInvocation) obj; - - Assert.assertEquals("echoString", invocation.getMethodName()); - Assert.assertArrayEquals(new Class[]{String.class}, invocation.getParameterTypes()); - Assert.assertArrayEquals(new Object[]{args.getArg()}, invocation.getArguments()); - - } - - private Request createRequest() { - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName("echoString"); - - invocation.setArguments(new Object[]{"Hello, World!"}); - - invocation.setParameterTypes(new Class[]{String.class}); - - invocation.setAttachment(Constants.INTERFACE_KEY, Demo.Iface.class.getName()); - - Request.Builder builder = new Request.Builder(1L); - builder.data(invocation); - return builder.build(); - - } - - static byte[] encodeFrame(byte[] content) { - byte[] result = new byte[4 + content.length]; - TFramedTransport.encodeFrameSize(content.length, result); - System.arraycopy(content, 0, result, 4, content.length); - return result; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java deleted file mode 100644 index 38bcd4c62d9..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * File Created at 2011-12-31 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.rpc.gen.thrift.Demo; -import org.apache.thrift.TException; - -/** - * @author kimi - */ -public class ThriftDemoImpl extends DemoImpl implements Demo.Iface {} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java deleted file mode 100644 index a233cc18013..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * File Created at 2011-12-08 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @author kimi - */ -public class ThriftProtocolTest extends AbstractTest { - - public static final int DEFAULT_PORT = 30660; - - private ThriftProtocol protocol; - - private Invoker invoker; - - private URL url; - - @Before - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName() ); - - } - - @After - public void tearDown() throws Exception { - - destroy(); - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - @Test - public void testRefer() throws Exception { - // FIXME - /*invoker = protocol.refer( Demo.class, url ); - - Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - Result result = invoker.invoke( invocation ); - - Assert.assertEquals( arg, result.getResult() );*/ - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java deleted file mode 100644 index 9cd1f5826da..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation Limited. - * All rights reserved. - * - * This software is the confidential and proprietary information of - * Alibaba Company. ("Confidential Information"). You shall not - * disclose such Confidential Information and shall use it only in - * accordance with the terms of the license agreement you entered into - * with Alibaba.com. - */ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author gang.lvg - */ -public class ThriftUtilsTest { - - @Test - public void testGenerateMethodArgsClassName() { - - Assert.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString" ) ); - - Assert.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension( DubboClassNameGenerator.NAME ).generateArgsClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString" ) ); - - } - - @Test - public void testGenerateMethodResultClassName() { - - Assert.assertEquals( $__DemoStub.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString" )); - - Assert.assertEquals( $__DemoStub.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( DubboClassNameGenerator.NAME ).generateResultClassName ( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString" )); - - } - - @Test - public void testGenerateMethodArgsClassNameThrift() { - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( ThriftClassNameGenerator.NAME ).generateArgsClassName( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - } - - @Test - public void testGenerateMethodResultClassNameThrift() { - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassNameThrift( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( ThriftClassNameGenerator.NAME ).generateResultClassName( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java deleted file mode 100644 index 369f61a5c8d..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.examples; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.rpc.gen.thrift.Demo; - -/** - * @author kimi - */ -public class DubboDemoConsumer { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("dubbo-demo-consumer.xml"); - context.start(); - Demo.Iface demo = (Demo.Iface) context.getBean("demoService"); - System.out.println(demo.echoI32(32)); - for (int i = 0; i < 10; i++) { - System.out.println(demo.echoI32(i + 1)); - } - context.close(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java deleted file mode 100644 index d65d21e69a7..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.examples; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author kimi - */ -public class DubboDemoProvider { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("dubbo-demo-provider.xml"); - context.start(); - System.out.println("context started"); - System.in.read(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml b/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml deleted file mode 100644 index 4f1ccc42380..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml b/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml deleted file mode 100644 index 8727b7bea1e..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift deleted file mode 100644 index 3e2023a9e17..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift +++ /dev/null @@ -1,3 +0,0 @@ -service ClassNameTestDubbo { - string echo(1:required string arg); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift deleted file mode 100644 index ccac7a1e0a4..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift +++ /dev/null @@ -1,3 +0,0 @@ -service ClassNameTestThrift { - string echo(1:required string arg); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift deleted file mode 100644 index 91a264a5251..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift +++ /dev/null @@ -1,16 +0,0 @@ -namespace dubbo_java com.alibaba.dubbo.rpc.gen.dubbo -namespace dubbo_cpp com.alibaba.dubbo.rpc.gen.dubbo - -namespace java com.alibaba.dubbo.rpc.gen.thrift -namespace cpp com.alibaba.dubbo.rpc.gen.thrift - -service Demo { - bool echoBool( 1:required bool arg ); - byte echoByte( 1:required byte arg ); - i16 echoI16 ( 1:required i16 arg ); - i32 echoI32 ( 1:required i32 arg ); - i64 echoI64 ( 1:required i64 arg ); - - double echoDouble( 1:required double arg ); - string echoString( 1:required string arg ); -} \ No newline at end of file diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 16de37c16a5..ef6cac2aa2a 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -36,7 +36,6 @@ dubbo-rpc-hessian dubbo-rpc-http dubbo-rpc-webservice - dubbo-rpc-thrift dubbo-rpc-memcached dubbo-rpc-redis dubbo-rpc-rest diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java index 8cfd1ded5fa..49506d4ced7 100644 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java +++ b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java @@ -108,7 +108,6 @@ private void runJavaAndHessian() { } try { Object response = null; - response = clientFactory.get(targetIP, targetPort, rpcTimeout, clientNums).request(requestObject).get(); long currentTime = System.nanoTime(); if (beginTime <= startTime) { continue; diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java deleted file mode 100644 index 3bb73e0ea88..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 1999-2012 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.examples.async; - -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.async.api.AsyncService; -import com.alibaba.dubbo.rpc.RpcContext; - -/** - * CallbackConsumer - * - * @author william.liangf - */ -public class AsyncConsumer { - - public static void main(String[] args) throws Exception { - String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - - final AsyncService asyncService = (AsyncService)context.getBean("asyncService"); - - Future f = RpcContext.getContext().asyncCall(new Callable() { - public String call() throws Exception { - return asyncService.sayHello("async call request"); - } - }); - - System.out.println("async call ret :" + f.get()); - - RpcContext.getContext().asyncCall(new Runnable() { - public void run() { - asyncService.sayHello("oneway call request1"); - asyncService.sayHello("oneway call request2"); - } - }); - - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java index 7bf96b99485..faa1db98d86 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java @@ -16,11 +16,11 @@ package com.alibaba.dubbo.examples.heartbeat; +import com.alibaba.dubbo.remoting.message.Request; +import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.remoting.transport.Channel; import com.alibaba.dubbo.remoting.exception.RemotingException; import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; import java.util.concurrent.atomic.AtomicInteger; diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 10d671fb266..bb596626a1a 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -321,12 +321,6 @@ - - - - - - @@ -420,7 +414,6 @@ com.alibaba:dubbo-container-logback com.alibaba:dubbo-tracker-api - @@ -583,7 +576,6 @@ META-INF/dubbo/internal/com.alibaba.dubbo.tracker.RpcTrackerEngineFactory - diff --git a/pom.xml b/pom.xml index f5a3619a593..1369b0b4164 100644 --- a/pom.xml +++ b/pom.xml @@ -174,7 +174,7 @@ 1.6 UTF-8 - 2.1.1 + 2.4 2.3.2 2.1.1 2.3.1 @@ -585,6 +585,7 @@ + 2.4 org.apache.maven.plugins From 0f88395ac191f865d1acaa049cffa14c071651a1 Mon Sep 17 00:00:00 2001 From: YanXs Date: Fri, 14 Apr 2017 16:27:35 +0800 Subject: [PATCH 34/69] =?UTF-8?q?=E5=A2=9E=E5=8A=A0AsyncContext,=20Asyncab?= =?UTF-8?q?leInvocationHandler=E6=94=AF=E6=8C=81=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E5=BC=82=E6=AD=A5=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/config/MethodConfig.java | 95 ------------------- .../src/main/resources/META-INF/dubbo.xsd | 17 ---- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../com/alibaba/dubbo/rpc/AsyncContext.java | 65 +++++++++++++ .../com/alibaba/dubbo/rpc/StaticContext.java | 76 --------------- .../rpc/proxy/AsyncableInvocationHandler.java | 30 ++++++ .../rpc/proxy/InvokerInvocationHandler.java | 32 +------ .../javassist/JavassistProxyFactory.java | 3 +- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 55 +++++------ 9 files changed, 128 insertions(+), 247 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java index b2d366e0eb3..54fc8ee8391 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/MethodConfig.java @@ -15,7 +15,6 @@ */ package com.alibaba.dubbo.config; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.config.support.Parameter; import java.util.List; @@ -39,9 +38,6 @@ public class MethodConfig extends AbstractMethodConfig { // 是否重试 private Boolean retry; - // 是否开启track,默认开启 - private Boolean enableTrack = Boolean.TRUE; - // 是否为可靠异步 private Boolean reliable; @@ -54,27 +50,6 @@ public class MethodConfig extends AbstractMethodConfig { // 是否需要开启stiky策略 private Boolean sticky; - // 是否需要返回 - private Boolean isReturn; - - //异步调用回调实例 - private Object oninvoke; - - //异步调用回调方法 - private String oninvokeMethod; - - //异步调用回调实例 - private Object onreturn; - - //异步调用回调方法 - private String onreturnMethod; - - //异步调用异常回调实例 - private Object onthrow; - - //异步调用异常回调方法 - private String onthrowMethod; - private List arguments; @Parameter(excluded = true) @@ -152,74 +127,4 @@ public void setSticky(Boolean sticky) { this.sticky = sticky; } - public Boolean getEnableTrack() { - return enableTrack; - } - - public void setEnableTrack(Boolean enableTrack) { - this.enableTrack = enableTrack; - } - - @Parameter(key = Constants.ON_RETURN_INSTANCE_KEY, excluded = true, attribute = true) - public Object getOnreturn() { - return onreturn; - } - - public void setOnreturn(Object onreturn) { - this.onreturn = onreturn; - } - - @Parameter(key = Constants.ON_RETURN_METHOD_KEY, excluded = true, attribute = true) - public String getOnreturnMethod() { - return onreturnMethod; - } - - public void setOnreturnMethod(String onreturnMethod) { - this.onreturnMethod = onreturnMethod; - } - - @Parameter(key = Constants.ON_THROW_INSTANCE_KEY, excluded = true, attribute = true) - public Object getOnthrow() { - return onthrow; - } - - public void setOnthrow(Object onthrow) { - this.onthrow = onthrow; - } - - @Parameter(key = Constants.ON_THROW_METHOD_KEY, excluded = true, attribute = true) - public String getOnthrowMethod() { - return onthrowMethod; - } - - public void setOnthrowMethod(String onthrowMethod) { - this.onthrowMethod = onthrowMethod; - } - - @Parameter(key = Constants.ON_INVOKE_INSTANCE_KEY, excluded = true, attribute = true) - public Object getOninvoke() { - return oninvoke; - } - - public void setOninvoke(Object oninvoke) { - this.oninvoke = oninvoke; - } - - @Parameter(key = Constants.ON_INVOKE_METHOD_KEY, excluded = true, attribute = true) - public String getOninvokeMethod() { - return oninvokeMethod; - } - - public void setOninvokeMethod(String oninvokeMethod) { - this.oninvokeMethod = oninvokeMethod; - } - - public Boolean isReturn() { - return isReturn; - } - - public void setReturn(Boolean isReturn) { - this.isReturn = isReturn; - } - } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 847b1e67ef4..001105e4d36 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -705,23 +705,6 @@ - - - - - - - - - - - - - - - - - diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index a00fa6ee8c9..09959c11d9c 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java new file mode 100644 index 00000000000..c9023f35110 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -0,0 +1,65 @@ +package com.alibaba.dubbo.rpc; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; + +import java.lang.reflect.Method; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * @author Xs + */ +public class AsyncContext { + + private static final ListeningExecutorService asyncExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32)); + + private final AsyncMethodWrapper asyncMethodWrapper; + + public AsyncContext(AsyncMethodWrapper asyncMethodWrapper) { + this.asyncMethodWrapper = asyncMethodWrapper; + } + + public Future start() { + return asyncExecutor.submit(new Callable() { + @Override + public Object call() throws Exception { + return asyncMethodWrapper.invokeSyncMethod(); + } + }); + } + + /** + * async method wrapper + */ + public static class AsyncMethodWrapper { + + private final Object proxy; + + private final Method wrapped; + + private final Object[] args; + + public AsyncMethodWrapper(Object proxy, Method wrapped, Object[] args) { + this.proxy = proxy; + this.wrapped = wrapped; + this.args = args; + } + + private Method getCorrespondingSyncMethod() throws Exception { + String methodName = wrapped.getName(); + Class[] parameterTypes = wrapped.getParameterTypes(); + String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); + return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); + } + + public Object invokeSyncMethod() throws Exception { + return getCorrespondingSyncMethod().invoke(proxy, args); + } + + public AsyncContext startAsync() { + return new AsyncContext(this); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java deleted file mode 100644 index 9a58aee0d3f..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/StaticContext.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.rpc; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * 系统存储,内部类. - */ -@Deprecated -public class StaticContext extends ConcurrentHashMap { - private static final long serialVersionUID = 1L; - private static final String SYSTEMNAME = "system"; - private String name; - - private static final ConcurrentMap context_map = new ConcurrentHashMap(); - - private StaticContext(String name) { - super(); - this.name = name; - } - - public String getName() { - return name; - } - - public static StaticContext getSystemContext() { - return getContext(SYSTEMNAME); - } - - public static StaticContext getContext(String name) { - StaticContext appContext = context_map.get(name); - if (appContext == null) { - appContext = context_map.putIfAbsent(name, new StaticContext(name)); - if (appContext == null) { - appContext = context_map.get(name); - } - } - return appContext; - } - - public static StaticContext remove(String name) { - return context_map.remove(name); - } - - public static String getKey(URL url, String methodName, String suffix) { - return getKey(url.getServiceKey(), methodName, suffix); - } - - public static String getKey(Map paras, String methodName, String suffix) { - return getKey(StringUtils.getServiceKey(paras), methodName, suffix); - } - - private static String getKey(String servicekey, String methodName, String suffix) { - StringBuffer sb = new StringBuffer().append(servicekey).append(".").append(methodName).append(".").append(suffix); - return sb.toString(); - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java new file mode 100644 index 00000000000..4f9d9cf8b1e --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.rpc.proxy; + +import com.alibaba.dubbo.rpc.AsyncContext; +import com.alibaba.dubbo.rpc.Invoker; + +import java.lang.reflect.Method; +import java.util.concurrent.Future; + +public class AsyncableInvocationHandler extends InvokerInvocationHandler { + + + public AsyncableInvocationHandler(Invoker handler) { + super(handler); + + } + + public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + if (!isAsyncMethod(method)) { + return super.invoke(proxy, method, args); + } else { + AsyncContext.AsyncMethodWrapper methodWrapper = new AsyncContext.AsyncMethodWrapper(proxy, method, args); + AsyncContext asyncContext = methodWrapper.startAsync(); + return asyncContext.start(); + } + } + + private boolean isAsyncMethod(Method method) { + return Future.class.isAssignableFrom(method.getReturnType()); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java index c12eb5b62b7..e6a19e577e4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -17,14 +17,9 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcInvocation; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; /** * InvokerHandler @@ -33,10 +28,7 @@ */ public class InvokerInvocationHandler implements InvocationHandler { - private static final ListeningExecutorService asyncExecutor = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32)); - - private final Invoker invoker; + protected final Invoker invoker; public InvokerInvocationHandler(Invoker handler) { this.invoker = handler; @@ -57,26 +49,6 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if ("equals".equals(methodName) && parameterTypes.length == 1) { return invoker.equals(args[0]); } - if (isAsyncMethod(method)) { - return asyncExecutor.submit(new Callable() { - @Override - public Object call() throws Exception { - return getCorrespondingSyncMethod(proxy.getClass(), method).invoke(proxy, args); - } - }); - } else { - return invoker.invoke(new RpcInvocation(method, args)).recreate(); - } - } - - private boolean isAsyncMethod(Method method) { - return Future.class.isAssignableFrom(method.getReturnType()); - } - - private Method getCorrespondingSyncMethod(Class clazz, Method method) throws Exception { - String methodName = method.getName(); - Class[] parameterTypes = method.getParameterTypes(); - String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - return clazz.getDeclaredMethod(syncMethodName, parameterTypes); + return invoker.invoke(new RpcInvocation(method, args)).recreate(); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java index ac1941dface..4c6d70e7c58 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java @@ -21,6 +21,7 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; +import com.alibaba.dubbo.rpc.proxy.AsyncableInvocationHandler; import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler; /** @@ -32,7 +33,7 @@ public class JavassistProxyFactory extends AbstractProxyFactory { @SuppressWarnings("unchecked") public T getProxy(Invoker invoker, Class[] interfaces) { - return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker)); + return (T) Proxy.getProxy(interfaces).newInstance(new AsyncableInvocationHandler(invoker)); } public Invoker getInvoker(T proxy, Class type, URL url) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index afa805421b9..01d82e83eb0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -1,46 +1,47 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.proxy.jdk; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; -import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; +import com.alibaba.dubbo.rpc.proxy.AsyncableInvocationHandler; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; /** * JavaassistRpcProxyFactory - + * * @author william.liangf */ public class JdkProxyFactory extends AbstractProxyFactory { @SuppressWarnings("unchecked") public T getProxy(Invoker invoker, Class[] interfaces) { - return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker)); + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + interfaces, new AsyncableInvocationHandler(invoker)); } public Invoker getInvoker(T proxy, Class type, URL url) { return new AbstractProxyInvoker(proxy, type, url) { @Override - protected Object doInvoke(T proxy, String methodName, - Class[] parameterTypes, + protected Object doInvoke(T proxy, String methodName, + Class[] parameterTypes, Object[] arguments) throws Throwable { Method method = proxy.getClass().getMethod(methodName, parameterTypes); return method.invoke(proxy, arguments); From 896ad2179d03f5a8330877ce10f7d6cc199565b1 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 16 Apr 2017 22:45:48 +0800 Subject: [PATCH 35/69] add TraceId and TraceIdReporter, update version to 3.0.1 --- README.md | 13 ++- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- .../dubbo-container-javaconfig/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- .../alibaba/dubbo/remoting/RpcMessage.java | 55 +++++------ dubbo-remoting/dubbo-remoting-common/pom.xml | 4 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 4 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-api/pom.xml | 2 +- .../dubbo-test-benchmark-client/pom.xml | 2 +- .../dubbo-test-benchmark-server/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 7 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo-tool/dubbo-demo-lite-archetype/pom.xml | 2 +- .../resources/archetype-resources/pom.xml | 4 +- .../dubbo-demo-lite-api/pom.xml | 2 +- .../dubbo-demo-lite-consumer/pom.xml | 2 +- .../dubbo-demo-lite-provider/pom.xml | 2 +- dubbo-tool/dubbo-demo-lite/pom.xml | 4 +- dubbo-tracker/dubbo-tracker-api/pom.xml | 6 +- .../com/alibaba/dubbo/tracker/RpcTracker.java | 2 - .../dubbo/tracker/RpcTrackerEngine.java | 2 + .../dubbo/tracker/RpcTrackerManager.java | 15 +-- dubbo-tracker/pom.xml | 3 +- dubbo/pom.xml | 14 +-- hessian-lite/pom.xml | 2 +- pom.xml | 94 ++----------------- 76 files changed, 123 insertions(+), 228 deletions(-) diff --git a/README.md b/README.md index 72d989938b9..3e9ebc86478 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,24 @@ # dubbo3 -dubbo3 fork [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) +dubbo3 基于 [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) 修改 具体的使用方法请参考[dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) ## dubbo3修改和增加的功能 +* 修改consumer端的异步实现方式,支持guava的ListenableFuture,使用异步调用api更加简单 + * 实现基于dubbo、hessian、http协议的分布式服务链路监控和追踪功能,可以将服务链路信息报告给[Zipkin](http://zipkin.io/),Zipkin的用户界面可以浏览全链路每一个服务的延迟 -* 修改了ExchangeChannel中基于dubbo协议同步调用的接口,便于添加Interceptor拦截request记录服务调用信息 +* 修改了ExchangeChannel中同步调用的接口,增加Interceptor接口拦截request记录服务调用信息 * 添加了okhttp3支持hessian协议、http协议,目前对这两种协议的拦截基于OkhttpClient的Interceptor机制 -## 如何开启tracker +### consumer异步调用 + + + + +### rpcTracker分布式链路追踪 目前tracker的使用方式只支持spring xml配置,目前有如下两种方式 diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 9fc1d69e102..13a9dd9c991 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index b1f58409646..23c75b0ec09 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index c6b3817a896..8eaeb85dd41 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index eb956be9c58..c7ee4d0ed96 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 3.0.0 + 3.0.1 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 634517385d4..65c039b07d8 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 3.0.0 + 3.0.1 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index e5fb886e287..f1971823a66 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 3f6856f1303..a33f0c356a3 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml index f5419d78178..1b3116919d2 100644 --- a/dubbo-container/dubbo-container-javaconfig/pom.xml +++ b/dubbo-container/dubbo-container-javaconfig/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-javaconfig jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index ac41c174a2c..0fbbbb08fd6 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index b0bb8a6d5f6..97bfcc30d31 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 5b8b849a640..738986bf90b 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index e6e1e1ffb78..122e4d343ac 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 3.0.0 + 3.0.1 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 8f1bc37dff0..1803f60600b 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 71721c1d142..0cd1c04fe68 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 3.0.0 + 3.0.1 dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 62ac9a61980..449d7181cf6 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 3.0.0 + 3.0.1 dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 4c1ac3629de..6451ad4959e 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 3.0.0 + 3.0.1 dubbo-demo-provider war diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 3e99a31b968..55d990034a1 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 088b2f731af..252f6edeef2 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 3.0.0 + 3.0.1 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 60f5c97d877..346242f5a1d 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 3.0.0 + 3.0.1 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 75e20543c08..1061304804e 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index a0820ae0d0c..13babedf362 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 3.0.0 + 3.0.1 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 2456a08ce17..d3c0e303b34 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 3.0.0 + 3.0.1 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 3c8d82cea68..ba6c25924a1 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 26687c56d26..0dedb487217 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 3.0.0 + 3.0.1 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 4634d207baf..074e2d74690 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 3.0.0 + 3.0.1 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index d1c2a5aa67f..d606f6c2f0a 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 3.0.0 + 3.0.1 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index c370a57c56b..fe11221e05c 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 3.0.0 + 3.0.1 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 3dd9592a604..27e12d3039e 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 3.0.0 + 3.0.1 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index fa31d2ce6d2..56f985cc928 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 1dd2aacd6a0..9556c423297 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessage.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessage.java index 8ab2c36a8f0..0292b05b269 100755 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessage.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/RpcMessage.java @@ -19,47 +19,42 @@ /** * RpcMessage. - * + * * @author qian.lei */ -public class RpcMessage implements Serializable -{ - private static final long serialVersionUID = -5148079121106659095L; +public class RpcMessage implements Serializable { + private static final long serialVersionUID = -5148079121106659095L; - private String mClassName; + private String mClassName; - private String mMethodDesc; + private String mMethodDesc; - private Class[] mParameterTypes; + private Class[] mParameterTypes; - private Object[] mArguments; + private Object[] mArguments; - public RpcMessage(String cn, String desc, Class[] parameterTypes,Object[] args) - { - mClassName = cn; - mMethodDesc = desc; - mParameterTypes = parameterTypes; - mArguments = args; - } + public RpcMessage(String cn, String desc, Class[] parameterTypes, Object[] args) { + mClassName = cn; + mMethodDesc = desc; + mParameterTypes = parameterTypes; + mArguments = args; + } - public String getClassName() - { - return mClassName; - } + public String getClassName() { + return mClassName; + } - public String getMethodDesc() - { - return mMethodDesc; - } + public String getMethodDesc() { + return mMethodDesc; + } - public Class[] getParameterTypes() { - return mParameterTypes; - } + public Class[] getParameterTypes() { + return mParameterTypes; + } - public Object[] getArguments() - { - return mArguments; - } + public Object[] getArguments() { + return mArguments; + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-common/pom.xml b/dubbo-remoting/dubbo-remoting-common/pom.xml index dacfa22efaa..52cd1e8a1d6 100644 --- a/dubbo-remoting/dubbo-remoting-common/pom.xml +++ b/dubbo-remoting/dubbo-remoting-common/pom.xml @@ -5,7 +5,7 @@ dubbo-remoting com.alibaba - 3.0.0 + 3.0.1 4.0.0 @@ -15,7 +15,7 @@ com.alibaba dubbo-common - 3.0.0 + 3.0.1 diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index 2f6e0c94e9e..9d8c2a13e15 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index f505c61bbb2..bc9e7ea609f 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 37821fc9bf4..cc6a98a9a7e 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 2837f08a43b..2330a989483 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 57774870ef7..1a261f46035 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 7b1582604e1..e9ed070ce81 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 3.0.0 + 3.0.1 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 439317330c5..6b79897f7ed 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index dfb857ffdd2..2e37611f934 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-api jar @@ -37,7 +37,7 @@ com.google.guava guava - 16.0.1 + 19.0 \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 5d65b682e93..da766dc76fd 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 42c4494c456..13e77c3e30f 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 893bd8afa96..dad5b540eff 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index e16cb426fa3..74a42ce5996 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 86af859d0bf..0c3158df347 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 558c11c335e..b72b6c864cf 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 1ec6d963c7f..1611c3672dc 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-rest jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 8610b1a3883..ae890999834 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index a7874cc90d3..6cb9006194c 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 3.0.0 + 3.0.1 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index ef6cac2aa2a..f9c675778bf 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index f2cece907e3..35da15b7128 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 3.0.0 + 3.0.1 dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 17440add37b..14de4651a94 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 3.0.0 + 3.0.1 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index ea699e98c92..2cbf2c1a08f 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml index f91bc0579a3..6b903220082 100644 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-benchmark-api jar diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml index 335725f7776..4a51d06796c 100644 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-benchmark-client jar diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml index 2d68048777f..cb0fc158f46 100644 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-benchmark-server jar diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index df7d33c9c03..e9258b8352d 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index b95015b61fb..b3d9acf48a3 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 8adc3826a24..483cd6c475f 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-examples jar @@ -94,11 +94,6 @@ dubbo-rpc-webservice ${project.parent.version} - - com.alibaba - dubbo-rpc-thrift - ${project.parent.version} - com.alibaba dubbo-rpc-memcached diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 873dd43c0dd..e29bd3c7f2d 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 3.0.0 + 3.0.1 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 01160655faf..35d58860c06 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-test pom diff --git a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml index dd7a4bcb83c..1f619d3c4e6 100644 --- a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml +++ b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-demo-lite-archetype - 3.0.0 + 3.0.1 maven-archetype dubbo-demo-lite-archetype diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml index 76274150c22..964f34e4775 100644 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml +++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 ${artifactId} ${groupId} @@ -35,7 +35,7 @@ com.alibaba dubbo - 3.0.0 + 3.0.1 diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml index f9b13b5f81c..2d550a67c30 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 3.0.0 + 3.0.1 dubbo-demo-lite-api jar diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml index 9e5c551d6c6..3a7cf51b014 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 3.0.0 + 3.0.1 dubbo-demo-lite-consumer jar diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml index 8871c05369a..ff6731a3965 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo-lite - 3.0.0 + 3.0.1 dubbo-demo-lite-provider war diff --git a/dubbo-tool/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml index 4704caa8851..85fd8030f4e 100644 --- a/dubbo-tool/dubbo-demo-lite/pom.xml +++ b/dubbo-tool/dubbo-demo-lite/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo-demo-lite pom @@ -39,7 +39,7 @@ com.alibaba dubbo - 3.0.0 + 3.0.1 diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index 2e1237dbb1e..d3a4d0957f5 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -5,7 +5,7 @@ dubbo-tracker com.alibaba - 3.0.0 + 3.0.1 4.0.0 @@ -22,13 +22,13 @@ com.alibaba dubbo-remoting-common - 3.0.0 + 3.0.1 com.alibaba dubbo-rpc-api - 3.0.0 + 3.0.1 diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java index 898d694b464..8db4c414e9e 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTracker.java @@ -14,6 +14,4 @@ public interface RpcTracker { void trackServerResponse(ServerResponseAdapter serverResponseAdapter); RpcTrackerEngine trackerEngine(); - -// boolean isStrict(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java index c181d4b18ed..8bd2889f9eb 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerEngine.java @@ -14,4 +14,6 @@ public interface RpcTrackerEngine { Object serverRequestInterceptor(); Object serverResponseInterceptor(); + + TraceIdReporter traceIdReporter(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java index dcb7913a7de..80535d5a713 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcTrackerManager.java @@ -39,11 +39,11 @@ public static synchronized void setRpcTrackerEngine(RpcTrackerEngine engine) { rpcTrackerEngine = engine; } - public static synchronized RpcTracker createRpcTracker(URL url) { - String protocol = url.getProtocol(); + public static synchronized RpcTracker getRpcTracker(URL url) { if (rpcTrackerEngine == null || rpcTrackerFactory == null) { return null; } + String protocol = url.getProtocol(); RpcTracker rpcTracker = rpcTrackerMap.get(RpcProtocol.valueOf(protocol)); if (rpcTracker == null) { rpcTracker = rpcTrackerFactory.createRpcTracker(url); @@ -55,18 +55,9 @@ public static synchronized RpcTracker createRpcTracker(URL url) { return rpcTracker; } - public static synchronized RpcTracker getRpcTracker(URL url) { - String protocol = url.getProtocol(); - RpcTracker rpcTracker = rpcTrackerMap.get(RpcProtocol.valueOf(protocol)); - if (rpcTracker == null) { - rpcTracker = createRpcTracker(url); - } - return rpcTracker; - } - public static RpcTracker mockRpcTracker(String address, String application) { String urlStr = "zipkin://" + address + "?application=" + application + "&collector=http"; URL url = URL.valueOf(urlStr); - return createRpcTracker(url); + return getRpcTracker(url); } } diff --git a/dubbo-tracker/pom.xml b/dubbo-tracker/pom.xml index 256aa503e0d..2742ec069bf 100644 --- a/dubbo-tracker/pom.xml +++ b/dubbo-tracker/pom.xml @@ -5,7 +5,7 @@ dubbo-parent com.alibaba - 3.0.0 + 3.0.1 4.0.0 @@ -13,7 +13,6 @@ pom dubbo-tracker-api - \ No newline at end of file diff --git a/dubbo/pom.xml b/dubbo/pom.xml index bb596626a1a..a8202304a01 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 dubbo jar @@ -158,17 +158,6 @@ - - com.alibaba - dubbo-rpc-thrift - ${project.parent.version} - - - org.apache.thrift - libthrift - - - com.alibaba dubbo-rpc-memcached @@ -390,7 +379,6 @@ com.alibaba:dubbo-rpc-hessian com.alibaba:dubbo-rpc-http com.alibaba:dubbo-rpc-webservice - com.alibaba:dubbo-rpc-thrift com.alibaba:dubbo-rpc-memcached com.alibaba:dubbo-rpc-redis com.alibaba:dubbo-rpc-rest diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index 468b76df2d8..d5f153a3898 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 3.0.0 + 3.0.1 hessian-lite jar diff --git a/pom.xml b/pom.xml index 1369b0b4164..d296e6295e0 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 2.0 --> com.alibaba dubbo-parent - 3.0.0 + 3.0.1 pom ${project.artifactId} The parent project of dubbo @@ -41,25 +41,6 @@ http://www.alibaba.com - - - - - - - - - - - - - - - - - - - dubbo-common dubbo-container @@ -256,6 +237,12 @@ org.apache.curator curator-framework ${curator_version} + + + com.google.guava + guava + + redis.clients @@ -471,73 +458,6 @@ okhttp 3.2.0 - - - io.zipkin.brave - brave-core - 3.9.0 - - - - io.zipkin.brave - brave-http - 3.9.0 - - - - io.zipkin.brave - brave-web-servlet-filter - 3.9.0 - - - - io.zipkin.brave - brave-okhttp - 3.9.0 - - - - com.squareup.retrofit2 - retrofit - 2.1.0 - - - - io.zipkin.brave - brave-spancollector-http - 3.9.0 - - - - io.zipkin.brave - brave-spancollector-kafka - 3.9.0 - - - - io.zipkin.brave - brave-spancollector-scribe - 3.9.0 - - - - io.zipkin.brave - brave-jaxrs2 - 3.9.0 - - - - io.zipkin.brave - brave-jersey2 - 3.9.0 - - - - com.google.auto.value - auto-value - 1.3 - - From 35d68cde2a356d0aa0f71b786c11306d3f7148f6 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 17 Apr 2017 00:01:06 +0800 Subject: [PATCH 36/69] README.md --- README.md | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e9ebc86478..33f26af0828 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,45 @@ dubbo3 基于 [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) 修改 ### consumer异步调用 +#### Example 1: 基于guava ListenableFuture示例 +```java +ListenableFuture future = simpleService.async_getComplex("abc"); +Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(Complex result) { + + } + + @Override + public void onFailure(Throwable t) { + + } +}); +``` +dubbo3中异步实现思路是为同步接口生成对应的异步接口,consumer和provider使用生成的接口 +origin interface: +```java +public interface SimpleService { + Complex getComplex(String id); +} +``` +async interface: +```java +public interface Unified_SimpleService extends SimpleService { + ListenableFuture async_getComplex(String id); +} +``` +consumer配置 +```xml + +``` +provider配置 +```xml + +``` - +#### auto-async自动生成异步接口 +自动生成async interface需要使用[auto-async] (https://github.com/YanXs/auto-async)库 ### rpcTracker分布式链路追踪 From ec7babb9ffc8bba29586e8ac212896fa195c2b5a Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 17 Apr 2017 00:03:14 +0800 Subject: [PATCH 37/69] README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 33f26af0828..ca49bae7e11 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,8 @@ provider配置 ``` #### auto-async自动生成异步接口 -自动生成async interface需要使用[auto-async] (https://github.com/YanXs/auto-async)库 +自动生成async interface需要使用[auto-async] (https://github.com/YanXs/auto-async) + ### rpcTracker分布式链路追踪 From cdf15940a2f310d0157cfd54d191edefccf708b4 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 17 Apr 2017 22:45:27 +0800 Subject: [PATCH 38/69] TraceId TraceIdReporter --- .../com/alibaba/dubbo/tracker/TraceId.java | 26 +++++++++++++++++++ .../dubbo/tracker/TraceIdReporter.java | 10 +++++++ 2 files changed, 36 insertions(+) create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java create mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceIdReporter.java diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java new file mode 100644 index 00000000000..b03596b629d --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java @@ -0,0 +1,26 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public class TraceId { + + public static final TraceId NOT_TRACE = new TraceId(false, ""); + + private final boolean sampled; + + private final String traceId; + + public TraceId(boolean sampled, String traceId) { + this.sampled = sampled; + this.traceId = traceId; + } + + public boolean isSampled() { + return sampled; + } + + public String getTraceId() { + return traceId; + } +} diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceIdReporter.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceIdReporter.java new file mode 100644 index 00000000000..5a13f382196 --- /dev/null +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceIdReporter.java @@ -0,0 +1,10 @@ +package com.alibaba.dubbo.tracker; + +/** + * @author Xs + */ +public interface TraceIdReporter { + + void report(TraceId traceId); + +} From ecc2704dbd97c9da819c5ed37093db1da4f259a9 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 17 Apr 2017 23:06:41 +0800 Subject: [PATCH 39/69] change the thread in AsyncContext to daemon --- .../src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index c9023f35110..61ec9346758 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.rpc; +import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; @@ -13,7 +14,8 @@ */ public class AsyncContext { - private static final ListeningExecutorService asyncExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32)); + private static final ListeningExecutorService asyncExecutor = + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16, new NamedThreadFactory("asyncContext", Boolean.TRUE))); private final AsyncMethodWrapper asyncMethodWrapper; From 681d73b92cf792ee4b9ed5428acd430f0e656a86 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 18 Apr 2017 17:13:21 +0800 Subject: [PATCH 40/69] add equals and hashCode methods in TraceId --- .../common/utils/NamedThreadFactory.java | 57 +++++++++---------- .../alibaba/dubbo/config/AbstractConfig.java | 1 + .../alibaba/dubbo/config/ProtocolConfig.java | 9 +-- .../rpc/proxy/AsyncableInvocationHandler.java | 5 +- .../tracker/ClientResponseInterceptor.java | 2 + .../com/alibaba/dubbo/tracker/TraceId.java | 17 +++++- 6 files changed, 48 insertions(+), 43 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NamedThreadFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NamedThreadFactory.java index b9da491d56f..ad9ee5439ac 100755 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NamedThreadFactory.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NamedThreadFactory.java @@ -20,50 +20,45 @@ /** * InternalThreadFactory. - * + * * @author qian.lei */ -public class NamedThreadFactory implements ThreadFactory -{ - private static final AtomicInteger POOL_SEQ = new AtomicInteger(1); +public class NamedThreadFactory implements ThreadFactory { - private final AtomicInteger mThreadNum = new AtomicInteger(1); + private static final AtomicInteger POOL_SEQ = new AtomicInteger(1); - private final String mPrefix; + private final AtomicInteger mThreadNum = new AtomicInteger(1); - private final boolean mDaemo; + private final String mPrefix; - private final ThreadGroup mGroup; + private final boolean mDaemo; - public NamedThreadFactory() - { - this("pool-" + POOL_SEQ.getAndIncrement(),false); - } + private final ThreadGroup mGroup; - public NamedThreadFactory(String prefix) - { - this(prefix,false); - } + public NamedThreadFactory() { + this("pool-" + POOL_SEQ.getAndIncrement(), false); + } - public NamedThreadFactory(String prefix,boolean daemo) - { - mPrefix = prefix + "-thread-"; - mDaemo = daemo; + public NamedThreadFactory(String prefix) { + this(prefix, false); + } + + public NamedThreadFactory(String prefix, boolean daemon) { + mPrefix = prefix + "-thread-"; + mDaemo = daemon; SecurityManager s = System.getSecurityManager(); - mGroup = ( s == null ) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); - } + mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); + } - public Thread newThread(Runnable runnable) - { - String name = mPrefix + mThreadNum.getAndIncrement(); - Thread ret = new Thread(mGroup,runnable,name,0); + public Thread newThread(Runnable runnable) { + String name = mPrefix + mThreadNum.getAndIncrement(); + Thread ret = new Thread(mGroup, runnable, name, 0); ret.setDaemon(mDaemo); return ret; - } + } - public ThreadGroup getThreadGroup() - { - return mGroup; - } + public ThreadGroup getThreadGroup() { + return mGroup; + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 281b0d29cd6..0fa0fb301b5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -25,6 +25,7 @@ import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.support.Parameter; +import com.alibaba.dubbo.rpc.AsyncContext; import java.io.Serializable; import java.lang.reflect.Method; diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index 89383559b89..8266a2bc462 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -23,9 +23,9 @@ import com.alibaba.dubbo.registry.support.AbstractRegistryFactory; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Dispatcher; -import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; +import com.alibaba.dubbo.remoting.transport.Transporter; import com.alibaba.dubbo.rpc.Protocol; import java.util.Map; @@ -455,13 +455,6 @@ public void setExtension(String extension) { this.extension = extension; } - public void destory() { - if (name != null) { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).destroy(); - ; - } - } - public static void destroyAll() { AbstractRegistryFactory.destroyAll(); ExtensionLoader loader = ExtensionLoader.getExtensionLoader(Protocol.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 4f9d9cf8b1e..09fce3751ac 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -8,10 +8,8 @@ public class AsyncableInvocationHandler extends InvokerInvocationHandler { - public AsyncableInvocationHandler(Invoker handler) { super(handler); - } public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { @@ -25,6 +23,7 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg } private boolean isAsyncMethod(Method method) { - return Future.class.isAssignableFrom(method.getReturnType()); + return Future.class.isAssignableFrom(method.getReturnType()) && + method.getName().startsWith("async_"); } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java index a2d0c72ae2f..7e1f72557b7 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/ClientResponseInterceptor.java @@ -4,5 +4,7 @@ * @author Xs */ public interface ClientResponseInterceptor { + void handle(ClientResponseAdapter clientResponseAdapter); + } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java index b03596b629d..a02f3252035 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/TraceId.java @@ -20,7 +20,22 @@ public boolean isSampled() { return sampled; } - public String getTraceId() { + public String get() { return traceId; } + + @Override + public boolean equals(Object object) { + if (this == object) return true; + if (object == null || getClass() != object.getClass()) { + return false; + } + TraceId that = (TraceId) object; + return traceId.equals(that.traceId); + } + + @Override + public int hashCode() { + return traceId.hashCode(); + } } From af709d505fb0c3ba525472fae35ac50b2764f760 Mon Sep 17 00:00:00 2001 From: YanXs Date: Fri, 21 Apr 2017 21:47:28 +0800 Subject: [PATCH 41/69] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=BC=82=E6=AD=A5?= =?UTF-8?q?=E5=A4=84=E7=90=86=E7=B1=BB,=20AsyncTarget,=20AsyncListener?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/cluster/support/BroadcastCluster.java | 3 +- .../support/BroadcastClusterInvoker.java | 163 ++++++++++++++++-- .../alibaba/dubbo/config/AbstractConfig.java | 1 - .../dubbo/cache/filter/CacheFilter.java | 28 ++- .../support/header/HeaderExchanger.java | 4 +- .../com/alibaba/dubbo/rpc/AsyncContext.java | 69 ++++---- .../com/alibaba/dubbo/rpc/AsyncListener.java | 6 + .../com/alibaba/dubbo/rpc/AsyncTarget.java | 8 + .../rpc/proxy/AsyncableInvocationHandler.java | 40 ++++- .../tracker/{dubbo => }/DubboRequest.java | 4 +- .../DubboRequestInterceptorBuilder.java | 2 +- .../DubboRequestSpanNameProvider.java | 5 +- .../tracker/{dubbo => }/DubboResponse.java | 4 +- 13 files changed, 253 insertions(+), 84 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{dubbo => }/DubboRequest.java (95%) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{dubbo => }/DubboRequestInterceptorBuilder.java (90%) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{dubbo => }/DubboRequestSpanNameProvider.java (83%) rename dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/{dubbo => }/DubboResponse.java (88%) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java index 907ec788a23..21e18e3ff13 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java @@ -22,7 +22,7 @@ /** * BroadcastCluster - * + * * @author william.liangf */ public class BroadcastCluster implements Cluster { @@ -30,5 +30,4 @@ public class BroadcastCluster implements Cluster { public Invoker join(Directory directory) throws RpcException { return new BroadcastClusterInvoker(directory); } - } \ No newline at end of file diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java index e5d74121206..d8edb7f9fab 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java @@ -15,38 +15,41 @@ */ package com.alibaba.dubbo.rpc.cluster.support; -import java.util.List; - import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; + /** * BroadcastClusterInvoker - * + * * @author william.liangf + * @author Xs */ public class BroadcastClusterInvoker extends AbstractClusterInvoker { - + private static final Logger logger = LoggerFactory.getLogger(BroadcastClusterInvoker.class); public BroadcastClusterInvoker(Directory directory) { super(directory); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); - RpcContext.getContext().setInvokers((List)invokers); + RpcContext.getContext().setInvokers((List) invokers); + return doInvokeAsync(invocation, invokers); + } + + private Result doInvokeSync(final Invocation invocation, final List> invokers) { RpcException exception = null; Result result = null; - for (Invoker invoker: invokers) { + for (Invoker invoker : invokers) { try { result = invoker.invoke(invocation); } catch (RpcException e) { @@ -63,4 +66,140 @@ public Result doInvoke(final Invocation invocation, List> invokers, L return result; } + private Result doInvokeAsync(final Invocation invocation, final List> invokers) { + CountDownLatch latch = new CountDownLatch(invokers.size()); + AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); + for (final Invoker invoker : invokers) { + AsyncInvocation asyncInvocation = new AsyncInvocation(invoker, invocation, latch); + AsyncContext asyncContext = asyncInvocation.startAsync(); + asyncContext.addListener(asyncInvocation); + asyncContext.start(); + asyncResultProcessor.addAsyncInvocation(asyncInvocation); + } + try { + latch.await(); + } catch (InterruptedException e) { + throw new RpcException(e.getMessage(), e); + } + asyncResultProcessor.processResult(); + if (asyncResultProcessor.getException() != null) { + throw asyncResultProcessor.getException(); + } + return asyncResultProcessor.getResult(); + } + + + private class AsyncInvocation implements AsyncTarget, AsyncListener { + + private final Invoker invoker; + + private final Invocation invocation; + + private final CountDownLatch latch; + + private Result reVal; + + private RpcException exception; + + public AsyncInvocation(Invoker invoker, Invocation invocation, CountDownLatch latch) { + this.invoker = invoker; + this.invocation = invocation; + this.latch = latch; + } + + @Override + public AsyncContext startAsync() { + return new AsyncContext(this); + } + + @Override + public Result invoke() throws Exception { + return doInvoke(invoker, invocation); + } + + @Override + public void onSuccess(Result result) { + try { + reVal = result; + } finally { + latch.countDown(); + } + } + + @Override + public void onFailure(Throwable t) { + try { + if (t instanceof RpcException) { + exception = (RpcException) t; + } else { + exception = new RpcException(t.getMessage(), t); + } + } finally { + latch.countDown(); + } + } + + public RpcException getException() { + return exception; + } + + public Result getResult() { + return reVal; + } + } + + private class AsyncResultProcessor { + + private final List asyncInvocations; + + private RpcException exception; + + private Result result; + + public AsyncResultProcessor(int size) { + asyncInvocations = new ArrayList(size); + } + + public void addAsyncInvocation(AsyncInvocation asyncInvocation) { + asyncInvocations.add(asyncInvocation); + } + + public void processResult() { + for (AsyncInvocation invocation : asyncInvocations) { + if (invocation.getException() != null) { + exception = invocation.getException(); + break; + } + } + if (exception == null) { + result = asyncInvocations.get(0).getResult(); + } + } + + public Result getResult() { + return result; + } + + public RpcException getException() { + return exception; + } + } + + private Result doInvoke(Invoker invoker, Invocation invocation) { + Result result = null; + RpcException exception = null; + try { + result = invoker.invoke(invocation); + } catch (RpcException e) { + exception = e; + logger.warn(e.getMessage(), e); + } catch (Throwable e) { + exception = new RpcException(e.getMessage(), e); + logger.warn(e.getMessage(), e); + } + if (exception != null) { + throw exception; + } + return result; + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 0fa0fb301b5..281b0d29cd6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -25,7 +25,6 @@ import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.support.Parameter; -import com.alibaba.dubbo.rpc.AsyncContext; import java.io.Serializable; import java.lang.reflect.Method; diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/filter/CacheFilter.java index 4d4e4d3b306..59593073ada 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/filter/CacheFilter.java @@ -21,16 +21,11 @@ import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.ConfigUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.*; /** * CacheFilter - * + * * @author william.liangf */ @Activate(group = {Constants.CONSUMER, Constants.PROVIDER}, value = Constants.CACHE_KEY) @@ -47,20 +42,17 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Cache cache = cacheFactory.getCache(invoker.getUrl().addParameter(Constants.METHOD_KEY, invocation.getMethodName())); if (cache != null) { String key = StringUtils.toArgumentString(invocation.getArguments()); - if (cache != null && key != null) { - Object value = cache.get(key); - if (value != null) { - return new RpcResult(value); - } - Result result = invoker.invoke(invocation); - if (! result.hasException()) { - cache.put(key, result.getValue()); - } - return result; + Object value = cache.get(key); + if (value != null) { + return new RpcResult(value); } + Result result = invoker.invoke(invocation); + if (!result.hasException()) { + cache.put(key, result.getValue()); + } + return result; } } return invoker.invoke(invocation); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 50106df1c56..e3de69482d9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -24,8 +24,8 @@ import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.message.Interceptor; import com.alibaba.dubbo.remoting.transport.DecodeHandler; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestInterceptorBuilder; -import com.alibaba.dubbo.tracker.dubbo.DubboRequestSpanNameProvider; +import com.alibaba.dubbo.tracker.DubboRequestInterceptorBuilder; +import com.alibaba.dubbo.tracker.DubboRequestSpanNameProvider; /** * DefaultMessenger diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index 61ec9346758..05276bf53a6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -1,67 +1,60 @@ package com.alibaba.dubbo.rpc; import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; -import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executors; -import java.util.concurrent.Future; /** * @author Xs */ -public class AsyncContext { +public class AsyncContext { private static final ListeningExecutorService asyncExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16, new NamedThreadFactory("asyncContext", Boolean.TRUE))); - private final AsyncMethodWrapper asyncMethodWrapper; + private final AsyncTarget asyncTarget; - public AsyncContext(AsyncMethodWrapper asyncMethodWrapper) { - this.asyncMethodWrapper = asyncMethodWrapper; + private final List listeners = new ArrayList(); + + private volatile boolean started; + + public AsyncContext(AsyncTarget asyncTarget) { + this.asyncTarget = asyncTarget; } - public Future start() { - return asyncExecutor.submit(new Callable() { + public ListenableFuture start() { + ListenableFuture future = asyncExecutor.submit(new Callable() { @Override - public Object call() throws Exception { - return asyncMethodWrapper.invokeSyncMethod(); + public T call() throws Exception { + return asyncTarget.invoke(); } }); - } - - /** - * async method wrapper - */ - public static class AsyncMethodWrapper { - - private final Object proxy; - - private final Method wrapped; - - private final Object[] args; - - public AsyncMethodWrapper(Object proxy, Method wrapped, Object[] args) { - this.proxy = proxy; - this.wrapped = wrapped; - this.args = args; + for (AsyncListener asyncListener : listeners) { + Futures.addCallback(future, asyncListener); } + started = true; + return future; + } - private Method getCorrespondingSyncMethod() throws Exception { - String methodName = wrapped.getName(); - Class[] parameterTypes = wrapped.getParameterTypes(); - String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); - } + public void addListener(ListenableFuture future, AsyncListener asyncListener) { + Futures.addCallback(future, asyncListener); + } - public Object invokeSyncMethod() throws Exception { - return getCorrespondingSyncMethod().invoke(proxy, args); - } + public void addListener(AsyncListener listener) { + check(); + listeners.add(listener); + } - public AsyncContext startAsync() { - return new AsyncContext(this); + private void check() { + if (started) { + throw new IllegalStateException("listener should not be added after context started."); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java new file mode 100644 index 00000000000..87f19daa90d --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java @@ -0,0 +1,6 @@ +package com.alibaba.dubbo.rpc; + +import com.google.common.util.concurrent.FutureCallback; + +public interface AsyncListener extends FutureCallback { +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java new file mode 100644 index 00000000000..13ee66fb352 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java @@ -0,0 +1,8 @@ +package com.alibaba.dubbo.rpc; + +public interface AsyncTarget { + + AsyncContext startAsync(); + + T invoke() throws Exception; +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 09fce3751ac..6009b310def 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -1,6 +1,7 @@ package com.alibaba.dubbo.rpc.proxy; import com.alibaba.dubbo.rpc.AsyncContext; +import com.alibaba.dubbo.rpc.AsyncTarget; import com.alibaba.dubbo.rpc.Invoker; import java.lang.reflect.Method; @@ -16,8 +17,8 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (!isAsyncMethod(method)) { return super.invoke(proxy, method, args); } else { - AsyncContext.AsyncMethodWrapper methodWrapper = new AsyncContext.AsyncMethodWrapper(proxy, method, args); - AsyncContext asyncContext = methodWrapper.startAsync(); + AsyncTarget asyncTarget = new AsyncMethodWrapper(proxy, method, args); + AsyncContext asyncContext = asyncTarget.startAsync(); return asyncContext.start(); } } @@ -26,4 +27,39 @@ private boolean isAsyncMethod(Method method) { return Future.class.isAssignableFrom(method.getReturnType()) && method.getName().startsWith("async_"); } + + /** + * async method wrapper + */ + public static class AsyncMethodWrapper implements AsyncTarget { + + private final Object proxy; + + private final Method wrapped; + + private final Object[] args; + + public AsyncMethodWrapper(Object proxy, Method wrapped, Object[] args) { + this.proxy = proxy; + this.wrapped = wrapped; + this.args = args; + } + + private Method getCorrespondingSyncMethod() throws Exception { + String methodName = wrapped.getName(); + Class[] parameterTypes = wrapped.getParameterTypes(); + String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); + return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); + } + + public AsyncContext startAsync() { + return new AsyncContext(this); + } + + @Override + public Object invoke() throws Exception { + return getCorrespondingSyncMethod().invoke(proxy, args); + } + + } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java similarity index 95% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java index ea84c46b751..ef84c9d9d34 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.dubbo; +package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.common.utils.StringUtils; @@ -21,7 +21,7 @@ public class DubboRequest { public DubboRequest(Request request) { this.request = request; if (request.getData() instanceof RpcInvocation) { - isTraceable = true; + isTraceable = getAttachment(RpcAttachment.Sampled.getName()) != null; invocation = (RpcInvocation) request.getData(); } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestInterceptorBuilder.java similarity index 90% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestInterceptorBuilder.java index 05335d5f1f7..185a5620cf5 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestInterceptorBuilder.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestInterceptorBuilder.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.dubbo; +package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java similarity index 83% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java index 74608a47336..3fee0b28d71 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboRequestSpanNameProvider.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequestSpanNameProvider.java @@ -1,7 +1,4 @@ -package com.alibaba.dubbo.tracker.dubbo; - -import com.alibaba.dubbo.tracker.RpcAttachment; -import com.alibaba.dubbo.tracker.RpcContextMethodNameProvider; +package com.alibaba.dubbo.tracker; /** * @author Xs diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java similarity index 88% rename from dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java rename to dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index 46b5eb5c9cd..ca5bb9f5d90 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/dubbo/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.tracker.dubbo; +package com.alibaba.dubbo.tracker; import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcResult; @@ -17,7 +17,7 @@ public class DubboResponse { public DubboResponse(Response response) { this.response = response; if (response.getResult() instanceof RpcResult) { - isTraceable = true; + isTraceable = result.getAttachment(RpcAttachment.Sampled.getName()) != null; result = (RpcResult) response.getResult(); } } From c88d511f87f24581291b42b5ed18a0a9d119d65f Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 22 Apr 2017 16:43:08 +0800 Subject: [PATCH 42/69] =?UTF-8?q?=E4=BF=AE=E5=A4=8DJettyHttpServer?= =?UTF-8?q?=E4=B8=AD=E5=9B=A0servletFilter=E6=B2=A1=E6=9C=89=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=BC=95=E8=B5=B7=E7=9A=84=E7=A9=BA=E6=8C=87=E9=92=88?= =?UTF-8?q?bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exchange/support/header/HeaderExchangeClient.java | 3 ++- .../dubbo/remoting/http/jetty/JettyHttpServer.java | 10 ++++++---- .../main/java/com/alibaba/dubbo/rpc/AsyncContext.java | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index f0b33da30c0..77017360b2c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -50,7 +50,8 @@ public class HeaderExchangeClient implements ExchangeClient { private static final Logger logger = LoggerFactory.getLogger(HeaderExchangeClient.class); - private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); + private static final ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2, + new NamedThreadFactory("dubbo-remoting-client-heartbeat", true)); // 心跳定时器 private ScheduledFuture heartbeatTimer; diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java index 2cc6c7c38b0..2c3d330e70d 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -74,10 +74,12 @@ public JettyHttpServer(URL url, final HttpHandler handler, ServletFilterBuilder servletHolder.setInitOrder(2); context.setServletHandler(servletHandler); - Filter filter = servletFilterBuilder.build(url); - if (filter != null) { - FilterHolder filterHolder = new FilterHolder(filter); - context.addFilter(filterHolder, "/*", Handler.REQUEST); + if (servletFilterBuilder != null) { + Filter filter = servletFilterBuilder.build(url); + if (filter != null) { + FilterHolder filterHolder = new FilterHolder(filter); + context.addFilter(filterHolder, "/*", Handler.REQUEST); + } } ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index 05276bf53a6..d759eba9567 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -43,7 +43,7 @@ public T call() throws Exception { return future; } - public void addListener(ListenableFuture future, AsyncListener asyncListener) { + public static void addListener(ListenableFuture future, AsyncListener asyncListener) { Futures.addCallback(future, asyncListener); } From a45f6bc4589b7e6852b4680a65e3a4f5733188e4 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 23 Apr 2017 12:49:47 +0800 Subject: [PATCH 43/69] =?UTF-8?q?=E5=A2=9E=E5=8A=A0NotifyCluster,NotifyClu?= =?UTF-8?q?sterInvoker=E9=87=87=E7=94=A8=E5=BC=82=E6=AD=A5=E5=B9=B6?= =?UTF-8?q?=E8=A1=8C=E7=9A=84=E6=96=B9=E5=BC=8F=EF=BC=8C=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?BroadcastCluster=E5=AE=9E=E7=8E=B0=E5=B9=BF=E6=92=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/cluster/support/BroadcastCluster.java | 1 + .../support/BroadcastClusterInvoker.java | 145 +-------------- .../rpc/cluster/support/NotifyCluster.java | 19 ++ .../cluster/support/NotifyClusterInvoker.java | 167 ++++++++++++++++++ .../com.alibaba.dubbo.rpc.cluster.Cluster | 3 +- .../META-INF/spring/dubbo-demo-provider.xml | 4 +- .../com/alibaba/dubbo/rpc/AsyncContext.java | 4 +- 7 files changed, 194 insertions(+), 149 deletions(-) create mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyCluster.java create mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java index 21e18e3ff13..4f1bdb0aa71 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastCluster.java @@ -25,6 +25,7 @@ * * @author william.liangf */ +@Deprecated public class BroadcastCluster implements Cluster { public Invoker join(Directory directory) throws RpcException { diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java index d8edb7f9fab..ea439fe1b3c 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java @@ -21,16 +21,14 @@ import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; -import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CountDownLatch; /** * BroadcastClusterInvoker * * @author william.liangf - * @author Xs */ +@Deprecated public class BroadcastClusterInvoker extends AbstractClusterInvoker { private static final Logger logger = LoggerFactory.getLogger(BroadcastClusterInvoker.class); @@ -43,10 +41,6 @@ public BroadcastClusterInvoker(Directory directory) { public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); RpcContext.getContext().setInvokers((List) invokers); - return doInvokeAsync(invocation, invokers); - } - - private Result doInvokeSync(final Invocation invocation, final List> invokers) { RpcException exception = null; Result result = null; for (Invoker invoker : invokers) { @@ -65,141 +59,4 @@ private Result doInvokeSync(final Invocation invocation, final List> } return result; } - - private Result doInvokeAsync(final Invocation invocation, final List> invokers) { - CountDownLatch latch = new CountDownLatch(invokers.size()); - AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); - for (final Invoker invoker : invokers) { - AsyncInvocation asyncInvocation = new AsyncInvocation(invoker, invocation, latch); - AsyncContext asyncContext = asyncInvocation.startAsync(); - asyncContext.addListener(asyncInvocation); - asyncContext.start(); - asyncResultProcessor.addAsyncInvocation(asyncInvocation); - } - try { - latch.await(); - } catch (InterruptedException e) { - throw new RpcException(e.getMessage(), e); - } - asyncResultProcessor.processResult(); - if (asyncResultProcessor.getException() != null) { - throw asyncResultProcessor.getException(); - } - return asyncResultProcessor.getResult(); - } - - - private class AsyncInvocation implements AsyncTarget, AsyncListener { - - private final Invoker invoker; - - private final Invocation invocation; - - private final CountDownLatch latch; - - private Result reVal; - - private RpcException exception; - - public AsyncInvocation(Invoker invoker, Invocation invocation, CountDownLatch latch) { - this.invoker = invoker; - this.invocation = invocation; - this.latch = latch; - } - - @Override - public AsyncContext startAsync() { - return new AsyncContext(this); - } - - @Override - public Result invoke() throws Exception { - return doInvoke(invoker, invocation); - } - - @Override - public void onSuccess(Result result) { - try { - reVal = result; - } finally { - latch.countDown(); - } - } - - @Override - public void onFailure(Throwable t) { - try { - if (t instanceof RpcException) { - exception = (RpcException) t; - } else { - exception = new RpcException(t.getMessage(), t); - } - } finally { - latch.countDown(); - } - } - - public RpcException getException() { - return exception; - } - - public Result getResult() { - return reVal; - } - } - - private class AsyncResultProcessor { - - private final List asyncInvocations; - - private RpcException exception; - - private Result result; - - public AsyncResultProcessor(int size) { - asyncInvocations = new ArrayList(size); - } - - public void addAsyncInvocation(AsyncInvocation asyncInvocation) { - asyncInvocations.add(asyncInvocation); - } - - public void processResult() { - for (AsyncInvocation invocation : asyncInvocations) { - if (invocation.getException() != null) { - exception = invocation.getException(); - break; - } - } - if (exception == null) { - result = asyncInvocations.get(0).getResult(); - } - } - - public Result getResult() { - return result; - } - - public RpcException getException() { - return exception; - } - } - - private Result doInvoke(Invoker invoker, Invocation invocation) { - Result result = null; - RpcException exception = null; - try { - result = invoker.invoke(invocation); - } catch (RpcException e) { - exception = e; - logger.warn(e.getMessage(), e); - } catch (Throwable e) { - exception = new RpcException(e.getMessage(), e); - logger.warn(e.getMessage(), e); - } - if (exception != null) { - throw exception; - } - return result; - } } \ No newline at end of file diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyCluster.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyCluster.java new file mode 100644 index 00000000000..0230538bc82 --- /dev/null +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyCluster.java @@ -0,0 +1,19 @@ +package com.alibaba.dubbo.rpc.cluster.support; + +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.cluster.Cluster; +import com.alibaba.dubbo.rpc.cluster.Directory; + +/** + * @author Xs + */ +public class NotifyCluster implements Cluster{ + + public final static String NAME = "notify"; + + @Override + public Invoker join(Directory directory) throws RpcException { + return new NotifyClusterInvoker(directory); + } +} diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java new file mode 100644 index 00000000000..4201a5f3f7e --- /dev/null +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -0,0 +1,167 @@ +package com.alibaba.dubbo.rpc.cluster.support; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.*; +import com.alibaba.dubbo.rpc.cluster.Directory; +import com.alibaba.dubbo.rpc.cluster.LoadBalance; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +/** + * @author Xs + */ +public class NotifyClusterInvoker extends AbstractClusterInvoker{ + + private static final Logger logger = LoggerFactory.getLogger(BroadcastClusterInvoker.class); + + public NotifyClusterInvoker(Directory directory) { + super(directory); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + checkInvokers(invokers, invocation); + RpcContext.getContext().setInvokers((List) invokers); + return doInvokeAsync(invocation, invokers); + } + + private Result doInvokeAsync(final Invocation invocation, final List> invokers) { + final CountDownLatch latch = new CountDownLatch(invokers.size()); + AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); + for (final Invoker invoker : invokers) { + AsyncInvocation asyncInvocation = new AsyncInvocation(invoker, invocation, latch); + AsyncContext asyncContext = asyncInvocation.startAsync(); + asyncContext.addListener(asyncInvocation); + asyncContext.start(); + asyncResultProcessor.addAsyncInvocation(asyncInvocation); + } + try { + latch.await(); + } catch (InterruptedException e) { + throw new RpcException(e.getMessage(), e); + } + asyncResultProcessor.processResult(); + if (asyncResultProcessor.getException() != null) { + throw asyncResultProcessor.getException(); + } + return asyncResultProcessor.getResult(); + } + + + private class AsyncInvocation implements AsyncTarget, AsyncListener { + + private final Invoker invoker; + + private final Invocation invocation; + + private final CountDownLatch latch; + + private Result reVal; + + private RpcException exception; + + public AsyncInvocation(Invoker invoker, Invocation invocation, CountDownLatch latch) { + this.invoker = invoker; + this.invocation = invocation; + this.latch = latch; + } + + @Override + public AsyncContext startAsync() { + return new AsyncContext(this); + } + + @Override + public Result invoke() throws Exception { + return doInvoke(invoker, invocation); + } + + @Override + public void onSuccess(Result result) { + try { + reVal = result; + } finally { + latch.countDown(); + } + } + + @Override + public void onFailure(Throwable t) { + try { + if (t instanceof RpcException) { + exception = (RpcException) t; + } else { + exception = new RpcException(t.getMessage(), t); + } + } finally { + latch.countDown(); + } + } + + public RpcException getException() { + return exception; + } + + public Result getResult() { + return reVal; + } + } + + private class AsyncResultProcessor { + + private final List asyncInvocations; + + private RpcException exception; + + private Result result; + + public AsyncResultProcessor(int size) { + asyncInvocations = new ArrayList(size); + } + + public void addAsyncInvocation(AsyncInvocation asyncInvocation) { + asyncInvocations.add(asyncInvocation); + } + + public void processResult() { + for (AsyncInvocation invocation : asyncInvocations) { + if (invocation.getException() != null) { + exception = invocation.getException(); + break; + } + } + if (exception == null) { + result = asyncInvocations.get(0).getResult(); + } + } + + public Result getResult() { + return result; + } + + public RpcException getException() { + return exception; + } + } + + private Result doInvoke(Invoker invoker, Invocation invocation) { + Result result = null; + RpcException exception = null; + try { + result = invoker.invoke(invocation); + } catch (RpcException e) { + exception = e; + logger.warn(e.getMessage(), e); + } catch (Throwable e) { + exception = new RpcException(e.getMessage(), e); + logger.warn(e.getMessage(), e); + } + if (exception != null) { + throw exception; + } + return result; + } +} diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster index 54e85ed763b..729c67c9cf8 100644 --- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster +++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster @@ -6,4 +6,5 @@ failback=com.alibaba.dubbo.rpc.cluster.support.FailbackCluster forking=com.alibaba.dubbo.rpc.cluster.support.ForkingCluster available=com.alibaba.dubbo.rpc.cluster.support.AvailableCluster mergeable=com.alibaba.dubbo.rpc.cluster.support.MergeableCluster -broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster \ No newline at end of file +broadcast=com.alibaba.dubbo.rpc.cluster.support.BroadcastCluster +notify=com.alibaba.dubbo.rpc.cluster.support.NotifyCluster \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index fd7d26db8e5..459bb520f83 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -40,7 +40,7 @@ - + @@ -66,7 +66,7 @@ - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index d759eba9567..a54ecbc66cd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -17,7 +17,7 @@ public class AsyncContext { private static final ListeningExecutorService asyncExecutor = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16, new NamedThreadFactory("asyncContext", Boolean.TRUE))); + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncContext", Boolean.TRUE))); private final AsyncTarget asyncTarget; @@ -54,7 +54,7 @@ public void addListener(AsyncListener listener) { private void check() { if (started) { - throw new IllegalStateException("listener should not be added after context started."); + throw new IllegalStateException("listener should be added before context started."); } } } From cf6a508ebb09f54c32083c6c214cacace5198887 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 23 Apr 2017 15:14:24 +0800 Subject: [PATCH 44/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9AsyncContext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/rpc/cluster/support/NotifyClusterInvoker.java | 2 +- .../src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index 4201a5f3f7e..7572b0b1b69 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -15,7 +15,7 @@ */ public class NotifyClusterInvoker extends AbstractClusterInvoker{ - private static final Logger logger = LoggerFactory.getLogger(BroadcastClusterInvoker.class); + private static final Logger logger = LoggerFactory.getLogger(NotifyClusterInvoker.class); public NotifyClusterInvoker(Directory directory) { super(directory); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index a54ecbc66cd..b858ae8b323 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -1,5 +1,6 @@ package com.alibaba.dubbo.rpc; +import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; @@ -26,6 +27,7 @@ public class AsyncContext { private volatile boolean started; public AsyncContext(AsyncTarget asyncTarget) { + Assert.notNull(asyncTarget, "asyncTarget must not be null"); this.asyncTarget = asyncTarget; } @@ -43,6 +45,10 @@ public T call() throws Exception { return future; } + public static ListenableFuture start(Callable callable){ + return asyncExecutor.submit(callable); + } + public static void addListener(ListenableFuture future, AsyncListener asyncListener) { Futures.addCallback(future, asyncListener); } From bac84ec0b6e7b031ecb7728d8708e03f02786edf Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 23 Apr 2017 20:24:07 +0800 Subject: [PATCH 45/69] add AsyncInvocation extends AsyncTarget and AsyncListener --- .../cluster/support/NotifyClusterInvoker.java | 20 +++++++++---------- .../com/alibaba/dubbo/rpc/AsyncContext.java | 19 +++++++++++++----- .../alibaba/dubbo/rpc/AsyncInvocation.java | 11 ++++++++++ .../com/alibaba/dubbo/rpc/AsyncTarget.java | 2 +- .../rpc/proxy/AsyncableInvocationHandler.java | 6 ++---- 5 files changed, 37 insertions(+), 21 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index 7572b0b1b69..d3ba760e581 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -13,7 +13,7 @@ /** * @author Xs */ -public class NotifyClusterInvoker extends AbstractClusterInvoker{ +public class NotifyClusterInvoker extends AbstractClusterInvoker { private static final Logger logger = LoggerFactory.getLogger(NotifyClusterInvoker.class); @@ -32,10 +32,8 @@ private Result doInvokeAsync(final Invocation invocation, final List> final CountDownLatch latch = new CountDownLatch(invokers.size()); AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { - AsyncInvocation asyncInvocation = new AsyncInvocation(invoker, invocation, latch); - AsyncContext asyncContext = asyncInvocation.startAsync(); - asyncContext.addListener(asyncInvocation); - asyncContext.start(); + AsyncInvocation asyncInvocation = new AsyncInvocationImpl(invoker, invocation, latch); + asyncInvocation.async().start(asyncInvocation); asyncResultProcessor.addAsyncInvocation(asyncInvocation); } try { @@ -51,7 +49,7 @@ private Result doInvokeAsync(final Invocation invocation, final List> } - private class AsyncInvocation implements AsyncTarget, AsyncListener { + private class AsyncInvocationImpl implements AsyncInvocation { private final Invoker invoker; @@ -63,14 +61,14 @@ private class AsyncInvocation implements AsyncTarget, AsyncListener invoker, Invocation invocation, CountDownLatch latch) { + public AsyncInvocationImpl(Invoker invoker, Invocation invocation, CountDownLatch latch) { this.invoker = invoker; this.invocation = invocation; this.latch = latch; } @Override - public AsyncContext startAsync() { + public AsyncContext async() { return new AsyncContext(this); } @@ -128,13 +126,13 @@ public void addAsyncInvocation(AsyncInvocation asyncInvocation) { public void processResult() { for (AsyncInvocation invocation : asyncInvocations) { - if (invocation.getException() != null) { - exception = invocation.getException(); + exception = invocation.getException(); + if (exception != null) { break; } } if (exception == null) { - result = asyncInvocations.get(0).getResult(); + result = (Result) asyncInvocations.get(0).getResult(); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index b858ae8b323..2a4c446ac2b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -2,10 +2,7 @@ import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; +import com.google.common.util.concurrent.*; import java.util.ArrayList; import java.util.List; @@ -45,7 +42,19 @@ public T call() throws Exception { return future; } - public static ListenableFuture start(Callable callable){ + public ListenableFuture start(AsyncListener singleListener) { + ListenableFuture future = asyncExecutor.submit(new Callable() { + @Override + public T call() throws Exception { + return asyncTarget.invoke(); + } + }); + Futures.addCallback(future, singleListener); + started = true; + return future; + } + + public static ListenableFuture start(Callable callable) { return asyncExecutor.submit(callable); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java new file mode 100644 index 00000000000..2fefecb9677 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java @@ -0,0 +1,11 @@ +package com.alibaba.dubbo.rpc; + +/** + * @author Xs + */ +public interface AsyncInvocation extends AsyncTarget, AsyncListener { + + RpcException getException(); + + T getResult(); +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java index 13ee66fb352..7c5a77b6a79 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java @@ -2,7 +2,7 @@ public interface AsyncTarget { - AsyncContext startAsync(); + AsyncContext async(); T invoke() throws Exception; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 6009b310def..e2d0621fe74 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -18,8 +18,7 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg return super.invoke(proxy, method, args); } else { AsyncTarget asyncTarget = new AsyncMethodWrapper(proxy, method, args); - AsyncContext asyncContext = asyncTarget.startAsync(); - return asyncContext.start(); + return asyncTarget.async().start(); } } @@ -52,7 +51,7 @@ private Method getCorrespondingSyncMethod() throws Exception { return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); } - public AsyncContext startAsync() { + public AsyncContext async() { return new AsyncContext(this); } @@ -60,6 +59,5 @@ public AsyncContext startAsync() { public Object invoke() throws Exception { return getCorrespondingSyncMethod().invoke(proxy, args); } - } } From 1231258a7274b8ee704d07acca8fadd05b695154 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 25 Apr 2017 17:12:52 +0800 Subject: [PATCH 46/69] update README.md --- README.md | 9 +++++++++ .../dubbo/rpc/cluster/support/NotifyClusterInvoker.java | 1 - 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ca49bae7e11..14a0d392ae8 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ dubbo3 基于 [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) 修改 * 修改consumer端的异步实现方式,支持guava的ListenableFuture,使用异步调用api更加简单 +* 添加NotifyCluster和NotifyClusterInvoker代替BroadcastCluster和BroadcastClusterInvoker实现广播 + * 实现基于dubbo、hessian、http协议的分布式服务链路监控和追踪功能,可以将服务链路信息报告给[Zipkin](http://zipkin.io/),Zipkin的用户界面可以浏览全链路每一个服务的延迟 * 修改了ExchangeChannel中同步调用的接口,增加Interceptor接口拦截request记录服务调用信息 @@ -55,6 +57,13 @@ provider配置 #### auto-async自动生成异步接口 自动生成async interface需要使用[auto-async] (https://github.com/YanXs/auto-async) +### NotifyCluster广播 +dubbo中使用BroadcastCluster实现广播功能,实现方式是顺序调用所有的invoker。这种方式带来的问题是效率低,时间复杂度O(m*n),m代表invoker数量,n代表方法执行时间 +NotifyCluster采用异步模式并行调用invoker,时间复杂度可以接近O(n),当然取决于线程数量和invoker的数量,但是相比于BroadcastCluster线性调用性能高出很多 + +使用方式与broadcastCluster相同,只需要cluster=notify即可 +具体实现参考NotifyClusterInvoker + ### rpcTracker分布式链路追踪 diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index d3ba760e581..757ea4f82f7 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -24,7 +24,6 @@ public NotifyClusterInvoker(Directory directory) { @SuppressWarnings({"unchecked", "rawtypes"}) public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); - RpcContext.getContext().setInvokers((List) invokers); return doInvokeAsync(invocation, invokers); } From a8febf6faf6ed92835f762b07a1cd8b8d184aa15 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 25 Apr 2017 17:23:01 +0800 Subject: [PATCH 47/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20NotifyClusterInvoker?= =?UTF-8?q?=20AsyncContext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../cluster/support/NotifyClusterInvoker.java | 5 ++++- .../com/alibaba/dubbo/rpc/AsyncContext.java | 20 ++++++------------- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 14a0d392ae8..59af54c0e03 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ NotifyCluster采用异步模式并行调用invoker,时间复杂度可以接近 net.nightawk - nightawk-dubbo + nightawk-dubbo3 1.0.0.RELEASE ``` diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index 757ea4f82f7..cca9e45531c 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -32,7 +32,10 @@ private Result doInvokeAsync(final Invocation invocation, final List> AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { AsyncInvocation asyncInvocation = new AsyncInvocationImpl(invoker, invocation, latch); - asyncInvocation.async().start(asyncInvocation); + asyncInvocation + .async() + .addListener(asyncInvocation) + .start(); asyncResultProcessor.addAsyncInvocation(asyncInvocation); } try { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index 2a4c446ac2b..c4d9911493d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -2,7 +2,10 @@ import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.google.common.util.concurrent.*; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; import java.util.ArrayList; import java.util.List; @@ -42,18 +45,6 @@ public T call() throws Exception { return future; } - public ListenableFuture start(AsyncListener singleListener) { - ListenableFuture future = asyncExecutor.submit(new Callable() { - @Override - public T call() throws Exception { - return asyncTarget.invoke(); - } - }); - Futures.addCallback(future, singleListener); - started = true; - return future; - } - public static ListenableFuture start(Callable callable) { return asyncExecutor.submit(callable); } @@ -62,9 +53,10 @@ public static void addListener(ListenableFuture future, AsyncListener asyncListe Futures.addCallback(future, asyncListener); } - public void addListener(AsyncListener listener) { + public AsyncContext addListener(AsyncListener listener) { check(); listeners.add(listener); + return this; } private void check() { From 0b6919abc7d3ea78def4d88a55971f18087138f0 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 26 Apr 2017 13:01:34 +0800 Subject: [PATCH 48/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9AsyncContext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 ++++++++- .../main/java/com/alibaba/dubbo/rpc/AsyncContext.java | 10 +++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 59af54c0e03..8e887bb4f92 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Futures.addCallback(future, new FutureCallback() { }); ``` dubbo3中异步实现思路是为同步接口生成对应的异步接口,consumer和provider使用生成的接口 +在客户端的代理InvocationHandler中调用同步接口, 具体实现参考AsyncableInvocationHandler origin interface: ```java public interface SimpleService { @@ -56,7 +57,13 @@ provider配置 #### auto-async自动生成异步接口 自动生成async interface需要使用[auto-async] (https://github.com/YanXs/auto-async) - +```xml + + net.vakilla + auto-async + 1.0.0 + +``` ### NotifyCluster广播 dubbo中使用BroadcastCluster实现广播功能,实现方式是顺序调用所有的invoker。这种方式带来的问题是效率低,时间复杂度O(m*n),m代表invoker数量,n代表方法执行时间 NotifyCluster采用异步模式并行调用invoker,时间复杂度可以接近O(n),当然取决于线程数量和invoker的数量,但是相比于BroadcastCluster线性调用性能高出很多 diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java index c4d9911493d..f79de8ee5be 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java @@ -7,8 +7,8 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executors; @@ -22,7 +22,7 @@ public class AsyncContext { private final AsyncTarget asyncTarget; - private final List listeners = new ArrayList(); + private final Set listeners = new HashSet(); private volatile boolean started; @@ -49,10 +49,6 @@ public static ListenableFuture start(Callable callable) { return asyncExecutor.submit(callable); } - public static void addListener(ListenableFuture future, AsyncListener asyncListener) { - Futures.addCallback(future, asyncListener); - } - public AsyncContext addListener(AsyncListener listener) { check(); listeners.add(listener); From 6f23f92e33bfb3c5261086a05ae6ff7a2468b75e Mon Sep 17 00:00:00 2001 From: YanXs Date: Fri, 5 May 2017 18:31:11 +0800 Subject: [PATCH 49/69] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20ReplyManager=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=20PendingReply?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/Version.java | 2 +- .../support/header/HeaderExchangeChannel.java | 40 +++----- .../support/header/HeaderExchangeHandler.java | 7 +- .../support/header/HeaderExchangeServer.java | 12 ++- .../exchange/support/header/PendingReply.java | 31 +++--- .../exchange/support/header/ReplyManager.java | 99 +++++++++++++++++++ 6 files changed, 146 insertions(+), 45 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/ReplyManager.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java index 80ee7a65249..4063a5f1272 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java @@ -36,7 +36,7 @@ private Version() {} private static final Logger logger = LoggerFactory.getLogger(Version.class); - private static final String VERSION = getVersion(Version.class, "2.0.0"); + private static final String VERSION = getVersion(Version.class, "3.0.1"); private static final boolean INTERNAL = hasResource("com/alibaba/dubbo/registry/internal/RemoteRegistry.class"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index 7fd939c6d1a..fe2a920b451 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -30,8 +30,6 @@ import com.alibaba.dubbo.remoting.transport.ChannelHandler; import java.net.InetSocketAddress; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** @@ -45,7 +43,7 @@ final class HeaderExchangeChannel implements ExchangeChannel { private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; - public static final ConcurrentHashMap REPLY_HOLDER = new ConcurrentHashMap(); + private final ReplyManager replyManager = ReplyManager.get(); private final Channel channel; @@ -56,6 +54,7 @@ final class HeaderExchangeChannel implements ExchangeChannel { throw new IllegalArgumentException("channel == null"); } this.channel = channel; + replyManager.initReplyCounter(channel); } static HeaderExchangeChannel getOrAddChannel(Channel ch) { @@ -110,23 +109,23 @@ public Response request(Request request, int timeout) throws RemotingException { throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } - PendingReply pendingReply = new PendingReply(request.getId()); - addPendingReply(pendingReply); + PendingReply pendingReply = new PendingReply(); + pendingReply.setMessageId(request.getId()); + replyManager.addPendingReply(request.getId(), pendingReply, channel); long startTimeMs = System.currentTimeMillis(); try { channel.send(request); } catch (RemotingException e) { - removePendingReply(pendingReply); + replyManager.removePendingReply(pendingReply, channel); throw e; } - LinkedBlockingQueue reply = pendingReply.getQueue(); Response response = null; try { - response = (timeout <= 0) ? reply.take() : reply.poll(timeout, TimeUnit.MILLISECONDS); + response = pendingReply.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RemotingException(this, e); } finally { - removePendingReply(pendingReply); + replyManager.removePendingReply(pendingReply, channel); } // timeout if (response == null) { @@ -142,24 +141,6 @@ public String getTimeoutMessage(Request request, int timeout, long startTimeMs) + " -> " + channel.getRemoteAddress(); } - private static void addPendingReply(PendingReply pendingReply) { - REPLY_HOLDER.putIfAbsent(pendingReply.getSavedReplyTo(), pendingReply); - } - - private static void removePendingReply(PendingReply pendingReply) { - REPLY_HOLDER.remove(pendingReply.getSavedReplyTo()); - } - - public static void handleResponse(Response response) { - PendingReply pendingReply = REPLY_HOLDER.get(response.getId()); - if (pendingReply == null) { - logger.warn("Response received after timeout for " + response); - return; - } - LinkedBlockingQueue replyHandoff = pendingReply.getQueue(); - replyHandoff.add(response); - } - public boolean isClosed() { return closed; } @@ -169,6 +150,8 @@ public void close() { channel.close(); } catch (Throwable e) { logger.warn(e.getMessage(), e); + } finally { + replyManager.destroyReplyCounter(channel); } } @@ -192,7 +175,8 @@ public void close(int timeout) { } private boolean shouldWait(long start, long timeout) { - return (System.currentTimeMillis() - start < timeout) && !REPLY_HOLDER.isEmpty(); + return System.currentTimeMillis() - start <= timeout && + replyManager.isChannelHoldingReplies(channel); } public InetSocketAddress getLocalAddress() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index 8089a3a7466..005d2532465 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -54,6 +54,8 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { private final ExchangeHandler handler; + private final ReplyManager replyManager = ReplyManager.get(); + public HeaderExchangeHandler(ExchangeHandler handler) { if (handler == null) { throw new IllegalArgumentException("handler == null"); @@ -94,7 +96,10 @@ private Response handleRequest(ExchangeChannel channel, Request req) throws Remo private void handleResponse(Response response) throws RemotingException { if (response != null && !response.isHeartbeat()) { - HeaderExchangeChannel.handleResponse(response); + PendingReply pendingReply = replyManager.getPendingReply(response.getId()); + if (pendingReply != null) { + pendingReply.reply(response); + } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index c25c1ffe024..b4173480048 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -62,6 +62,8 @@ public class HeaderExchangeServer implements ExchangeServer { private final Server server; + private final ReplyManager replyManager = ReplyManager.get(); + private volatile boolean closed = false; public HeaderExchangeServer(Server server) { @@ -86,7 +88,13 @@ public boolean isClosed() { } private boolean isRunning() { - return !HeaderExchangeChannel.REPLY_HOLDER.isEmpty(); + Collection channels = getChannels(); + for (Channel channel : channels) { + if (replyManager.isChannelHoldingReplies(channel)) { + return true; + } + } + return false; } public void close() { @@ -125,7 +133,7 @@ private void sendChannelReadOnlyEvent() { if (channel.isConnected()) channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } catch (RemotingException e) { - logger.warn("send connot write messge error.", e); + logger.warn("send cannot write message error.", e); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java index 1fe75c0d20f..7bfe276ba56 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/PendingReply.java @@ -3,31 +3,36 @@ import com.alibaba.dubbo.remoting.message.Response; -import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; /** - * ADD CALLBACK HERE ?? + * @author Xs. */ public class PendingReply { - private volatile Long savedReplyTo; + private volatile Long messageId; - private final LinkedBlockingQueue queue; + private final BlockingQueue queue = new ArrayBlockingQueue(1); - public PendingReply(Long savedReplyTo) { - this.savedReplyTo = savedReplyTo; - this.queue = new LinkedBlockingQueue(); + public Long getMessageId() { + return messageId; } - public Long getSavedReplyTo() { - return savedReplyTo; + public void setMessageId(Long messageId) { + this.messageId = messageId; } - public void setSavedReplyTo(Long savedReplyTo) { - this.savedReplyTo = savedReplyTo; + public void reply(Response reply) { + this.queue.add(reply); } - public LinkedBlockingQueue getQueue() { - return queue; + public Response get(long timeout, TimeUnit unit) throws InterruptedException { + return (timeout <= 0) ? queue.take() : queue.poll(timeout, unit); + } + + public Response get() throws InterruptedException { + return queue.take(); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/ReplyManager.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/ReplyManager.java new file mode 100644 index 00000000000..796c75cb107 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/header/ReplyManager.java @@ -0,0 +1,99 @@ +package com.alibaba.dubbo.remoting.exchange.support.header; + +import com.alibaba.dubbo.remoting.transport.Channel; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +public class ReplyManager { + + private static final ReplyManager instance = new ReplyManager(); + + private final Map replyStore = new StrictConcurrentHashMap(); + + private final Map channelReplyCounters = new ConcurrentHashMap(); + + private ReplyManager() { + } + + public static ReplyManager get() { + return instance; + } + + public void initReplyCounter(Channel channel) { + ChannelReplyCounter counter = channelReplyCounters.get(channel); + if (counter == null) { + counter = new ChannelReplyCounter(channel); + channelReplyCounters.put(channel, counter); + } + } + + public void destroyReplyCounter(Channel channel) { + channelReplyCounters.remove(channel); + } + + public void addPendingReply(Long id, PendingReply pendingReply, Channel channel) { + replyStore.put(id, pendingReply); + ChannelReplyCounter counter = channelReplyCounters.get(channel); + if (counter == null) { + throw new IllegalStateException("channelReplyCounter should not be null here"); + } + counter.increment(); + } + + public PendingReply getPendingReply(Long messageId) { + return replyStore.get(messageId); + } + + public void removePendingReply(PendingReply pendingReply, Channel channel) { + replyStore.remove(pendingReply.getMessageId()); + ChannelReplyCounter counter = channelReplyCounters.get(channel); + if (counter == null) { + throw new IllegalStateException("channelReplyCounter should not be null here"); + } + counter.decrement(); + } + + public boolean isChannelHoldingReplies(Channel channel) { + ChannelReplyCounter counter = channelReplyCounters.get(channel); + return counter != null && counter.get() > 0; + } + + private class StrictConcurrentHashMap extends ConcurrentHashMap { + public V put(K key, V value) { + if (contains(key)) { + throw new IllegalArgumentException("contains value for key: " + key); + } + return super.put(key, value); + } + } + + + private class ChannelReplyCounter { + + private final Channel channel; + + private final AtomicInteger counter = new AtomicInteger(0); + + private ChannelReplyCounter(Channel channel) { + this.channel = channel; + } + + public Channel getChannel() { + return channel; + } + + public void increment() { + counter.incrementAndGet(); + } + + public void decrement() { + counter.decrementAndGet(); + } + + public int get() { + return counter.get(); + } + } +} From 5631d96c4b9fc94488f928077e709c6789241be6 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 8 May 2017 20:11:30 +0800 Subject: [PATCH 50/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20DubboRequest=20Dubbo?= =?UTF-8?q?Response?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/META-INF/spring/dubbo-demo-provider.xml | 2 +- .../java/com/alibaba/dubbo/tracker/DubboRequest.java | 8 ++++++-- .../java/com/alibaba/dubbo/tracker/DubboResponse.java | 9 +-------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 459bb520f83..ccbb5a1d2df 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -40,7 +40,7 @@ - + diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java index ef84c9d9d34..c5c28ddb45c 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboRequest.java @@ -18,11 +18,15 @@ public class DubboRequest { private boolean isTraceable; - public DubboRequest(Request request) { + public enum Type { + IN, OUT + } + + public DubboRequest(Request request, Type type) { this.request = request; if (request.getData() instanceof RpcInvocation) { - isTraceable = getAttachment(RpcAttachment.Sampled.getName()) != null; invocation = (RpcInvocation) request.getData(); + isTraceable = (type == Type.OUT || getAttachment(RpcAttachment.Sampled.getName()) != null); } } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index ca5bb9f5d90..ac02af9bd62 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -10,14 +10,11 @@ public class DubboResponse { private final Response response; - private boolean isTraceable; - - private volatile RpcResult result; + private RpcResult result; public DubboResponse(Response response) { this.response = response; if (response.getResult() instanceof RpcResult) { - isTraceable = result.getAttachment(RpcAttachment.Sampled.getName()) != null; result = (RpcResult) response.getResult(); } } @@ -26,10 +23,6 @@ public boolean returnOK() { return response.getStatus() == Response.OK && !result.hasException(); } - public boolean isTraceable() { - return isTraceable; - } - public String exceptionMessage() { if (returnOK()) { return "response OK"; From 53b9dd36154e030f809c3c94c2643ce007784e03 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 9 May 2017 18:35:45 +0800 Subject: [PATCH 51/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20DubboResponse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/remoting/exchange/codec/ExchangeCodec.java | 1 - dubbo-tracker/dubbo-tracker-api/pom.xml | 9 +++++++-- .../java/com/alibaba/dubbo/tracker/DubboResponse.java | 10 ++++++---- pom.xml | 8 ++++++++ 4 files changed, 21 insertions(+), 7 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 063c896c484..37e944d1835 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -79,7 +79,6 @@ public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOE if (logger.isTraceEnabled()) { logger.trace("the resulting byte size of encoding is " + buffer.readableBytes()); } - } public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { diff --git a/dubbo-tracker/dubbo-tracker-api/pom.xml b/dubbo-tracker/dubbo-tracker-api/pom.xml index d3a4d0957f5..4c3bc276c7e 100644 --- a/dubbo-tracker/dubbo-tracker-api/pom.xml +++ b/dubbo-tracker/dubbo-tracker-api/pom.xml @@ -22,13 +22,13 @@ com.alibaba dubbo-remoting-common - 3.0.1 + ${project.parent.version} com.alibaba dubbo-rpc-api - 3.0.1 + ${project.parent.version} @@ -40,6 +40,11 @@ com.squareup.okhttp3 okhttp + + + org.apache.commons + commons-lang3 + \ No newline at end of file diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java index ac02af9bd62..c6ee631d7f5 100644 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java +++ b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/DubboResponse.java @@ -2,6 +2,7 @@ import com.alibaba.dubbo.remoting.message.Response; import com.alibaba.dubbo.rpc.RpcResult; +import org.apache.commons.lang3.exception.ExceptionUtils; /** * @author Xs. @@ -20,7 +21,8 @@ public DubboResponse(Response response) { } public boolean returnOK() { - return response.getStatus() == Response.OK && !result.hasException(); + return response.getStatus() == Response.OK + && !result.hasException(); } public String exceptionMessage() { @@ -28,9 +30,9 @@ public String exceptionMessage() { return "response OK"; } Throwable throwable = result.getException(); - if (throwable instanceof NullPointerException) { - return "NullPointerException"; + if (throwable != null) { + return ExceptionUtils.getStackTrace(throwable); } - return throwable.getMessage(); + return "response " + response.getStatus(); } } diff --git a/pom.xml b/pom.xml index d296e6295e0..af9d091a83f 100644 --- a/pom.xml +++ b/pom.xml @@ -458,8 +458,16 @@ okhttp 3.2.0 + + + org.apache.commons + commons-lang3 + 3.3.2 + + + junit From 9cf1be5db86735394e82c46cd3cf17f0d354bf4f Mon Sep 17 00:00:00 2001 From: YanXs Date: Thu, 11 May 2017 23:31:49 +0800 Subject: [PATCH 52/69] README.md --- README.md | 14 +-- .../support/BroadcastClusterInvoker.java | 1 - .../support/FailoverClusterInvoker.java | 1 - .../support/ForkingClusterInvoker.java | 103 +++++++++--------- .../dubbo/config/spring/ConfigTest.java | 4 - .../com/alibaba/dubbo/rpc/RpcContext.java | 27 +---- 6 files changed, 61 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index 8e887bb4f92..ffb5a0a67be 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,8 @@ Futures.addCallback(future, new FutureCallback() { }); ``` dubbo3中异步实现思路是为同步接口生成对应的异步接口,consumer和provider使用生成的接口 -在客户端的代理InvocationHandler中调用同步接口, 具体实现参考AsyncableInvocationHandler -origin interface: +在客户端的代理InvocationHandler中调用同步接口, 具体实现参考AsyncableInvocationHandler +origin interface: ```java public interface SimpleService { Complex getComplex(String id); @@ -109,30 +109,30 @@ NotifyCluster采用异步模式并行调用invoker,时间复杂度可以接近 ## 依赖 服务链路追踪主要基于Zipkin的 [brave] (https://github.com/openzipkin/brave) -链路追踪功能分离到另一个项目 [nightawk] (https://github.com/YanXs/nighthawk) +链路追踪功能参考另一个项目 [nightawk] (https://github.com/YanXs/nighthawk) 项目中需要引用 ```xml com.alibaba dubbo - 3.0.0 + 3.0.1 - net.nightawk + io.vakilla.nightawk nightawk-core 1.0.0.RELEASE - net.nightawk + io.vakilla.nightawk nightawk-dubbo3 1.0.0.RELEASE ``` -以上依赖需要自己使用maven编译打包 +以上依赖需要自己使用maven编译打包(以后会提交到maven中央库) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java index ea439fe1b3c..09ee6c005d8 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java @@ -40,7 +40,6 @@ public BroadcastClusterInvoker(Directory directory) { @SuppressWarnings({"unchecked", "rawtypes"}) public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); - RpcContext.getContext().setInvokers((List) invokers); RpcException exception = null; Result result = null; for (Invoker invoker : invokers) { diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java index bc7423acb77..d58118c8615 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/FailoverClusterInvoker.java @@ -68,7 +68,6 @@ public Result doInvoke(Invocation invocation, final List> invokers, L } Invoker invoker = select(loadbalance, invocation, copyinvokers, invoked); invoked.add(invoker); - RpcContext.getContext().setInvokers((List) invoked); try { Result result = invoker.invoke(invocation); if (le != null && logger.isWarnEnabled()) { diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index 1ee93ec827a..07d63f59578 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.rpc.cluster.support; - +package com.alibaba.dubbo.rpc.cluster.support; + import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -33,67 +33,66 @@ import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; - -/** + +/** * 并行调用,只要一个成功即返回,通常用于实时性要求较高的操作,但需要浪费更多服务资源。 * - * Fork - * - * @author william.liangf - */ -public class ForkingClusterInvoker extends AbstractClusterInvoker{ + * Fork + * + * @author william.liangf + */ +public class ForkingClusterInvoker extends AbstractClusterInvoker{ private final ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("forking-cluster-timer", true)); - - public ForkingClusterInvoker(Directory directory) { - super(directory); - } - + + public ForkingClusterInvoker(Directory directory) { + super(directory); + } + @SuppressWarnings({ "unchecked", "rawtypes" }) public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); - final List> selected; - final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS); - final int timeout = getUrl().getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); - if (forks <= 0 || forks >= invokers.size()) { - selected = invokers; - } else { - selected = new ArrayList>(); - for (int i = 0; i < forks; i++) { - //在invoker列表(排除selected)后,如果没有选够,则存在重复循环问题.见select实现. - Invoker invoker = select(loadbalance, invocation, invokers, selected); - if(!selected.contains(invoker)){//防止重复添加invoker - selected.add(invoker); - } - } + final List> selected; + final int forks = getUrl().getParameter(Constants.FORKS_KEY, Constants.DEFAULT_FORKS); + final int timeout = getUrl().getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); + if (forks <= 0 || forks >= invokers.size()) { + selected = invokers; + } else { + selected = new ArrayList>(); + for (int i = 0; i < forks; i++) { + //在invoker列表(排除selected)后,如果没有选够,则存在重复循环问题.见select实现. + Invoker invoker = select(loadbalance, invocation, invokers, selected); + if(!selected.contains(invoker)){//防止重复添加invoker + selected.add(invoker); + } + } } - RpcContext.getContext().setInvokers((List)selected); - final AtomicInteger count = new AtomicInteger(); - final BlockingQueue ref = new LinkedBlockingQueue(); - for (final Invoker invoker : selected) { - executor.execute(new Runnable() { - public void run() { - try { - Result result = invoker.invoke(invocation); - ref.offer(result); - } catch(Throwable e) { - int value = count.incrementAndGet(); - if (value >= selected.size()) { - ref.offer(e); - } - } - } - }); - } - try { + final AtomicInteger count = new AtomicInteger(); + final BlockingQueue ref = new LinkedBlockingQueue(); + for (final Invoker invoker : selected) { + executor.execute(new Runnable() { + public void run() { + try { + Result result = invoker.invoke(invocation); + ref.offer(result); + } catch(Throwable e) { + int value = count.incrementAndGet(); + if (value >= selected.size()) { + ref.offer(e); + } + } + } + }); + } + try { Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS); if (ret instanceof Throwable) { Throwable e = (Throwable) ret; throw new RpcException(e instanceof RpcException ? ((RpcException)e).getCode() : 0, "Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e.getCause() != null ? e.getCause() : e); } - return (Result) ret; - } catch (InterruptedException e) { - throw new RpcException("Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e); - } - } + return (Result) ret; + } catch (InterruptedException e) { + throw new RpcException("Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e); + } + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index 71d81d3d7af..44894330b90 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -415,8 +415,6 @@ public void test_RpcContext_getUrls() throws Exception { } catch (RpcException expected) { assertThat(expected.getMessage(), containsString("Tried 3 times")); } - - assertEquals(3, RpcContext.getContext().getUrls().size()); } finally { ctx.stop(); ctx.close(); @@ -447,8 +445,6 @@ public void test_retrySettingFail() throws Exception { } catch (RpcException expected) { assertThat(expected.getMessage(), containsString("Tried 1 times")); } - - assertEquals(1, RpcContext.getContext().getUrls().size()); } finally { ctx.stop(); ctx.close(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index 5779cc649c2..aebd9dc62d9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -15,13 +15,12 @@ */ package com.alibaba.dubbo.rpc; -import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.NetUtils; import java.net.InetSocketAddress; -import java.util.*; -import java.util.concurrent.*; +import java.util.HashMap; +import java.util.Map; /** * Thread local context. (API, ThreadLocal, ThreadSafe) @@ -42,6 +41,7 @@ protected RpcContext initialValue() { return new RpcContext(); } }; + /** * get context. * @@ -60,8 +60,6 @@ public static void removeContext() { LOCAL.remove(); } - private List urls; - private URL url; private String methodName; @@ -134,13 +132,6 @@ public void setResponse(Object response) { this.response = response; } - public List getUrls() { - return urls == null && url != null ? (List) Collections.singletonList(url) : urls; - } - - public void setUrls(List urls) { - this.urls = urls; - } public URL getUrl() { return url; @@ -448,17 +439,6 @@ public Object get(String key) { return values.get(key); } - public RpcContext setInvokers(List> invokers) { - if (invokers != null && invokers.size() > 0) { - List urls = new ArrayList(invokers.size()); - for (Invoker invoker : invokers) { - urls.add(invoker.getUrl()); - } - setUrls(urls); - } - return this; - } - public RpcContext setInvoker(Invoker invoker) { if (invoker != null) { setUrl(invoker.getUrl()); @@ -474,5 +454,4 @@ public RpcContext setInvocation(Invocation invocation) { } return this; } - } \ No newline at end of file From 4b9adc27209a026c8f3fe0ba740dbbfccd852bd9 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 13 May 2017 10:26:02 +0800 Subject: [PATCH 53/69] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ffb5a0a67be..9bad619584f 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ dubbo3 基于 [dubbox 2.8.4] (https://github.com/dangdangdotcom/dubbox) 修改 ## dubbo3修改和增加的功能 -* 修改consumer端的异步实现方式,支持guava的ListenableFuture,使用异步调用api更加简单 +* 重新设计实现了consumer端的异步实现方式,支持guava的ListenableFuture,使用异步调用api更加简单 * 添加NotifyCluster和NotifyClusterInvoker代替BroadcastCluster和BroadcastClusterInvoker实现广播 @@ -40,7 +40,7 @@ public interface SimpleService { Complex getComplex(String id); } ``` -async interface: +async interface:(使用auto-async自动生成) ```java public interface Unified_SimpleService extends SimpleService { ListenableFuture async_getComplex(String id); From 6a1281f3a283604ae04ac4ac065094a9173d32b3 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 17 May 2017 19:52:02 +0800 Subject: [PATCH 54/69] =?UTF-8?q?=E5=BC=82=E6=AD=A5=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cluster/support/NotifyClusterInvoker.java | 12 +++-- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../{AsyncContext.java => AsyncCommand.java} | 42 +++++++++++------- .../com/alibaba/dubbo/rpc/AsyncTarget.java | 4 +- .../rpc/proxy/AsyncableInvocationHandler.java | 12 ++--- .../javassist/JavassistProxyFactory.java | 8 ++-- .../rpc/protocol/dubbo/DubboInvoker.java | 7 +-- .../rpc/protocol/dubbo/DubboProtocol.java | 13 ++++-- .../alibaba/dubbo/tracker/RpcResponse.java | 44 ------------------- 9 files changed, 55 insertions(+), 89 deletions(-) rename dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/{AsyncContext.java => AsyncCommand.java} (53%) delete mode 100644 dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index cca9e45531c..4ecacf0e962 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -32,10 +32,8 @@ private Result doInvokeAsync(final Invocation invocation, final List> AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { AsyncInvocation asyncInvocation = new AsyncInvocationImpl(invoker, invocation, latch); - asyncInvocation - .async() - .addListener(asyncInvocation) - .start(); + AsyncCommand command = asyncInvocation.async(); + command.addListener(asyncInvocation).execute(); asyncResultProcessor.addAsyncInvocation(asyncInvocation); } try { @@ -70,12 +68,12 @@ public AsyncInvocationImpl(Invoker invoker, Invocation invocation, CountDownL } @Override - public AsyncContext async() { - return new AsyncContext(this); + public AsyncCommand async() { + return new AsyncCommand(this); } @Override - public Result invoke() throws Exception { + public Result run() throws Exception { return doInvoke(invoker, invocation); } diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 09959c11d9c..403950ffc0c 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java similarity index 53% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java index f79de8ee5be..ff8e55bceea 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java @@ -2,6 +2,7 @@ import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.google.common.base.Preconditions; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; @@ -11,53 +12,60 @@ import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; /** * @author Xs */ -public class AsyncContext { +public class AsyncCommand { - private static final ListeningExecutorService asyncExecutor = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncContext", Boolean.TRUE))); + private static final ListeningExecutorService asyncCommandExecutor = + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); private final AsyncTarget asyncTarget; - private final Set listeners = new HashSet(); + private final Set listeners = new HashSet(8); - private volatile boolean started; + private final AtomicReference state = new AtomicReference(State.LATENT); - public AsyncContext(AsyncTarget asyncTarget) { + private enum State { + LATENT, + STARTED, + FINISHED + } + + public AsyncCommand(AsyncTarget asyncTarget) { Assert.notNull(asyncTarget, "asyncTarget must not be null"); this.asyncTarget = asyncTarget; } - public ListenableFuture start() { - ListenableFuture future = asyncExecutor.submit(new Callable() { + public ListenableFuture execute() { + Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "command could be execute more than once"); + ListenableFuture future = asyncCommandExecutor.submit(new Callable() { @Override public T call() throws Exception { - return asyncTarget.invoke(); + try { + return asyncTarget.run(); + } finally { + state.compareAndSet(State.STARTED, State.FINISHED); + } } }); for (AsyncListener asyncListener : listeners) { Futures.addCallback(future, asyncListener); } - started = true; return future; } - public static ListenableFuture start(Callable callable) { - return asyncExecutor.submit(callable); - } - - public AsyncContext addListener(AsyncListener listener) { + public AsyncCommand addListener(AsyncListener listener) { check(); listeners.add(listener); return this; } private void check() { - if (started) { - throw new IllegalStateException("listener should be added before context started."); + if (state.get() != State.LATENT) { + throw new IllegalStateException("listener should be added before command started."); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java index 7c5a77b6a79..748b900df72 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java @@ -2,7 +2,7 @@ public interface AsyncTarget { - AsyncContext async(); + AsyncCommand async(); - T invoke() throws Exception; + T run() throws Exception; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index e2d0621fe74..ed163797856 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.rpc.proxy; -import com.alibaba.dubbo.rpc.AsyncContext; +import com.alibaba.dubbo.rpc.AsyncCommand; import com.alibaba.dubbo.rpc.AsyncTarget; import com.alibaba.dubbo.rpc.Invoker; @@ -18,7 +18,7 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg return super.invoke(proxy, method, args); } else { AsyncTarget asyncTarget = new AsyncMethodWrapper(proxy, method, args); - return asyncTarget.async().start(); + return asyncTarget.async().execute(); } } @@ -30,7 +30,7 @@ private boolean isAsyncMethod(Method method) { /** * async method wrapper */ - public static class AsyncMethodWrapper implements AsyncTarget { + class AsyncMethodWrapper implements AsyncTarget { private final Object proxy; @@ -51,12 +51,12 @@ private Method getCorrespondingSyncMethod() throws Exception { return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); } - public AsyncContext async() { - return new AsyncContext(this); + public AsyncCommand async() { + return new AsyncCommand(this); } @Override - public Object invoke() throws Exception { + public Object run() throws Exception { return getCorrespondingSyncMethod().invoke(proxy, args); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java index 4c6d70e7c58..e06dd61d5f2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java @@ -22,11 +22,10 @@ import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; import com.alibaba.dubbo.rpc.proxy.AsyncableInvocationHandler; -import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler; /** * JavassistRpcProxyFactory - + * * @author william.liangf */ public class JavassistProxyFactory extends AbstractProxyFactory { @@ -41,12 +40,11 @@ public Invoker getInvoker(T proxy, Class type, URL url) { final Wrapper wrapper = Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type); return new AbstractProxyInvoker(proxy, type, url) { @Override - protected Object doInvoke(T proxy, String methodName, - Class[] parameterTypes, + protected Object doInvoke(T proxy, String methodName, + Class[] parameterTypes, Object[] arguments) throws Throwable { return wrapper.invokeMethod(proxy, methodName, parameterTypes, arguments); } }; } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 92ce7f37721..8d5e07da544 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -74,7 +74,6 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { currentClient = clients[index.getAndIncrement() % clients.length]; } try { - boolean isAsync = RpcUtils.isAsync(getUrl(), invocation); boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); if (isOneway) { @@ -87,9 +86,11 @@ protected Result doInvoke(final Invocation invocation) throws Throwable { return (Result) response.getResult(); } } catch (TimeoutException e) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (RemotingException e) { - throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index d637d5ac9f0..04b327f3812 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -97,14 +97,17 @@ public Object reply(ExchangeChannel channel, Object message) throws RemotingExce } } 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); + 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, (message.getClass().getName() + ": " + message) + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); + throw new RemotingException(channel, (message.getClass().getName() + ": " + message) + ", channel: consumer: " + + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); } @Override @@ -124,7 +127,7 @@ public void connected(Channel channel) throws RemotingException { @Override public void disconnected(Channel channel) throws RemotingException { if (logger.isInfoEnabled()) { - logger.info("disconected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); + logger.info("disconnected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); } invoke(channel, Constants.ON_DISCONNECT_KEY); } @@ -194,7 +197,9 @@ Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); if (exporter == null) - throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv); + throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv); return exporter.getInvoker(); } diff --git a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java b/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java deleted file mode 100644 index 8c76f59a5d0..00000000000 --- a/dubbo-tracker/dubbo-tracker-api/src/main/java/com/alibaba/dubbo/tracker/RpcResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.alibaba.dubbo.tracker; - -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcResult; - -public class RpcResponse { - - private final Invoker invoker; - - private final Result result; - - public RpcResponse(Invoker invoker, Result result) { - this.invoker = invoker; - this.result = result; - } - - public Invoker getInvoker() { - return invoker; - } - - public Result getResult() { - return result; - } - - public boolean isTraceableResponse() { - return result instanceof RpcResult; - } - - public boolean returnSuccessfully() { - return !result.hasException(); - } - - public String exceptionMessage(){ - if (returnSuccessfully()) { - return "result OK"; - } - Throwable throwable = result.getException(); - if (throwable instanceof NullPointerException) { - return "NullPointerException"; - } - return throwable.getMessage(); - } -} From dc8f29cae72025e2f966ca3469101948b0b5cbb7 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 17 May 2017 19:59:32 +0800 Subject: [PATCH 55/69] add AsyncRunnable --- .../main/java/com/alibaba/dubbo/rpc/AsyncCommand.java | 10 +++++----- .../java/com/alibaba/dubbo/rpc/AsyncInvocation.java | 2 +- .../dubbo/rpc/{AsyncTarget.java => AsyncRunnable.java} | 2 +- .../dubbo/rpc/proxy/AsyncableInvocationHandler.java | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) rename dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/{AsyncTarget.java => AsyncRunnable.java} (72%) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java index ff8e55bceea..7109a61d149 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java @@ -22,7 +22,7 @@ public class AsyncCommand { private static final ListeningExecutorService asyncCommandExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); - private final AsyncTarget asyncTarget; + private final AsyncRunnable asyncRunnable; private final Set listeners = new HashSet(8); @@ -34,9 +34,9 @@ private enum State { FINISHED } - public AsyncCommand(AsyncTarget asyncTarget) { - Assert.notNull(asyncTarget, "asyncTarget must not be null"); - this.asyncTarget = asyncTarget; + public AsyncCommand(AsyncRunnable asyncRunnable) { + Assert.notNull(asyncRunnable, "asyncTarget must not be null"); + this.asyncRunnable = asyncRunnable; } public ListenableFuture execute() { @@ -45,7 +45,7 @@ public ListenableFuture execute() { @Override public T call() throws Exception { try { - return asyncTarget.run(); + return asyncRunnable.run(); } finally { state.compareAndSet(State.STARTED, State.FINISHED); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java index 2fefecb9677..b1b7dc7aba1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java @@ -3,7 +3,7 @@ /** * @author Xs */ -public interface AsyncInvocation extends AsyncTarget, AsyncListener { +public interface AsyncInvocation extends AsyncRunnable, AsyncListener { RpcException getException(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java similarity index 72% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java index 748b900df72..025b1a2aefa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncTarget.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.rpc; -public interface AsyncTarget { +public interface AsyncRunnable { AsyncCommand async(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index ed163797856..681e1b33718 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -1,7 +1,7 @@ package com.alibaba.dubbo.rpc.proxy; import com.alibaba.dubbo.rpc.AsyncCommand; -import com.alibaba.dubbo.rpc.AsyncTarget; +import com.alibaba.dubbo.rpc.AsyncRunnable; import com.alibaba.dubbo.rpc.Invoker; import java.lang.reflect.Method; @@ -17,8 +17,8 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (!isAsyncMethod(method)) { return super.invoke(proxy, method, args); } else { - AsyncTarget asyncTarget = new AsyncMethodWrapper(proxy, method, args); - return asyncTarget.async().execute(); + AsyncRunnable asyncRunnable = new AsyncMethodWrapper(proxy, method, args); + return asyncRunnable.async().execute(); } } @@ -30,7 +30,7 @@ private boolean isAsyncMethod(Method method) { /** * async method wrapper */ - class AsyncMethodWrapper implements AsyncTarget { + class AsyncMethodWrapper implements AsyncRunnable { private final Object proxy; From 17683a6664e60013424a2a7a662c7ea5900d6c19 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 17 May 2017 20:06:24 +0800 Subject: [PATCH 56/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B5=8B=E8=AF=95=20no?= =?UTF-8?q?tifyCluster?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/META-INF/spring/dubbo-demo-consumer.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 403950ffc0c..4c679a69dbd 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + From 64d2f42ed935307bca092feccd9bf39417c5d179 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 21 May 2017 21:01:45 +0800 Subject: [PATCH 57/69] add HystrixFilter using Hystrix --- .../support/fixed/FixedThreadPool.java | 23 +++---- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../remoting/transport/AbstractServer.java | 60 +++++++++---------- dubbo-rpc/dubbo-rpc-api/pom.xml | 11 ++++ .../dubbo/rpc/filter/ActiveLimitFilter.java | 27 ++++----- .../dubbo/rpc/filter/HystrixFilter.java | 60 +++++++++++++++++++ .../rpc/listener/ListenerInvokerWrapper.java | 2 +- 7 files changed, 123 insertions(+), 62 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/threadpool/support/fixed/FixedThreadPool.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/threadpool/support/fixed/FixedThreadPool.java index cdd2dce1759..a5a6925e905 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/threadpool/support/fixed/FixedThreadPool.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/threadpool/support/fixed/FixedThreadPool.java @@ -15,23 +15,19 @@ */ package com.alibaba.dubbo.common.threadpool.support.fixed; -import java.util.concurrent.Executor; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.common.threadpool.support.AbortPolicyWithReport; import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import java.util.concurrent.*; + /** * 此线程池启动时即创建固定大小的线程数,不做任何伸缩,来源于:Executors.newFixedThreadPool() - * - * @see java.util.concurrent.Executors#newFixedThreadPool(int) + * * @author william.liangf + * @see java.util.concurrent.Executors#newFixedThreadPool(int) */ public class FixedThreadPool implements ThreadPool { @@ -39,11 +35,10 @@ public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); - return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS, - queues == 0 ? new SynchronousQueue() : - (queues < 0 ? new LinkedBlockingQueue() - : new LinkedBlockingQueue(queues)), - new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url)); + return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS, + queues == 0 ? new SynchronousQueue() : + (queues < 0 ? new LinkedBlockingQueue() + : new LinkedBlockingQueue(queues)), + new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } - } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 4c679a69dbd..403950ffc0c 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java index 789098a07f4..3f29529c965 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java @@ -15,11 +15,6 @@ */ package com.alibaba.dubbo.remoting.transport; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; @@ -30,34 +25,39 @@ import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.exception.RemotingException; +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; + /** * AbstractServer - * + * * @author qian.lei * @author ding.lid */ public abstract class AbstractServer extends AbstractEndpoint implements Server { - + private static final Logger logger = LoggerFactory.getLogger(AbstractServer.class); - private InetSocketAddress localAddress; + private InetSocketAddress localAddress; + + private InetSocketAddress bindAddress; + + private int accepts; - private InetSocketAddress bindAddress; + private int idleTimeout = 600; //600 seconds - private int accepts; + protected static final String SERVER_THREAD_POOL_NAME = "DubboServerHandler"; - private int idleTimeout = 600; //600 seconds - - protected static final String SERVER_THREAD_POOL_NAME ="DubboServerHandler"; - ExecutorService executor; public AbstractServer(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); localAddress = getUrl().toInetSocketAddress(); - String host = url.getParameter(Constants.ANYHOST_KEY, false) - || NetUtils.isInvalidLocalHost(getUrl().getHost()) - ? NetUtils.ANYHOST : getUrl().getHost(); + String host = url.getParameter(Constants.ANYHOST_KEY, false) + || NetUtils.isInvalidLocalHost(getUrl().getHost()) + ? NetUtils.ANYHOST : getUrl().getHost(); bindAddress = new InetSocketAddress(host, getUrl().getPort()); this.accepts = url.getParameter(Constants.ACCEPTS_KEY, Constants.DEFAULT_ACCEPTS); this.idleTimeout = url.getParameter(Constants.IDLE_TIMEOUT_KEY, Constants.DEFAULT_IDLE_TIMEOUT); @@ -67,16 +67,16 @@ public AbstractServer(URL url, ChannelHandler handler) throws RemotingException logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } } catch (Throwable t) { - throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() - + " on " + getLocalAddress() + ", cause: " + t.getMessage(), t); + throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() + + " on " + getLocalAddress() + ", cause: " + t.getMessage(), t); } executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class) .getDefaultExtension().get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); } - + protected abstract void doOpen() throws Throwable; - + protected abstract void doClose() throws Throwable; public void reset(URL url) { @@ -104,7 +104,7 @@ public void reset(URL url) { logger.error(t.getMessage(), t); } try { - if (url.hasParameter(Constants.THREADS_KEY) + if (url.hasParameter(Constants.THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int threads = url.getParameter(Constants.THREADS_KEY, 0); @@ -138,12 +138,12 @@ public void send(Object message, boolean sent) throws RemotingException { } } } - + public void close() { if (logger.isInfoEnabled()) { logger.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } - ExecutorUtil.shutdownNow(executor ,100); + ExecutorUtil.shutdownNow(executor, 100); try { super.close(); } catch (Throwable e) { @@ -155,16 +155,16 @@ public void close() { logger.warn(e.getMessage(), e); } } - + public void close(int timeout) { - ExecutorUtil.gracefulShutdown(executor ,timeout); + ExecutorUtil.gracefulShutdown(executor, timeout); close(); } public InetSocketAddress getLocalAddress() { return localAddress; } - + public InetSocketAddress getBindAddress() { return bindAddress; } @@ -187,14 +187,14 @@ public void connected(Channel ch) throws RemotingException { } super.connected(ch); } - + @Override public void disconnected(Channel ch) throws RemotingException { Collection channels = getChannels(); - if (channels.size() == 0){ + if (channels.size() == 0) { logger.warn("All clients has discontected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); } super.disconnected(ch); } - + } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 2e37611f934..39dcbbc7a3f 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -39,5 +39,16 @@ guava 19.0 + + com.netflix.hystrix + hystrix-core + 1.5.10 + + + + com.netflix.hystrix + hystrix-metrics-event-stream + 1.5.10 + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ActiveLimitFilter.java index c7d33a35494..bfe90cc830b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ActiveLimitFilter.java @@ -18,16 +18,11 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcStatus; +import com.alibaba.dubbo.rpc.*; /** * LimitInvokerFilter - * + * * @author william.liangf */ @Activate(group = Constants.CONSUMER, value = Constants.ACTIVES_KEY) @@ -44,20 +39,20 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept long remain = timeout; int active = count.getActive(); if (active >= max) { - synchronized (count) { + synchronized (this) { while ((active = count.getActive()) >= max) { try { count.wait(remain); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } long elapsed = System.currentTimeMillis() - start; remain = timeout - elapsed; if (remain <= 0) { throw new RpcException("Waiting concurrent invoke timeout in client-side for service: " - + invoker.getInterface().getName() + ", method: " - + invocation.getMethodName() + ", elapsed: " + elapsed - + ", timeout: " + timeout + ". concurrent invokes: " + active - + ". max concurrent invoke limit: " + max); + + invoker.getInterface().getName() + ", method: " + + invocation.getMethodName() + ", elapsed: " + elapsed + + ", timeout: " + timeout + ". concurrent invokes: " + active + + ". max concurrent invoke limit: " + max); } } } @@ -75,10 +70,10 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept throw t; } } finally { - if(max>0){ - synchronized (count) { + if (max > 0) { + synchronized (this) { count.notify(); - } + } } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java new file mode 100644 index 00000000000..ffac024c4e5 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java @@ -0,0 +1,60 @@ +package com.alibaba.dubbo.rpc.filter; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.rpc.*; +import com.netflix.hystrix.*; + +/** + * @author Xs + */ +@Activate(group = Constants.CONSUMER, value = "threads") +public class HystrixFilter implements Filter { + + @Override + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + return new DefaultCommand(invoker, invocation).execute(); + } + + private static class DefaultCommand extends HystrixCommand { + + private final Invoker invoker; + private final Invocation invocation; + + public DefaultCommand(Invoker invoker, Invocation invocation) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey(invoker))) + .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey(invoker, invocation))) + .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() + .withCircuitBreakerRequestVolumeThreshold(20) + .withCircuitBreakerSleepWindowInMilliseconds(30000) + .withCircuitBreakerErrorThresholdPercentage(50) + .withExecutionTimeoutEnabled(false)) + .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(threads(invoker)))); + this.invoker = invoker; + this.invocation = invocation; + } + + private static String groupKey(Invoker invoker) { + return invoker.getInterface().getName() + getVersion(invoker); + } + + private static String getVersion(Invoker invoker) { + return invoker.getUrl().getParameter("version", ""); + } + + private static String commandKey(Invoker invoker, Invocation invocation) { + return String.format("%s_%d", invoker.getInterface().getName() + invocation.getMethodName(), + invocation.getArguments() == null ? 0 : invocation.getArguments().length); + } + + private static int threads(Invoker invoker) { + return invoker.getUrl().getParameter("threads", 20); + } + + @Override + protected Result run() throws Exception { + return invoker.invoke(invocation); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java index 679cfbd5a6d..d1650a6d815 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/listener/ListenerInvokerWrapper.java @@ -72,7 +72,7 @@ public Result invoke(Invocation invocation) throws RpcException { @Override public String toString() { - return getInterface() + " -> " + getUrl() == null ? " " : getUrl().toString(); + return getUrl().toString(); } public void destroy() { From f28f3dddcbee64dbb7efcf493ef01d825f464e2d Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 21 May 2017 22:28:14 +0800 Subject: [PATCH 58/69] add threads attribute for HystrixFilter --- .../dubbo/config/AbstractMethodConfig.java | 10 +++++ .../dubbo/config/AbstractReferenceConfig.java | 42 +++++++++---------- .../src/main/resources/META-INF/dubbo.xsd | 5 +++ .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../dubbo/rpc/filter/HystrixFilter.java | 2 + 5 files changed, 39 insertions(+), 22 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java index 97292fad6b4..39350067137 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractMethodConfig.java @@ -40,6 +40,8 @@ public abstract class AbstractMethodConfig extends AbstractConfig { // 最大并发调用 protected Integer actives; + protected Integer threads; + // 负载均衡 protected String loadbalance; @@ -105,6 +107,14 @@ public void setActives(Integer actives) { this.actives = actives; } + public Integer getThreads() { + return threads; + } + + public void setThreads(Integer threads) { + this.threads = threads; + } + public Boolean getSent() { return sent; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractReferenceConfig.java index d7506d983ea..fcb47d284b2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractReferenceConfig.java @@ -23,44 +23,44 @@ /** * AbstractConsumerConfig - * - * @see com.alibaba.dubbo.config.ReferenceConfig + * * @author william.liangf * @export + * @see com.alibaba.dubbo.config.ReferenceConfig */ public abstract class AbstractReferenceConfig extends AbstractInterfaceConfig { private static final long serialVersionUID = -2786526984373031126L; // ======== 引用缺省值,当引用属性未设置时使用该缺省值替代 ======== - + // 检查服务提供者是否存在 - protected Boolean check; + protected Boolean check; // 是否加载时即刻初始化 - protected Boolean init; + protected Boolean init; // 是否使用泛接口 - protected String generic; + protected String generic; // 优先从JVM内获取引用实例 - protected Boolean injvm; - + protected Boolean injvm; + // lazy create connection - protected Boolean lazy; + protected Boolean lazy; + + protected String reconnect; + + protected Boolean sticky; - protected String reconnect; - - protected Boolean sticky; - //stub是否支持event事件. //TODO slove merge problem - protected Boolean stubevent ;//= Constants.DEFAULT_STUB_EVENT; + protected Boolean stubevent;//= Constants.DEFAULT_STUB_EVENT; // 版本 - protected String version; + protected String version; // 服务分组 - protected String group; + protected String group; public Boolean isCheck() { return check; @@ -105,12 +105,12 @@ public String getGeneric() { public Boolean isInjvm() { return injvm; } - + /** * @param injvm * @deprecated 通过scope设置,scope=local表示使用injvm协议. */ - @Deprecated + @Deprecated public void setInjvm(Boolean injvm) { this.injvm = injvm; } @@ -142,7 +142,7 @@ public void setLazy(Boolean lazy) { @Override public void setOnconnect(String onconnect) { - if (onconnect != null && onconnect.length() >0){ + if (onconnect != null && onconnect.length() > 0) { this.stubevent = true; } super.setOnconnect(onconnect); @@ -150,7 +150,7 @@ public void setOnconnect(String onconnect) { @Override public void setOndisconnect(String ondisconnect) { - if (ondisconnect != null && ondisconnect.length() >0){ + if (ondisconnect != null && ondisconnect.length() > 0) { this.stubevent = true; } super.setOndisconnect(ondisconnect); @@ -160,7 +160,7 @@ public void setOndisconnect(String ondisconnect) { public Boolean getStubevent() { return stubevent; } - + @Parameter(key = Constants.RECONNECT_KEY) public String getReconnect() { return reconnect; diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 001105e4d36..88899e6df91 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -30,6 +30,11 @@ + + + + + diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 403950ffc0c..e5f10e1046c 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java index ffac024c4e5..5c8ff5da4cf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/HystrixFilter.java @@ -6,6 +6,8 @@ import com.netflix.hystrix.*; /** + * for test now + * * @author Xs */ @Activate(group = Constants.CONSUMER, value = "threads") From 0ef50a1d1e4ed75b45dedcbeac84cab99cfa8443 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 22 May 2017 23:35:47 +0800 Subject: [PATCH 59/69] =?UTF-8?q?=E9=87=8D=E6=96=B0=E8=AE=BE=E8=AE=A1=20As?= =?UTF-8?q?yncCommand=20=E5=A2=9E=E5=8A=A0=20ListenableAsyncCommand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cluster/support/NotifyClusterInvoker.java | 53 ++++++++------ .../src/main/resources/META-INF/dubbo.xsd | 5 -- .../META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../com/alibaba/dubbo/rpc/AsyncCommand.java | 71 ------------------- .../alibaba/dubbo/rpc/AsyncInvocation.java | 11 --- .../com/alibaba/dubbo/rpc/AsyncRunnable.java | 8 --- .../alibaba/dubbo/rpc/async/AsyncCommand.java | 52 ++++++++++++++ .../dubbo/rpc/{ => async}/AsyncListener.java | 2 +- .../rpc/async/ListenableAsyncCommand.java | 34 +++++++++ .../rpc/proxy/AsyncableInvocationHandler.java | 15 ++-- 10 files changed, 123 insertions(+), 130 deletions(-) delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java rename dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/{ => async}/AsyncListener.java (76%) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index 4ecacf0e962..37d343a086d 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -2,7 +2,12 @@ import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.*; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.async.AsyncListener; +import com.alibaba.dubbo.rpc.async.ListenableAsyncCommand; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; @@ -31,9 +36,9 @@ private Result doInvokeAsync(final Invocation invocation, final List> final CountDownLatch latch = new CountDownLatch(invokers.size()); AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { - AsyncInvocation asyncInvocation = new AsyncInvocationImpl(invoker, invocation, latch); - AsyncCommand command = asyncInvocation.async(); - command.addListener(asyncInvocation).execute(); + AsyncInvocationCommand command = new AsyncInvocationCommand(invoker, invocation); + AsyncInvocation asyncInvocation = new AsyncInvocation(latch); + command.addListener(asyncInvocation).queue(); asyncResultProcessor.addAsyncInvocation(asyncInvocation); } try { @@ -49,33 +54,34 @@ private Result doInvokeAsync(final Invocation invocation, final List> } - private class AsyncInvocationImpl implements AsyncInvocation { + private class AsyncInvocationCommand extends ListenableAsyncCommand { private final Invoker invoker; private final Invocation invocation; - private final CountDownLatch latch; - - private Result reVal; - - private RpcException exception; - - public AsyncInvocationImpl(Invoker invoker, Invocation invocation, CountDownLatch latch) { + public AsyncInvocationCommand(Invoker invoker, Invocation invocation) { this.invoker = invoker; this.invocation = invocation; - this.latch = latch; - } - - @Override - public AsyncCommand async() { - return new AsyncCommand(this); } @Override public Result run() throws Exception { return doInvoke(invoker, invocation); } + } + + private class AsyncInvocation implements AsyncListener{ + + private final CountDownLatch latch; + + private Result reVal; + + private RpcException exception; + + private AsyncInvocation(CountDownLatch latch) { + this.latch = latch; + } @Override public void onSuccess(Result result) { @@ -106,33 +112,34 @@ public RpcException getException() { public Result getResult() { return reVal; } + } private class AsyncResultProcessor { - private final List asyncInvocations; + private final List asyncInvocation; private RpcException exception; private Result result; public AsyncResultProcessor(int size) { - asyncInvocations = new ArrayList(size); + asyncInvocation = new ArrayList(size); } public void addAsyncInvocation(AsyncInvocation asyncInvocation) { - asyncInvocations.add(asyncInvocation); + this.asyncInvocation.add(asyncInvocation); } public void processResult() { - for (AsyncInvocation invocation : asyncInvocations) { + for (AsyncInvocation invocation : asyncInvocation) { exception = invocation.getException(); if (exception != null) { break; } } if (exception == null) { - result = (Result) asyncInvocations.get(0).getResult(); + result = asyncInvocation.get(0).getResult(); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 88899e6df91..001105e4d36 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -30,11 +30,6 @@ - - - - - diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index e5f10e1046c..09959c11d9c 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -14,7 +14,7 @@ - + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java deleted file mode 100644 index 7109a61d149..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncCommand.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.alibaba.dubbo.rpc; - -import com.alibaba.dubbo.common.utils.Assert; -import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicReference; - -/** - * @author Xs - */ -public class AsyncCommand { - - private static final ListeningExecutorService asyncCommandExecutor = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); - - private final AsyncRunnable asyncRunnable; - - private final Set listeners = new HashSet(8); - - private final AtomicReference state = new AtomicReference(State.LATENT); - - private enum State { - LATENT, - STARTED, - FINISHED - } - - public AsyncCommand(AsyncRunnable asyncRunnable) { - Assert.notNull(asyncRunnable, "asyncTarget must not be null"); - this.asyncRunnable = asyncRunnable; - } - - public ListenableFuture execute() { - Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "command could be execute more than once"); - ListenableFuture future = asyncCommandExecutor.submit(new Callable() { - @Override - public T call() throws Exception { - try { - return asyncRunnable.run(); - } finally { - state.compareAndSet(State.STARTED, State.FINISHED); - } - } - }); - for (AsyncListener asyncListener : listeners) { - Futures.addCallback(future, asyncListener); - } - return future; - } - - public AsyncCommand addListener(AsyncListener listener) { - check(); - listeners.add(listener); - return this; - } - - private void check() { - if (state.get() != State.LATENT) { - throw new IllegalStateException("listener should be added before command started."); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java deleted file mode 100644 index b1b7dc7aba1..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncInvocation.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.alibaba.dubbo.rpc; - -/** - * @author Xs - */ -public interface AsyncInvocation extends AsyncRunnable, AsyncListener { - - RpcException getException(); - - T getResult(); -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java deleted file mode 100644 index 025b1a2aefa..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncRunnable.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.alibaba.dubbo.rpc; - -public interface AsyncRunnable { - - AsyncCommand async(); - - T run() throws Exception; -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java new file mode 100644 index 00000000000..95e5857155d --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java @@ -0,0 +1,52 @@ +package com.alibaba.dubbo.rpc.async; + +import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.google.common.base.Preconditions; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; + +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; + +/** + * @author Xs + */ +public abstract class AsyncCommand { + + protected static final ListeningExecutorService asyncCommandExecutor = + MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); + + protected final AtomicReference state = new AtomicReference(State.LATENT); + + protected enum State { + LATENT, + STARTED, + FINISHED + } + + public ListenableFuture execute() { + checkState(); + return submit(); + } + + protected void checkState(){ + Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "command could be execute more than once"); + } + + protected ListenableFuture submit() { + return asyncCommandExecutor.submit(new Callable() { + @Override + public T call() throws Exception { + try { + return run(); + } finally { + state.compareAndSet(State.STARTED, State.FINISHED); + } + } + }); + } + + public abstract T run() throws Exception; +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java similarity index 76% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java index 87f19daa90d..e9d55116950 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/AsyncListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java @@ -1,4 +1,4 @@ -package com.alibaba.dubbo.rpc; +package com.alibaba.dubbo.rpc.async; import com.google.common.util.concurrent.FutureCallback; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java new file mode 100644 index 00000000000..89101d45494 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java @@ -0,0 +1,34 @@ +package com.alibaba.dubbo.rpc.async; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * @author Xs + */ +public abstract class ListenableAsyncCommand extends AsyncCommand { + + private AsyncListener listener; + + public void queue() { + checkState(); + ListenableFuture future = submit(); + if (listener != null) { + Futures.addCallback(future, listener); + } + + } + + public ListenableAsyncCommand addListener(AsyncListener listener) { + check(); + this.listener = listener; + return this; + } + + + private void check() { + if (state.get() != State.LATENT) { + throw new IllegalStateException("listener should be added before command started."); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 681e1b33718..aae7c9be883 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -1,8 +1,7 @@ package com.alibaba.dubbo.rpc.proxy; -import com.alibaba.dubbo.rpc.AsyncCommand; -import com.alibaba.dubbo.rpc.AsyncRunnable; import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.async.AsyncCommand; import java.lang.reflect.Method; import java.util.concurrent.Future; @@ -17,8 +16,8 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (!isAsyncMethod(method)) { return super.invoke(proxy, method, args); } else { - AsyncRunnable asyncRunnable = new AsyncMethodWrapper(proxy, method, args); - return asyncRunnable.async().execute(); + AsyncMethodCommand command = new AsyncMethodCommand(proxy, method, args); + return command.execute(); } } @@ -30,7 +29,7 @@ private boolean isAsyncMethod(Method method) { /** * async method wrapper */ - class AsyncMethodWrapper implements AsyncRunnable { + class AsyncMethodCommand extends AsyncCommand { private final Object proxy; @@ -38,7 +37,7 @@ class AsyncMethodWrapper implements AsyncRunnable { private final Object[] args; - public AsyncMethodWrapper(Object proxy, Method wrapped, Object[] args) { + public AsyncMethodCommand(Object proxy, Method wrapped, Object[] args) { this.proxy = proxy; this.wrapped = wrapped; this.args = args; @@ -51,10 +50,6 @@ private Method getCorrespondingSyncMethod() throws Exception { return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); } - public AsyncCommand async() { - return new AsyncCommand(this); - } - @Override public Object run() throws Exception { return getCorrespondingSyncMethod().invoke(proxy, args); From 8d9a6fc2528b56251da26e959947620567633323 Mon Sep 17 00:00:00 2001 From: YanXs Date: Mon, 22 May 2017 23:39:40 +0800 Subject: [PATCH 60/69] NotifyClusterInvoker --- .../cluster/support/NotifyClusterInvoker.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index 37d343a086d..ab779353045 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -37,9 +37,9 @@ private Result doInvokeAsync(final Invocation invocation, final List> AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { AsyncInvocationCommand command = new AsyncInvocationCommand(invoker, invocation); - AsyncInvocation asyncInvocation = new AsyncInvocation(latch); - command.addListener(asyncInvocation).queue(); - asyncResultProcessor.addAsyncInvocation(asyncInvocation); + InvokerListener invokerListener = new InvokerListener(latch); + command.addListener(invokerListener).queue(); + asyncResultProcessor.addAsyncInvocation(invokerListener); } try { latch.await(); @@ -71,7 +71,7 @@ public Result run() throws Exception { } } - private class AsyncInvocation implements AsyncListener{ + private class InvokerListener implements AsyncListener{ private final CountDownLatch latch; @@ -79,7 +79,7 @@ private class AsyncInvocation implements AsyncListener{ private RpcException exception; - private AsyncInvocation(CountDownLatch latch) { + private InvokerListener(CountDownLatch latch) { this.latch = latch; } @@ -117,29 +117,29 @@ public Result getResult() { private class AsyncResultProcessor { - private final List asyncInvocation; + private final List invokerListener; private RpcException exception; private Result result; public AsyncResultProcessor(int size) { - asyncInvocation = new ArrayList(size); + invokerListener = new ArrayList(size); } - public void addAsyncInvocation(AsyncInvocation asyncInvocation) { - this.asyncInvocation.add(asyncInvocation); + public void addAsyncInvocation(InvokerListener invokerListener) { + this.invokerListener.add(invokerListener); } public void processResult() { - for (AsyncInvocation invocation : asyncInvocation) { + for (InvokerListener invocation : invokerListener) { exception = invocation.getException(); if (exception != null) { break; } } if (exception == null) { - result = asyncInvocation.get(0).getResult(); + result = invokerListener.get(0).getResult(); } } From 43be42f60540551ee0a16a7b4fe011e04f3e8dc6 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 23 May 2017 19:05:06 +0800 Subject: [PATCH 61/69] =?UTF-8?q?AsyncCommand=20ListenableAsyncCommand=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cluster/support/NotifyClusterInvoker.java | 14 ++++----- .../alibaba/dubbo/rpc/async/AsyncCommand.java | 29 ++++++++++--------- ...syncListener.java => CommandListener.java} | 2 +- .../rpc/async/ListenableAsyncCommand.java | 20 ++++++++----- .../rpc/proxy/AsyncableInvocationHandler.java | 4 +-- 5 files changed, 38 insertions(+), 31 deletions(-) rename dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/{AsyncListener.java => CommandListener.java} (60%) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index ab779353045..ac3b530b204 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -6,7 +6,7 @@ import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.async.AsyncListener; +import com.alibaba.dubbo.rpc.async.CommandListener; import com.alibaba.dubbo.rpc.async.ListenableAsyncCommand; import com.alibaba.dubbo.rpc.cluster.Directory; import com.alibaba.dubbo.rpc.cluster.LoadBalance; @@ -36,9 +36,9 @@ private Result doInvokeAsync(final Invocation invocation, final List> final CountDownLatch latch = new CountDownLatch(invokers.size()); AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { - AsyncInvocationCommand command = new AsyncInvocationCommand(invoker, invocation); + ListenableAsyncCommand command = new AsyncInvocationCommand(invoker, invocation); InvokerListener invokerListener = new InvokerListener(latch); - command.addListener(invokerListener).queue(); + command.addListener(invokerListener).submit(); asyncResultProcessor.addAsyncInvocation(invokerListener); } try { @@ -53,7 +53,6 @@ private Result doInvokeAsync(final Invocation invocation, final List> return asyncResultProcessor.getResult(); } - private class AsyncInvocationCommand extends ListenableAsyncCommand { private final Invoker invoker; @@ -71,7 +70,7 @@ public Result run() throws Exception { } } - private class InvokerListener implements AsyncListener{ + private class InvokerListener implements CommandListener { private final CountDownLatch latch; @@ -112,7 +111,6 @@ public RpcException getException() { public Result getResult() { return reVal; } - } private class AsyncResultProcessor { @@ -131,7 +129,7 @@ public void addAsyncInvocation(InvokerListener invokerListener) { this.invokerListener.add(invokerListener); } - public void processResult() { + void processResult() { for (InvokerListener invocation : invokerListener) { exception = invocation.getException(); if (exception != null) { @@ -150,6 +148,7 @@ public Result getResult() { public RpcException getException() { return exception; } + } private Result doInvoke(Invoker invoker, Invocation invocation) { @@ -169,4 +168,5 @@ private Result doInvoke(Invoker invoker, Invocation invocation) { } return result; } + } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java index 95e5857155d..3d8f7a2bc5e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java @@ -1,6 +1,7 @@ package com.alibaba.dubbo.rpc.async; import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.alibaba.dubbo.rpc.RpcException; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; @@ -15,27 +16,17 @@ */ public abstract class AsyncCommand { - protected static final ListeningExecutorService asyncCommandExecutor = + private static final ListeningExecutorService asyncCommandExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); protected final AtomicReference state = new AtomicReference(State.LATENT); protected enum State { - LATENT, - STARTED, - FINISHED + LATENT, STARTED, FINISHED } - public ListenableFuture execute() { + public ListenableFuture queue() { checkState(); - return submit(); - } - - protected void checkState(){ - Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "command could be execute more than once"); - } - - protected ListenableFuture submit() { return asyncCommandExecutor.submit(new Callable() { @Override public T call() throws Exception { @@ -48,5 +39,17 @@ public T call() throws Exception { }); } + public T execute() { + try { + return queue().get(); + } catch (Exception e) { + throw new RpcException(e); + } + } + + protected void checkState() { + Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "command could not be executed more than once"); + } + public abstract T run() throws Exception; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandListener.java similarity index 60% rename from dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandListener.java index e9d55116950..1eff64e97fb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandListener.java @@ -2,5 +2,5 @@ import com.google.common.util.concurrent.FutureCallback; -public interface AsyncListener extends FutureCallback { +public interface CommandListener extends FutureCallback { } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java index 89101d45494..9a6d3c7abbd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/ListenableAsyncCommand.java @@ -1,31 +1,35 @@ package com.alibaba.dubbo.rpc.async; +import com.alibaba.dubbo.common.utils.Assert; import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; /** * @author Xs */ public abstract class ListenableAsyncCommand extends AsyncCommand { - private AsyncListener listener; + private CommandListener listener; - public void queue() { - checkState(); - ListenableFuture future = submit(); + public void submit() { if (listener != null) { - Futures.addCallback(future, listener); + Futures.addCallback(queue(), listener); + } else { + throw new IllegalStateException("listener must not be null, you can use queue() instead"); } + } + public void submitWithListener(CommandListener listener) { + Assert.notNull(listener, "listener must be null"); + this.listener = listener; + this.submit(); } - public ListenableAsyncCommand addListener(AsyncListener listener) { + public ListenableAsyncCommand addListener(CommandListener listener) { check(); this.listener = listener; return this; } - private void check() { if (state.get() != State.LATENT) { throw new IllegalStateException("listener should be added before command started."); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index aae7c9be883..fb8b983055e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -16,8 +16,8 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg if (!isAsyncMethod(method)) { return super.invoke(proxy, method, args); } else { - AsyncMethodCommand command = new AsyncMethodCommand(proxy, method, args); - return command.execute(); + AsyncCommand command = new AsyncMethodCommand(proxy, method, args); + return command.queue(); } } From caeb633a292177671aae03dd114da00da95576a0 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 23 May 2017 21:30:32 +0800 Subject: [PATCH 62/69] add CommandExecutor CommandExecutorFactory --- .../alibaba/dubbo/rpc/async/AsyncCommand.java | 34 +++++++++++---- .../dubbo/rpc/async/CommandExecutor.java | 22 ++++++++++ .../rpc/async/CommandExecutorFactory.java | 41 +++++++++++++++++++ 3 files changed, 89 insertions(+), 8 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java index 3d8f7a2bc5e..4ac0db79828 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java @@ -1,14 +1,10 @@ package com.alibaba.dubbo.rpc.async; -import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.rpc.RpcException; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; import java.util.concurrent.Callable; -import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; /** @@ -16,8 +12,14 @@ */ public abstract class AsyncCommand { - private static final ListeningExecutorService asyncCommandExecutor = - MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(32, new NamedThreadFactory("asyncCommand", Boolean.TRUE))); + + public static final String COMMON_KEY = "common-command"; + + public static final int COMMON_CORE_SIZE = 64; + + public static final int UNKNOWN_CORE_SIZE = 10; + + private final CommandExecutor commandExecutor; protected final AtomicReference state = new AtomicReference(State.LATENT); @@ -25,9 +27,25 @@ protected enum State { LATENT, STARTED, FINISHED } + public AsyncCommand() { + this(COMMON_KEY, COMMON_CORE_SIZE); + } + + public AsyncCommand(String key) { + this(key, UNKNOWN_CORE_SIZE); + } + + public AsyncCommand(String key, int coreSize) { + commandExecutor = initExecutor(key, coreSize); + } + + private CommandExecutor initExecutor(String key, int coreSize) { + return CommandExecutorFactory.getCommandExecutor(key, coreSize); + } + public ListenableFuture queue() { checkState(); - return asyncCommandExecutor.submit(new Callable() { + return commandExecutor.executeCommand(new Callable() { @Override public T call() throws Exception { try { @@ -41,7 +59,7 @@ public T call() throws Exception { public T execute() { try { - return queue().get(); + return (T) queue().get(); } catch (Exception e) { throw new RpcException(e); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java new file mode 100644 index 00000000000..d1600266fef --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.rpc.async; + +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; + +import java.util.concurrent.Callable; + +/** + * @author Xs + */ +public class CommandExecutor { + + private final ListeningExecutorService commandExecutor; + + public CommandExecutor(ListeningExecutorService commandExecutor) { + this.commandExecutor = commandExecutor; + } + + public ListenableFuture executeCommand(Callable callable) { + return commandExecutor.submit(callable); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java new file mode 100644 index 00000000000..ac8f3a4badd --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java @@ -0,0 +1,41 @@ +package com.alibaba.dubbo.rpc.async; + +import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.google.common.util.concurrent.MoreExecutors; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; + +/** + * @author Xs + */ +public class CommandExecutorFactory { + + private static final Map threadPools = new ConcurrentHashMap(); + + @SuppressWarnings("unchecked") + public static CommandExecutor getCommandExecutor(String key, int coreSize) { + CommandExecutor previouslyCached = threadPools.get(key); + if (previouslyCached != null) { + return previouslyCached; + } + synchronized (CommandExecutorFactory.class) { + if (!threadPools.containsKey(key)) { + CommandExecutor commandExecutor = new CommandExecutor(MoreExecutors.listeningDecorator( + Executors.newFixedThreadPool(coreSize, + new NamedThreadFactory("asyncCommand", Boolean.TRUE)))); + threadPools.put(key, commandExecutor); + } + } + return threadPools.get(key); + } + + public static CommandExecutorFactory getInstance() { + return Holder.INSTANCE; + } + + public static class Holder { + public static CommandExecutorFactory INSTANCE = new CommandExecutorFactory(); + } +} From 2fa1c90e9980e0455ae688906533d9663c901894 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sat, 27 May 2017 20:37:40 +0800 Subject: [PATCH 63/69] LruCache --- .../alibaba/dubbo/cache/support/lru/LruCache.java | 14 +++++++------- .../com/alibaba/dubbo/rpc/async/AsyncCommand.java | 2 +- .../dubbo/rpc/protocol/ProtocolFilterWrapper.java | 1 - 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java index 33609dcc1e1..a6410f794a8 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java @@ -15,26 +15,26 @@ */ package com.alibaba.dubbo.cache.support.lru; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - import com.alibaba.dubbo.cache.Cache; import com.alibaba.dubbo.common.URL; +import java.util.LinkedHashMap; +import java.util.Map; + /** * LruCache - * + * * @author william.liangf */ public class LruCache implements Cache { - + private final Map store; public LruCache(URL url) { final int max = url.getParameter("cache.size", 1000); - this.store = new LinkedHashMap() { + this.store = new LinkedHashMap(16, 0.75f, true) { private static final long serialVersionUID = -3834209229668463829L; + @Override protected boolean removeEldestEntry(Entry eldest) { return size() > max; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java index 4ac0db79828..4ecacf62a75 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java @@ -59,7 +59,7 @@ public T call() throws Exception { public T execute() { try { - return (T) queue().get(); + return queue().get(); } catch (Exception e) { throw new RpcException(e); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ProtocolFilterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ProtocolFilterWrapper.java index ad760f5c380..df335bb3b8e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ProtocolFilterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ProtocolFilterWrapper.java @@ -104,5 +104,4 @@ public String toString() { } return last; } - } \ No newline at end of file From 162736c92b04d024a27206ed0e0280e2eac566a4 Mon Sep 17 00:00:00 2001 From: YanXs Date: Sun, 28 May 2017 12:59:01 +0800 Subject: [PATCH 64/69] add ByteBuddyProxyFactory --- .../dubbo/common/bytecode/Wrapper.java | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../dubbo/cache/support/lru/LruCache.java | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 6 ++ .../com/alibaba/dubbo/rpc/ProxyFactory.java | 6 +- .../bytebuddy/ByteBuddyProxyFactory.java | 80 +++++++++++++++++++ .../rpc/proxy/bytebuddy/MethodInclusion.java | 13 +++ .../ObjectMethodElementMatchers.java | 37 +++++++++ .../proxy/bytebuddy/ProxyClassBuilder.java | 40 ++++++++++ .../com.alibaba.dubbo.rpc.ProxyFactory | 3 +- 10 files changed, 184 insertions(+), 7 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java index 9e0be398458..ee0ca79bbd7 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java @@ -300,7 +300,7 @@ private static Wrapper makeWrapper(Class c) { Matcher matcher; for (Map.Entry entry : ms.entrySet()) { String md = entry.getKey(); - Method method = (Method) entry.getValue(); + Method method = entry.getValue(); if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index ccbb5a1d2df..21c7e792ddf 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -66,7 +66,7 @@ - diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java index a6410f794a8..e6e0cb0b851 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/com/alibaba/dubbo/cache/support/lru/LruCache.java @@ -36,7 +36,7 @@ public LruCache(URL url) { private static final long serialVersionUID = -3834209229668463829L; @Override - protected boolean removeEldestEntry(Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { return size() > max; } }; diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 39dcbbc7a3f..39f851fce98 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -50,5 +50,11 @@ hystrix-metrics-event-stream 1.5.10 + + + net.bytebuddy + byte-buddy + 1.6.9 + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java index 4369050a547..87f63f7e970 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java @@ -22,7 +22,7 @@ /** * ProxyFactory. (API/SPI, Singleton, ThreadSafe) - * + * * @author william.liangf */ @SPI("javassist") @@ -30,7 +30,7 @@ public interface ProxyFactory { /** * create proxy. - * + * * @param invoker * @return proxy */ @@ -39,7 +39,7 @@ public interface ProxyFactory { /** * create invoker. - * + * * @param * @param proxy * @param type diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java new file mode 100644 index 00000000000..780f5dddd20 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java @@ -0,0 +1,80 @@ +package com.alibaba.dubbo.rpc.proxy.bytebuddy; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; +import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; +import com.alibaba.dubbo.rpc.proxy.AsyncableInvocationHandler; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.SuperCall; +import net.bytebuddy.matcher.ElementMatcher; +import net.bytebuddy.matcher.ElementMatchers; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.concurrent.Callable; + +import static net.bytebuddy.matcher.ElementMatchers.not; + +/** + * @author Xs + */ +public class ByteBuddyProxyFactory extends AbstractProxyFactory { + + @Override + @SuppressWarnings("unchecked") + public T getProxy(Invoker invoker, Class[] interfaces) { + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + interfaces, new AsyncableInvocationHandler(invoker)); + } + + @Override + public Invoker getInvoker(T proxied, Class type, URL url) { + Class proxyClass = ProxyClassBuilder.build(proxied.getClass(), + proxied.getClass().getSimpleName(), ProxyMethodInclusion.INSTANCE, new ProxyInterceptor()); + final Object proxy = createNewInstance(proxyClass); + return new AbstractProxyInvoker(proxied, type, url) { + @Override + protected Object doInvoke(T proxied, String methodName, + Class[] parameterTypes, + Object[] arguments) throws Throwable { + Method method = proxy.getClass().getMethod(methodName, parameterTypes); + return method.invoke(proxy, arguments); + } + }; + } + + private Object createNewInstance(Class clazz) { + try { + return clazz.getConstructor().newInstance(); + } catch (Exception e) { + throw new RpcException(e); + } + } + + public class ProxyInterceptor { + + @RuntimeType + public Object intercept(@SuperCall Callable superMethod) { + try { + return superMethod.call(); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RpcException(e); + } + } + } + + public enum ProxyMethodInclusion implements MethodInclusion { + INSTANCE; + + @Override + public ElementMatcher getIncludes() { + return not(ElementMatchers.isPrivate() + .or(ObjectMethodElementMatchers.INSTANCE)); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java new file mode 100644 index 00000000000..162245923d1 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.rpc.proxy.bytebuddy; + +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +/** + * @author Xs. + */ +public interface MethodInclusion { + + ElementMatcher getIncludes(); + +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java new file mode 100644 index 00000000000..36a2f439b40 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java @@ -0,0 +1,37 @@ +package com.alibaba.dubbo.rpc.proxy.bytebuddy; + +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; +import net.bytebuddy.matcher.ElementMatchers; + +import static net.bytebuddy.matcher.ElementMatchers.named; +import static net.bytebuddy.matcher.ElementMatchers.takesArguments; + +/** + * @author Xs. + */ +public enum ObjectMethodElementMatchers implements ElementMatcher { + + INSTANCE; + + private final Junction matcher; + + ObjectMethodElementMatchers() { + matcher = ElementMatchers.named("getClass").and(takesArguments(0)) + .or(named("equals").and(takesArguments(Object.class))) + .or(named("hashCode").and(takesArguments(0))) + .or(named("wait").and(takesArguments(0))) + .or(named("wait").and(takesArguments(long.class))) + .or(named("wait").and(takesArguments(long.class, int.class))) + .or(named("toString").and(takesArguments(0))) + .or(named("clone").and(takesArguments(0))) + .or(named("notify").and(takesArguments(0))) + .or(named("notifyAll").and(takesArguments(0))) + .or(named("finalize").and(takesArguments(0))); + } + + @Override + public boolean matches(MethodDescription target) { + return matcher.matches(target); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java new file mode 100644 index 00000000000..b5cdabec420 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java @@ -0,0 +1,40 @@ +package com.alibaba.dubbo.rpc.proxy.bytebuddy; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.implementation.MethodDelegation; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * @author Xs. + */ +public class ProxyClassBuilder { + + private static final ConcurrentMap, Class> classCache = new ConcurrentHashMap, Class>(); + + private static final String DEFAULT_PREFIX = "BuddyProxy$"; + + public static Class build(Class origin, String name, MethodInclusion methodInclusion, Object interceptor) { + DynamicType.Builder builder = new ByteBuddy() + .subclass(origin).name(proxyClassName(name)); + Class cachedClass = classCache.get(origin); + if (cachedClass != null) { + return cachedClass; + } + Class proxied = builder + .method(methodInclusion.getIncludes()) + .intercept(MethodDelegation.to(interceptor)) + .make() + .load(Thread.currentThread().getContextClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); + classCache.putIfAbsent(origin, proxied); + return proxied; + } + + private static String proxyClassName(String name) { + return DEFAULT_PREFIX + name; + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory index d281b8a5645..b4417968df0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory +++ b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory @@ -1,3 +1,4 @@ stub=com.alibaba.dubbo.rpc.proxy.wrapper.StubProxyFactoryWrapper jdk=com.alibaba.dubbo.rpc.proxy.jdk.JdkProxyFactory -javassist=com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory \ No newline at end of file +javassist=com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory +bytebuddy=com.alibaba.dubbo.rpc.proxy.bytebuddy.ByteBuddyProxyFactory \ No newline at end of file From 7621ac1b2805416536eb7fec19cd502b14fc46b5 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 31 May 2017 17:12:46 +0800 Subject: [PATCH 65/69] drop ByteBuddyProxyFactory , udpate AsyncableInvocationHandler JdkProxyFactory --- .../rpc/proxy/AsyncableInvocationHandler.java | 30 ++++++- .../bytebuddy/ByteBuddyProxyFactory.java | 80 ------------------- .../rpc/proxy/bytebuddy/MethodInclusion.java | 13 --- .../ObjectMethodElementMatchers.java | 37 --------- .../proxy/bytebuddy/ProxyClassBuilder.java | 40 ---------- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 47 ++++++++--- 6 files changed, 66 insertions(+), 181 deletions(-) delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index fb8b983055e..1c7b47ad644 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -4,6 +4,9 @@ import com.alibaba.dubbo.rpc.async.AsyncCommand; import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; public class AsyncableInvocationHandler extends InvokerInvocationHandler { @@ -29,7 +32,9 @@ private boolean isAsyncMethod(Method method) { /** * async method wrapper */ - class AsyncMethodCommand extends AsyncCommand { + static class AsyncMethodCommand extends AsyncCommand { + + static Map cachedMethods = new ConcurrentHashMap(128); private final Object proxy; @@ -47,7 +52,28 @@ private Method getCorrespondingSyncMethod() throws Exception { String methodName = wrapped.getName(); Class[] parameterTypes = wrapped.getParameterTypes(); String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - return proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); + String methodKey = methodKey(syncMethodName, parameterTypes); + Method previouslyCached = cachedMethods.get(methodKey); + if (previouslyCached != null) { + return previouslyCached; + } + synchronized (AsyncMethodCommand.class) { + if (!cachedMethods.containsKey(methodKey)) { + Method method = proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); + cachedMethods.put(methodKey, method); + } + } + return cachedMethods.get(methodKey); + } + + private String methodKey(String methodName, Class[] parameterTypes) { + StringBuilder builder = new StringBuilder(methodName); + if (parameterTypes != null && parameterTypes.length > 0) { + for (Class clz : parameterTypes) { + builder.append(clz.getName()); + } + } + return builder.toString(); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java deleted file mode 100644 index 780f5dddd20..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.alibaba.dubbo.rpc.proxy.bytebuddy; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; -import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; -import com.alibaba.dubbo.rpc.proxy.AsyncableInvocationHandler; -import net.bytebuddy.description.method.MethodDescription; -import net.bytebuddy.implementation.bind.annotation.RuntimeType; -import net.bytebuddy.implementation.bind.annotation.SuperCall; -import net.bytebuddy.matcher.ElementMatcher; -import net.bytebuddy.matcher.ElementMatchers; - -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.concurrent.Callable; - -import static net.bytebuddy.matcher.ElementMatchers.not; - -/** - * @author Xs - */ -public class ByteBuddyProxyFactory extends AbstractProxyFactory { - - @Override - @SuppressWarnings("unchecked") - public T getProxy(Invoker invoker, Class[] interfaces) { - return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), - interfaces, new AsyncableInvocationHandler(invoker)); - } - - @Override - public Invoker getInvoker(T proxied, Class type, URL url) { - Class proxyClass = ProxyClassBuilder.build(proxied.getClass(), - proxied.getClass().getSimpleName(), ProxyMethodInclusion.INSTANCE, new ProxyInterceptor()); - final Object proxy = createNewInstance(proxyClass); - return new AbstractProxyInvoker(proxied, type, url) { - @Override - protected Object doInvoke(T proxied, String methodName, - Class[] parameterTypes, - Object[] arguments) throws Throwable { - Method method = proxy.getClass().getMethod(methodName, parameterTypes); - return method.invoke(proxy, arguments); - } - }; - } - - private Object createNewInstance(Class clazz) { - try { - return clazz.getConstructor().newInstance(); - } catch (Exception e) { - throw new RpcException(e); - } - } - - public class ProxyInterceptor { - - @RuntimeType - public Object intercept(@SuperCall Callable superMethod) { - try { - return superMethod.call(); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RpcException(e); - } - } - } - - public enum ProxyMethodInclusion implements MethodInclusion { - INSTANCE; - - @Override - public ElementMatcher getIncludes() { - return not(ElementMatchers.isPrivate() - .or(ObjectMethodElementMatchers.INSTANCE)); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java deleted file mode 100644 index 162245923d1..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/MethodInclusion.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.alibaba.dubbo.rpc.proxy.bytebuddy; - -import net.bytebuddy.description.method.MethodDescription; -import net.bytebuddy.matcher.ElementMatcher; - -/** - * @author Xs. - */ -public interface MethodInclusion { - - ElementMatcher getIncludes(); - -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java deleted file mode 100644 index 36a2f439b40..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ObjectMethodElementMatchers.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.alibaba.dubbo.rpc.proxy.bytebuddy; - -import net.bytebuddy.description.method.MethodDescription; -import net.bytebuddy.matcher.ElementMatcher; -import net.bytebuddy.matcher.ElementMatchers; - -import static net.bytebuddy.matcher.ElementMatchers.named; -import static net.bytebuddy.matcher.ElementMatchers.takesArguments; - -/** - * @author Xs. - */ -public enum ObjectMethodElementMatchers implements ElementMatcher { - - INSTANCE; - - private final Junction matcher; - - ObjectMethodElementMatchers() { - matcher = ElementMatchers.named("getClass").and(takesArguments(0)) - .or(named("equals").and(takesArguments(Object.class))) - .or(named("hashCode").and(takesArguments(0))) - .or(named("wait").and(takesArguments(0))) - .or(named("wait").and(takesArguments(long.class))) - .or(named("wait").and(takesArguments(long.class, int.class))) - .or(named("toString").and(takesArguments(0))) - .or(named("clone").and(takesArguments(0))) - .or(named("notify").and(takesArguments(0))) - .or(named("notifyAll").and(takesArguments(0))) - .or(named("finalize").and(takesArguments(0))); - } - - @Override - public boolean matches(MethodDescription target) { - return matcher.matches(target); - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java deleted file mode 100644 index b5cdabec420..00000000000 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/bytebuddy/ProxyClassBuilder.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.alibaba.dubbo.rpc.proxy.bytebuddy; - -import net.bytebuddy.ByteBuddy; -import net.bytebuddy.dynamic.DynamicType; -import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; -import net.bytebuddy.implementation.MethodDelegation; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @author Xs. - */ -public class ProxyClassBuilder { - - private static final ConcurrentMap, Class> classCache = new ConcurrentHashMap, Class>(); - - private static final String DEFAULT_PREFIX = "BuddyProxy$"; - - public static Class build(Class origin, String name, MethodInclusion methodInclusion, Object interceptor) { - DynamicType.Builder builder = new ByteBuddy() - .subclass(origin).name(proxyClassName(name)); - Class cachedClass = classCache.get(origin); - if (cachedClass != null) { - return cachedClass; - } - Class proxied = builder - .method(methodInclusion.getIncludes()) - .intercept(MethodDelegation.to(interceptor)) - .make() - .load(Thread.currentThread().getContextClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); - classCache.putIfAbsent(origin, proxied); - return proxied; - } - - private static String proxyClassName(String name) { - return DEFAULT_PREFIX + name; - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index 01d82e83eb0..c7ba4eb16fa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -23,6 +23,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * JavaassistRpcProxyFactory @@ -38,15 +40,42 @@ public T getProxy(Invoker invoker, Class[] interfaces) { } public Invoker getInvoker(T proxy, Class type, URL url) { - return new AbstractProxyInvoker(proxy, type, url) { - @Override - protected Object doInvoke(T proxy, String methodName, - Class[] parameterTypes, - Object[] arguments) throws Throwable { - Method method = proxy.getClass().getMethod(methodName, parameterTypes); - return method.invoke(proxy, arguments); - } - }; + return new CachedProxyInvoker(proxy, type, url); } + static class CachedProxyInvoker extends AbstractProxyInvoker { + + static Map cachedMethods = new ConcurrentHashMap(128); + + public CachedProxyInvoker(T proxy, Class type, URL url) { + super(proxy, type, url); + } + + @Override + protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { + String methodKey = methodKey(methodName, parameterTypes); + Method previouslyCached = cachedMethods.get(methodKey); + if (previouslyCached != null) { + return previouslyCached; + } + synchronized (CachedProxyInvoker.class) { + if (!cachedMethods.containsKey(methodKey)) { + Method method = proxy.getClass().getDeclaredMethod(methodName, parameterTypes); + cachedMethods.put(methodKey, method); + } + } + return cachedMethods.get(methodKey).invoke(proxy, arguments); + } + + + private String methodKey(String methodName, Class[] parameterTypes) { + StringBuilder builder = new StringBuilder(methodName); + if (parameterTypes != null && parameterTypes.length > 0) { + for (Class clz : parameterTypes) { + builder.append(clz.getName()); + } + } + return builder.toString(); + } + } } \ No newline at end of file From 6142f2618080d14f5d3989798f41e8b52e6c0d56 Mon Sep 17 00:00:00 2001 From: YanXs Date: Thu, 1 Jun 2017 17:09:52 +0800 Subject: [PATCH 66/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20AsyncCommand=20READM?= =?UTF-8?q?E.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ .../common/compiler/support/JdkCompiler.java | 4 ++-- .../META-INF/spring/dubbo-demo-provider.xml | 2 +- .../alibaba/dubbo/rpc/async/AsyncCommand.java | 16 ++++------------ .../dubbo/rpc/async/CommandExecutor.java | 18 +++++++++++++++--- .../rpc/async/CommandExecutorFactory.java | 5 +++-- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 4 ++-- .../com.alibaba.dubbo.rpc.ProxyFactory | 3 +-- 8 files changed, 33 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 9bad619584f..3360449a65f 100644 --- a/README.md +++ b/README.md @@ -36,12 +36,17 @@ dubbo3中异步实现思路是为同步接口生成对应的异步接口,consu 在客户端的代理InvocationHandler中调用同步接口, 具体实现参考AsyncableInvocationHandler origin interface: ```java +@AutoAsync public interface SimpleService { + @Asyncable Complex getComplex(String id); } ``` async interface:(使用auto-async自动生成) ```java +@AutoGenerated( + value = "net.auto.async.processor.AutoAsyncProcessor" +) public interface Unified_SimpleService extends SimpleService { ListenableFuture async_getComplex(String id); } diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JdkCompiler.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JdkCompiler.java index 5f6bcfcef88..f8754114686 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JdkCompiler.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JdkCompiler.java @@ -103,8 +103,8 @@ public Class doCompile(String name, String sourceCode) throws Throwable { javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, className + ClassUtils.JAVA_EXTENSION, javaFileObject); Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options, - null, Arrays.asList(new JavaFileObject[]{javaFileObject})).call(); - if (result == null || ! result.booleanValue()) { + null, Collections.singletonList(javaFileObject)).call(); + if (result == null || !result) { throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector); } return classLoader.loadClass(name); diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 21c7e792ddf..ccbb5a1d2df 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -66,7 +66,7 @@ - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java index 4ecacf62a75..14614dc436d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/AsyncCommand.java @@ -4,7 +4,6 @@ import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; /** @@ -21,6 +20,8 @@ public abstract class AsyncCommand { private final CommandExecutor commandExecutor; + private final CommandExecutorFactory factory = CommandExecutorFactory.getInstance(); + protected final AtomicReference state = new AtomicReference(State.LATENT); protected enum State { @@ -40,21 +41,12 @@ public AsyncCommand(String key, int coreSize) { } private CommandExecutor initExecutor(String key, int coreSize) { - return CommandExecutorFactory.getCommandExecutor(key, coreSize); + return factory.getCommandExecutor(key, coreSize); } public ListenableFuture queue() { checkState(); - return commandExecutor.executeCommand(new Callable() { - @Override - public T call() throws Exception { - try { - return run(); - } finally { - state.compareAndSet(State.STARTED, State.FINISHED); - } - } - }); + return commandExecutor.execute(this); } public T execute() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java index d1600266fef..61047858e78 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutor.java @@ -3,12 +3,13 @@ import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; +import java.io.Closeable; import java.util.concurrent.Callable; /** * @author Xs */ -public class CommandExecutor { +public class CommandExecutor implements Closeable { private final ListeningExecutorService commandExecutor; @@ -16,7 +17,18 @@ public CommandExecutor(ListeningExecutorService commandExecutor) { this.commandExecutor = commandExecutor; } - public ListenableFuture executeCommand(Callable callable) { - return commandExecutor.submit(callable); + public ListenableFuture execute(final AsyncCommand command) { + return commandExecutor.submit(new Callable() { + @Override + public T call() throws Exception { + return command.run(); + } + }); + } + + public void close() { + if (commandExecutor != null) { + commandExecutor.shutdown(); + } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java index ac8f3a4badd..edfba1504ff 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/async/CommandExecutorFactory.java @@ -15,7 +15,8 @@ public class CommandExecutorFactory { private static final Map threadPools = new ConcurrentHashMap(); @SuppressWarnings("unchecked") - public static CommandExecutor getCommandExecutor(String key, int coreSize) { + public CommandExecutor getCommandExecutor(String key, int coreSize) { + CommandExecutor previouslyCached = threadPools.get(key); if (previouslyCached != null) { return previouslyCached; @@ -35,7 +36,7 @@ public static CommandExecutorFactory getInstance() { return Holder.INSTANCE; } - public static class Holder { + private static class Holder { public static CommandExecutorFactory INSTANCE = new CommandExecutorFactory(); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index c7ba4eb16fa..bdf9ea43474 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -27,7 +27,7 @@ import java.util.concurrent.ConcurrentHashMap; /** - * JavaassistRpcProxyFactory + * JdkProxyFactory * * @author william.liangf */ @@ -43,7 +43,7 @@ public Invoker getInvoker(T proxy, Class type, URL url) { return new CachedProxyInvoker(proxy, type, url); } - static class CachedProxyInvoker extends AbstractProxyInvoker { + private static class CachedProxyInvoker extends AbstractProxyInvoker { static Map cachedMethods = new ConcurrentHashMap(128); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory index b4417968df0..d281b8a5645 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory +++ b/dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory @@ -1,4 +1,3 @@ stub=com.alibaba.dubbo.rpc.proxy.wrapper.StubProxyFactoryWrapper jdk=com.alibaba.dubbo.rpc.proxy.jdk.JdkProxyFactory -javassist=com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory -bytebuddy=com.alibaba.dubbo.rpc.proxy.bytebuddy.ByteBuddyProxyFactory \ No newline at end of file +javassist=com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory \ No newline at end of file From d11d1bdd1b47a6d116ba444c35c0a7b1b07a6095 Mon Sep 17 00:00:00 2001 From: YanXs Date: Tue, 6 Jun 2017 18:42:36 +0800 Subject: [PATCH 67/69] add MethodCache --- .../cluster/support/NotifyClusterInvoker.java | 28 ++++++------ .../dubbo/common/utils/MethodCache.java | 44 +++++++++++++++++++ .../rpc/proxy/AsyncableInvocationHandler.java | 29 ++---------- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 29 ++---------- 4 files changed, 64 insertions(+), 66 deletions(-) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java index ac3b530b204..95574791d90 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/NotifyClusterInvoker.java @@ -32,14 +32,14 @@ public Result doInvoke(final Invocation invocation, List> invokers, L return doInvokeAsync(invocation, invokers); } - private Result doInvokeAsync(final Invocation invocation, final List> invokers) { - final CountDownLatch latch = new CountDownLatch(invokers.size()); + private Result doInvokeAsync(final Invocation invocation, List> invokers) { + CountDownLatch latch = new CountDownLatch(invokers.size()); AsyncResultProcessor asyncResultProcessor = new AsyncResultProcessor(invokers.size()); for (final Invoker invoker : invokers) { ListenableAsyncCommand command = new AsyncInvocationCommand(invoker, invocation); - InvokerListener invokerListener = new InvokerListener(latch); - command.addListener(invokerListener).submit(); - asyncResultProcessor.addAsyncInvocation(invokerListener); + AsyncResult result = new AsyncResult(latch); + command.addListener(result).submit(); + asyncResultProcessor.addAsyncResult(result); } try { latch.await(); @@ -70,7 +70,7 @@ public Result run() throws Exception { } } - private class InvokerListener implements CommandListener { + private class AsyncResult implements CommandListener { private final CountDownLatch latch; @@ -78,7 +78,7 @@ private class InvokerListener implements CommandListener { private RpcException exception; - private InvokerListener(CountDownLatch latch) { + private AsyncResult(CountDownLatch latch) { this.latch = latch; } @@ -115,29 +115,29 @@ public Result getResult() { private class AsyncResultProcessor { - private final List invokerListener; + private final List asyncResult; private RpcException exception; private Result result; public AsyncResultProcessor(int size) { - invokerListener = new ArrayList(size); + asyncResult = new ArrayList(size); } - public void addAsyncInvocation(InvokerListener invokerListener) { - this.invokerListener.add(invokerListener); + public void addAsyncResult(AsyncResult asyncResult) { + this.asyncResult.add(asyncResult); } void processResult() { - for (InvokerListener invocation : invokerListener) { + for (AsyncResult invocation : asyncResult) { exception = invocation.getException(); if (exception != null) { break; } } if (exception == null) { - result = invokerListener.get(0).getResult(); + result = asyncResult.get(0).getResult(); } } @@ -148,7 +148,6 @@ public Result getResult() { public RpcException getException() { return exception; } - } private Result doInvoke(Invoker invoker, Invocation invocation) { @@ -168,5 +167,4 @@ private Result doInvoke(Invoker invoker, Invocation invocation) { } return result; } - } diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java new file mode 100644 index 00000000000..2cd0aa91a8e --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java @@ -0,0 +1,44 @@ +package com.alibaba.dubbo.common.utils; + +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class MethodCache { + + private final Map cachedMethods = new ConcurrentHashMap(32); + + private final Object lock = new Object(); + + private MethodCache() { + } + + public static MethodCache newCache() { + return new MethodCache(); + } + + private String methodKey(String methodName, Class[] parameterTypes) { + StringBuilder builder = new StringBuilder(methodName); + if (parameterTypes != null && parameterTypes.length > 0) { + for (Class clz : parameterTypes) { + builder.append(clz.getName()); + } + } + return builder.toString(); + } + + public Method get(Object object, String methodName, Class[] parameterTypes) throws Exception { + String methodKey = methodKey(methodName, parameterTypes); + Method previouslyCached = cachedMethods.get(methodKey); + if (previouslyCached != null) { + return previouslyCached; + } + synchronized (lock) { + if (!cachedMethods.containsKey(methodKey)) { + Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes); + cachedMethods.put(methodKey, method); + } + } + return cachedMethods.get(methodKey); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 1c7b47ad644..85e4186e5f8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -1,12 +1,10 @@ package com.alibaba.dubbo.rpc.proxy; +import com.alibaba.dubbo.common.utils.MethodCache; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.async.AsyncCommand; import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; public class AsyncableInvocationHandler extends InvokerInvocationHandler { @@ -34,7 +32,7 @@ private boolean isAsyncMethod(Method method) { */ static class AsyncMethodCommand extends AsyncCommand { - static Map cachedMethods = new ConcurrentHashMap(128); + private static final MethodCache methodCache = MethodCache.newCache(); private final Object proxy; @@ -52,28 +50,7 @@ private Method getCorrespondingSyncMethod() throws Exception { String methodName = wrapped.getName(); Class[] parameterTypes = wrapped.getParameterTypes(); String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - String methodKey = methodKey(syncMethodName, parameterTypes); - Method previouslyCached = cachedMethods.get(methodKey); - if (previouslyCached != null) { - return previouslyCached; - } - synchronized (AsyncMethodCommand.class) { - if (!cachedMethods.containsKey(methodKey)) { - Method method = proxy.getClass().getDeclaredMethod(syncMethodName, parameterTypes); - cachedMethods.put(methodKey, method); - } - } - return cachedMethods.get(methodKey); - } - - private String methodKey(String methodName, Class[] parameterTypes) { - StringBuilder builder = new StringBuilder(methodName); - if (parameterTypes != null && parameterTypes.length > 0) { - for (Class clz : parameterTypes) { - builder.append(clz.getName()); - } - } - return builder.toString(); + return methodCache.get(wrapped, syncMethodName, parameterTypes); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index bdf9ea43474..0955d52806f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -16,6 +16,7 @@ package com.alibaba.dubbo.rpc.proxy.jdk; import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.MethodCache; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.proxy.AbstractProxyFactory; import com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker; @@ -43,9 +44,9 @@ public Invoker getInvoker(T proxy, Class type, URL url) { return new CachedProxyInvoker(proxy, type, url); } - private static class CachedProxyInvoker extends AbstractProxyInvoker { + static class CachedProxyInvoker extends AbstractProxyInvoker { - static Map cachedMethods = new ConcurrentHashMap(128); + private final static MethodCache methodCache = MethodCache.newCache(); public CachedProxyInvoker(T proxy, Class type, URL url) { super(proxy, type, url); @@ -53,29 +54,7 @@ public CachedProxyInvoker(T proxy, Class type, URL url) { @Override protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { - String methodKey = methodKey(methodName, parameterTypes); - Method previouslyCached = cachedMethods.get(methodKey); - if (previouslyCached != null) { - return previouslyCached; - } - synchronized (CachedProxyInvoker.class) { - if (!cachedMethods.containsKey(methodKey)) { - Method method = proxy.getClass().getDeclaredMethod(methodName, parameterTypes); - cachedMethods.put(methodKey, method); - } - } - return cachedMethods.get(methodKey).invoke(proxy, arguments); - } - - - private String methodKey(String methodName, Class[] parameterTypes) { - StringBuilder builder = new StringBuilder(methodName); - if (parameterTypes != null && parameterTypes.length > 0) { - for (Class clz : parameterTypes) { - builder.append(clz.getName()); - } - } - return builder.toString(); + return methodCache.get(proxy, methodName, parameterTypes); } } } \ No newline at end of file From aadd1aefa1288b450751a552044f3b8ad27734ce Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 7 Jun 2017 20:39:21 +0800 Subject: [PATCH 68/69] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20MethodCache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/common/utils/MethodCache.java | 19 +- .../dubbo/common/utils/StringUtils.java | 564 +++++++++--------- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 1 - .../rpc/proxy/AsyncableInvocationHandler.java | 33 +- 4 files changed, 299 insertions(+), 318 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java index 2cd0aa91a8e..c510c1ba9ed 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java @@ -1,12 +1,13 @@ package com.alibaba.dubbo.common.utils; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class MethodCache { - private final Map cachedMethods = new ConcurrentHashMap(32); + private final Map cachedMethods = new ConcurrentHashMap(32); private final Object lock = new Object(); @@ -17,18 +18,16 @@ public static MethodCache newCache() { return new MethodCache(); } - private String methodKey(String methodName, Class[] parameterTypes) { - StringBuilder builder = new StringBuilder(methodName); - if (parameterTypes != null && parameterTypes.length > 0) { - for (Class clz : parameterTypes) { - builder.append(clz.getName()); - } - } - return builder.toString(); + private Integer methodKey(Object object, String methodName, Class[] parameterTypes) { + return methodName.hashCode() + Arrays.hashCode(parameterTypes) + object.hashCode(); } public Method get(Object object, String methodName, Class[] parameterTypes) throws Exception { - String methodKey = methodKey(methodName, parameterTypes); + Assert.notNull(object, "object must not be null!"); + if (StringUtils.isEmpty(methodName)) { + throw new IllegalArgumentException("methodName must not be null or empty"); + } + Integer methodKey = methodKey(object, methodName, parameterTypes); Method previouslyCached = cachedMethods.get(methodKey); if (previouslyCached != null) { return previouslyCached; diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java index ead6a8adfea..4412dc62c67 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/StringUtils.java @@ -15,26 +15,21 @@ */ package com.alibaba.dubbo.common.utils; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.io.UnsafeStringWriter; import com.alibaba.dubbo.common.json.JSON; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * StringUtils - * + * * @author qian.lei */ @@ -42,45 +37,41 @@ public final class StringUtils { private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); - public static final String[] EMPTY_STRING_ARRAY = new String[0]; - - private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); //key value pair pattern. - - private static final Pattern INT_PATTERN = Pattern.compile("^\\d+$"); - - public static boolean isBlank(String str) - { - if( str == null || str.length() == 0 ) - return true; - return false; - } - - /** - * is empty string. - * - * @param str source string. - * @return is empty. - */ - public static boolean isEmpty(String str) - { - if( str == null || str.length() == 0 ) - return true; - return false; - } - - /** - * is not empty string. - * - * @param str source string. - * @return is not empty. - */ - public static boolean isNotEmpty(String str) - { + public static final String[] EMPTY_STRING_ARRAY = new String[0]; + + private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); //key value pair pattern. + + private static final Pattern INT_PATTERN = Pattern.compile("^\\d+$"); + + public static boolean isBlank(String str) { + if (str == null || str.length() == 0) + return true; + return false; + } + + /** + * is empty string. + * + * @param str source string. + * @return is empty. + */ + public static boolean isEmpty(String str) { + if (str == null || str.length() == 0) + return true; + return false; + } + + /** + * is not empty string. + * + * @param str source string. + * @return is not empty. + */ + public static boolean isNotEmpty(String str) { return str != null && str.length() > 0; } - + /** - * * @param s1 * @param s2 * @return equals @@ -92,22 +83,22 @@ public static boolean isEquals(String s1, String s2) { return false; return s1.equals(s2); } - + /** * is integer string. - * + * * @param str * @return is integer */ public static boolean isInteger(String str) { - if (str == null || str.length() == 0) - return false; + if (str == null || str.length() == 0) + return false; return INT_PATTERN.matcher(str).matches(); } - + public static int parseInteger(String str) { - if (! isInteger(str)) - return 0; + if (!isInteger(str)) + return 0; return Integer.parseInt(str); } @@ -119,23 +110,22 @@ public static boolean isJavaIdentifier(String s) { if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } - for (int i=1; i list = null; + /** + * translat. + * + * @param src source string. + * @param from src char table. + * @param to target char table. + * @return String. + */ + public static String translat(String src, String from, String to) { + if (isEmpty(src)) return src; + StringBuilder sb = null; + int ix; + char c; + for (int i = 0, len = src.length(); i < len; i++) { + c = src.charAt(i); + ix = from.indexOf(c); + if (ix == -1) { + if (sb != null) + sb.append(c); + } else { + if (sb == null) { + sb = new StringBuilder(len); + sb.append(src, 0, i); + } + if (ix < to.length()) + sb.append(to.charAt(ix)); + } + } + return sb == null ? src : sb.toString(); + } + + /** + * split. + * + * @param ch char. + * @return string array. + */ + public static String[] split(String str, char ch) { + List list = null; char c; - int ix = 0,len=str.length(); - for(int i=0;i(); - list.add(str.substring(ix, i)); - ix = i + 1; - } - } - if( ix > 0 ) - list.add(str.substring(ix)); - return list == null ? EMPTY_STRING_ARRAY : (String[])list.toArray(EMPTY_STRING_ARRAY); - } - - /** - * join string. - * - * @param array String array. - * @return String. - */ - public static String join(String[] array) - { - if( array.length == 0 ) return ""; - StringBuilder sb = new StringBuilder(); - for( String s : array ) - sb.append(s); - return sb.toString(); - } - - /** - * join string like javascript. - * - * @param array String array. - * @param split split - * @return String. - */ - public static String join(String[] array, char split) - { - if( array.length == 0 ) return ""; - StringBuilder sb = new StringBuilder(); - for(int i=0;i 0 ) - sb.append(split); - sb.append(array[i]); - } - return sb.toString(); - } - - /** - * join string like javascript. - * - * @param array String array. - * @param split split - * @return String. - */ - public static String join(String[] array, String split) - { - if( array.length == 0 ) return ""; - StringBuilder sb = new StringBuilder(); - for(int i=0;i 0 ) - sb.append(split); - sb.append(array[i]); - } - return sb.toString(); - } - - public static String join(Collection coll, String split) { - if(coll.isEmpty()) return ""; - - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - for(String s : coll) { - if(isFirst) isFirst = false; else sb.append(split); - sb.append(s); - } - return sb.toString(); - } - - /** - * parse key-value pair. - * - * @param str string. - * @param itemSeparator item separator. - * @return key-value map; - */ - private static Map parseKeyValuePair(String str, String itemSeparator) - { - String[] tmp = str.split(itemSeparator); - Map map = new HashMap(tmp.length); - for (String aTmp : tmp) { - Matcher matcher = KVP_PATTERN.matcher(aTmp); - if (!matcher.matches()) - continue; - map.put(matcher.group(1), matcher.group(2)); - } - return map; - } - - public static String getQueryStringValue(String qs, String key) { - Map map = StringUtils.parseQueryString(qs); - return map.get(key); - } - - /** + int ix = 0, len = str.length(); + for (int i = 0; i < len; i++) { + c = str.charAt(i); + if (c == ch) { + if (list == null) + list = new ArrayList(); + list.add(str.substring(ix, i)); + ix = i + 1; + } + } + if (ix > 0) + list.add(str.substring(ix)); + return list == null ? EMPTY_STRING_ARRAY : (String[]) list.toArray(EMPTY_STRING_ARRAY); + } + + /** + * join string. + * + * @param array String array. + * @return String. + */ + public static String join(String[] array) { + if (array.length == 0) return ""; + StringBuilder sb = new StringBuilder(); + for (String s : array) + sb.append(s); + return sb.toString(); + } + + /** + * join string like javascript. + * + * @param array String array. + * @param split split + * @return String. + */ + public static String join(String[] array, char split) { + if (array.length == 0) return ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + if (i > 0) + sb.append(split); + sb.append(array[i]); + } + return sb.toString(); + } + + /** + * join string like javascript. + * + * @param array String array. + * @param split split + * @return String. + */ + public static String join(String[] array, String split) { + if (array.length == 0) return ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < array.length; i++) { + if (i > 0) + sb.append(split); + sb.append(array[i]); + } + return sb.toString(); + } + + public static String join(Collection coll, String split) { + if (coll.isEmpty()) return ""; + + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + for (String s : coll) { + if (isFirst) isFirst = false; + else sb.append(split); + sb.append(s); + } + return sb.toString(); + } + + /** + * parse key-value pair. + * + * @param str string. + * @param itemSeparator item separator. + * @return key-value map; + */ + private static Map parseKeyValuePair(String str, String itemSeparator) { + String[] tmp = str.split(itemSeparator); + Map map = new HashMap(tmp.length); + for (String aTmp : tmp) { + Matcher matcher = KVP_PATTERN.matcher(aTmp); + if (!matcher.matches()) + continue; + map.put(matcher.group(1), matcher.group(2)); + } + return map; + } + + public static String getQueryStringValue(String qs, String key) { + Map map = StringUtils.parseQueryString(qs); + return map.get(key); + } + + /** * parse query string to Parameters. - * + * * @param qs query string. * @return Parameters instance. */ - public static Map parseQueryString(String qs) - { - if( qs == null || qs.length() == 0 ) + public static Map parseQueryString(String qs) { + if (qs == null || qs.length() == 0) return new HashMap(); - return parseKeyValuePair(qs, "\\&"); - } - - public static String getServiceKey(Map ps) { - StringBuilder buf = new StringBuilder(); + return parseKeyValuePair(qs, "\\&"); + } + + public static String getServiceKey(Map ps) { + StringBuilder buf = new StringBuilder(); String group = ps.get(Constants.GROUP_KEY); - if (group != null && group.length()>0){ + if (group != null && group.length() > 0) { buf.append(group).append("/"); } buf.append(ps.get(Constants.INTERFACE_KEY)); String version = ps.get(Constants.VERSION_KEY); - if (version!= null && version.length()>0){ + if (version != null && version.length() > 0) { buf.append(":").append(version); } return buf.toString(); - } - - public static String toQueryString(Map ps) { - StringBuilder buf = new StringBuilder(); - if (ps != null && ps.size() > 0) { - for (Map.Entry entry : new TreeMap(ps).entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (key != null && key.length() > 0 - && value != null && value.length() > 0) { - if (buf.length() > 0) { - buf.append("&"); - } - buf.append(key); - buf.append("="); - buf.append(value); - } - } - } - return buf.toString(); - } - - public static String camelToSplitName(String camelName, String split) { - if (camelName == null || camelName.length() == 0) { - return camelName; - } - StringBuilder buf = null; - for (int i = 0; i < camelName.length(); i ++) { - char ch = camelName.charAt(i); - if (ch >= 'A' && ch <= 'Z') { - if (buf == null) { - buf = new StringBuilder(); - if (i > 0) { - buf.append(camelName.substring(0, i)); - } - } - if (i > 0) { - buf.append(split); - } - buf.append(Character.toLowerCase(ch)); - } else if (buf != null) { - buf.append(ch); - } - } - return buf == null ? camelName : buf.toString(); - } - - public static String toArgumentString(Object[] args) { - StringBuilder buf = new StringBuilder(); + } + + public static String toQueryString(Map ps) { + StringBuilder buf = new StringBuilder(); + if (ps != null && ps.size() > 0) { + for (Map.Entry entry : new TreeMap(ps).entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (key != null && key.length() > 0 + && value != null && value.length() > 0) { + if (buf.length() > 0) { + buf.append("&"); + } + buf.append(key); + buf.append("="); + buf.append(value); + } + } + } + return buf.toString(); + } + + public static String camelToSplitName(String camelName, String split) { + if (camelName == null || camelName.length() == 0) { + return camelName; + } + StringBuilder buf = null; + for (int i = 0; i < camelName.length(); i++) { + char ch = camelName.charAt(i); + if (ch >= 'A' && ch <= 'Z') { + if (buf == null) { + buf = new StringBuilder(); + if (i > 0) { + buf.append(camelName.substring(0, i)); + } + } + if (i > 0) { + buf.append(split); + } + buf.append(Character.toLowerCase(ch)); + } else if (buf != null) { + buf.append(ch); + } + } + return buf == null ? camelName : buf.toString(); + } + + public static String toArgumentString(Object[] args) { + StringBuilder buf = new StringBuilder(); for (Object arg : args) { if (buf.length() > 0) { buf.append(Constants.COMMA_SEPARATOR); @@ -449,7 +422,8 @@ public static String toArgumentString(Object[] args) { } } return buf.toString(); - } + } - private StringUtils(){} + private StringUtils() { + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java index 73cfadaa654..fed3831d0de 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -80,5 +80,4 @@ public String toString() { return getUrl().toString(); } - } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 85e4186e5f8..93433c49409 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -2,6 +2,7 @@ import com.alibaba.dubbo.common.utils.MethodCache; import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.async.AsyncCommand; import java.lang.reflect.Method; @@ -9,13 +10,15 @@ public class AsyncableInvocationHandler extends InvokerInvocationHandler { + private static final MethodCache methodCache = MethodCache.newCache(); + public AsyncableInvocationHandler(Invoker handler) { super(handler); } - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!isAsyncMethod(method)) { - return super.invoke(proxy, method, args); + return invokeSuper(proxy, method, args); } else { AsyncCommand command = new AsyncMethodCommand(proxy, method, args); return command.queue(); @@ -30,32 +33,38 @@ private boolean isAsyncMethod(Method method) { /** * async method wrapper */ - static class AsyncMethodCommand extends AsyncCommand { - - private static final MethodCache methodCache = MethodCache.newCache(); + class AsyncMethodCommand extends AsyncCommand { private final Object proxy; - private final Method wrapped; + private final Method asyncMethod; private final Object[] args; - public AsyncMethodCommand(Object proxy, Method wrapped, Object[] args) { + public AsyncMethodCommand(Object proxy, Method asyncMethod, Object[] args) { this.proxy = proxy; - this.wrapped = wrapped; + this.asyncMethod = asyncMethod; this.args = args; } private Method getCorrespondingSyncMethod() throws Exception { - String methodName = wrapped.getName(); - Class[] parameterTypes = wrapped.getParameterTypes(); + String methodName = asyncMethod.getName(); + Class[] parameterTypes = asyncMethod.getParameterTypes(); String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - return methodCache.get(wrapped, syncMethodName, parameterTypes); + return methodCache.get(proxy, syncMethodName, parameterTypes); } @Override public Object run() throws Exception { - return getCorrespondingSyncMethod().invoke(proxy, args); + return AsyncableInvocationHandler.this.invokeSuper(proxy, getCorrespondingSyncMethod(), args); + } + } + + private Object invokeSuper(Object proxy, Method method, Object[] args) { + try { + return super.invoke(proxy, method, args); + } catch (Throwable e) { + throw new RpcException(e.getMessage(), e); } } } From ef55ee60b95019ed5ab8d848d25d431b5ee58329 Mon Sep 17 00:00:00 2001 From: YanXs Date: Wed, 7 Jun 2017 21:37:56 +0800 Subject: [PATCH 69/69] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20MethodCacheKey=20?= =?UTF-8?q?=E8=AE=A1=E7=AE=97=E9=94=99=E8=AF=AFBUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/utils/MethodCache.java | 12 ++++++------ .../dubbo/rpc/proxy/AsyncableInvocationHandler.java | 2 +- .../alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java index c510c1ba9ed..307c4ce673b 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MethodCache.java @@ -18,23 +18,23 @@ public static MethodCache newCache() { return new MethodCache(); } - private Integer methodKey(Object object, String methodName, Class[] parameterTypes) { - return methodName.hashCode() + Arrays.hashCode(parameterTypes) + object.hashCode(); + private Integer methodKey(Class targetClass, String methodName, Class[] parameterTypes) { + return methodName.hashCode() + Arrays.hashCode(parameterTypes) + targetClass.hashCode(); } - public Method get(Object object, String methodName, Class[] parameterTypes) throws Exception { - Assert.notNull(object, "object must not be null!"); + public Method get(Class targetClass, String methodName, Class[] parameterTypes) throws Exception { + Assert.notNull(targetClass, "object must not be null!"); if (StringUtils.isEmpty(methodName)) { throw new IllegalArgumentException("methodName must not be null or empty"); } - Integer methodKey = methodKey(object, methodName, parameterTypes); + Integer methodKey = methodKey(targetClass, methodName, parameterTypes); Method previouslyCached = cachedMethods.get(methodKey); if (previouslyCached != null) { return previouslyCached; } synchronized (lock) { if (!cachedMethods.containsKey(methodKey)) { - Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes); + Method method = targetClass.getDeclaredMethod(methodName, parameterTypes); cachedMethods.put(methodKey, method); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java index 93433c49409..76e3af8d56d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/AsyncableInvocationHandler.java @@ -51,7 +51,7 @@ private Method getCorrespondingSyncMethod() throws Exception { String methodName = asyncMethod.getName(); Class[] parameterTypes = asyncMethod.getParameterTypes(); String syncMethodName = methodName.substring(methodName.indexOf("async_") + "async_".length()); - return methodCache.get(proxy, syncMethodName, parameterTypes); + return methodCache.get(proxy.getClass(), syncMethodName, parameterTypes); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index 0955d52806f..f9eb90f67ec 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -54,7 +54,7 @@ public CachedProxyInvoker(T proxy, Class type, URL url) { @Override protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { - return methodCache.get(proxy, methodName, parameterTypes); + return methodCache.get(proxy.getClass(), methodName, parameterTypes); } } } \ No newline at end of file