Java Code Examples for com.alibaba.dubbo.common.Constants

The following examples show how to use com.alibaba.dubbo.common.Constants. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: dubbox   Source File: DubboRegistryFactory.java    License: Apache License 2.0 6 votes vote down vote up
public Registry createRegistry(URL url) {
    url = getRegistryURL(url);
    List<URL> urls = new ArrayList<URL>();
    urls.add(url.removeParameter(Constants.BACKUP_KEY));
    String backup = url.getParameter(Constants.BACKUP_KEY);
    if (backup != null && backup.length() > 0) {
        String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(backup);
        for (String address : addresses) {
            urls.add(url.setAddress(address));
        }
    }
    RegistryDirectory<RegistryService> directory = new RegistryDirectory<RegistryService>(RegistryService.class, url.addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString()));
    Invoker<RegistryService> registryInvoker = cluster.join(directory);
    RegistryService registryService = proxyFactory.getProxy(registryInvoker);
    DubboRegistry registry = new DubboRegistry(registryInvoker, registryService);
    directory.setRegistry(registry);
    directory.setProtocol(protocol);
    directory.notify(urls);
    directory.subscribe(new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters()));
    return registry;
}
 
Example 2
Source Project: dubbox   Source File: SyncUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Provider url2Provider(Pair<Long, URL> pair) {
	if (pair == null) {
		return null;
	}
	
    Long id = pair.getKey();
    URL url = pair.getValue();

    if (url == null)
        return null;

    Provider p = new Provider();
    p.setId(id);
    p.setService(url.getServiceKey());
    p.setAddress(url.getAddress());
    p.setApplication(url.getParameter(Constants.APPLICATION_KEY));
    p.setUrl(url.toIdentityString());
    p.setParameters(url.toParameterString());

    p.setDynamic(url.getParameter("dynamic", true));
    p.setEnabled(url.getParameter(Constants.ENABLED_KEY, true));
    p.setWeight(url.getParameter(Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT));
    p.setUsername(url.getParameter("owner"));

    return p;
}
 
Example 3
Source Project: dubbo3   Source File: ProviderServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> findApplications() {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : providerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            String app = u.getParameter(Constants.APPLICATION_KEY);
            if(app != null) ret.add(app);
        }
    }
    
    return ret;
}
 
Example 4
Source Project: dubbox-hystrix   Source File: ConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericServiceConfig() throws Exception {
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("test"));
    service.setRegistry(new RegistryConfig("mock://localhost"));
    service.setInterface(DemoService.class.getName());
    service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN);
    service.setRef(new GenericService(){

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            return null;
        }
    });
    try {
        service.export();
        Collection<Registry> collection = MockRegistryFactory.getCachedRegistry();
        MockRegistry registry = (MockRegistry)collection.iterator().next();
        URL url = registry.getRegistered().get(0);
        Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY));
    } finally {
        MockRegistryFactory.cleanCachedRegistry();
        service.unexport();
    }
}
 
Example 5
Source Project: dubbox   Source File: MockClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerInvoke_forcemock_defaultreturn(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName());
	url = url.addParameter(Constants.MOCK_KEY, "force" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
    URL mockUrl = URL.valueOf("mock://localhost/"+IHelloService.class.getName()
			+"?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ")
			.addParameters(url.getParameters());
	
	Protocol protocol = new MockProtocol();
	Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
	invokers.add(mInvoker1);
    
    RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("sayHello");
    Result ret = cluster.invoke(invocation);
    Assert.assertEquals(null, ret.getValue());
}
 
Example 6
Source Project: dubbo-2.6.5   Source File: ReferenceConfig.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkAndConvertImplicitConfig(MethodConfig method, Map<String, String> map, Map<Object, Object> 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 覆盖静态上下文中异步调用的方法 onreturn.method
    String onReturnMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_RETURN_METHOD_KEY);
    Object onReturnMethod = attributes.get(onReturnMethodKey);
    if (onReturnMethod instanceof String) {
        attributes.put(onReturnMethodKey, getMethodByName(method.getOnreturn().getClass(), onReturnMethod.toString()));
    }
    //convert onthrow methodName to Method 覆盖静态上下文中异常调用方法 onthrow.method
    String onThrowMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_THROW_METHOD_KEY);
    Object onThrowMethod = attributes.get(onThrowMethodKey);
    if (onThrowMethod instanceof String) {
        attributes.put(onThrowMethodKey, getMethodByName(method.getOnthrow().getClass(), onThrowMethod.toString()));
    }
    //convert oninvoke methodName to Method 覆盖静态上下文中异步调用后执行的方法 oninvoke.method
    String onInvokeMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_INVOKE_METHOD_KEY);
    Object onInvokeMethod = attributes.get(onInvokeMethodKey);
    if (onInvokeMethod instanceof String) {
        attributes.put(onInvokeMethodKey, getMethodByName(method.getOninvoke().getClass(), onInvokeMethod.toString()));
    }
}
 
Example 7
Source Project: dubbox   Source File: ExchangeCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception {
    Request request = new Request(1L);
    request.setData("hello");
    ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512);
    AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
    try {
        codec.encode(channel, encodeBuffer, request);
        Assert.fail();
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6));
    }

    Response response = new Response(1L);
    response.setResult("hello");
    encodeBuffer = ChannelBuffers.dynamicBuffer(512);
    channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
    codec.encode(channel, encodeBuffer, response);
    Assert.assertTrue(channel.getReceivedMessage() instanceof Response);
    Response receiveMessage = (Response) channel.getReceivedMessage();
    Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus());
    Assert.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: "));
}
 
Example 8
Source Project: dubbox-hystrix   Source File: ProviderServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> findAddresses() {
    List<String> ret = new ArrayList<String>();
    
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(null == providerUrls) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : providerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            String app = u.getAddress();
            if(app != null) ret.add(app);
        }
    }
    
    return ret;
}
 
Example 9
Source Project: dubbo3   Source File: ProviderServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> findMethodsByService(String service) {
    List<String> ret = new ArrayList<String>();

    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null || service == null || service.length() == 0) return ret;
    
    Map<Long, URL> providers = providerUrls.get(service);
    if(null == providers || providers.isEmpty()) return ret;
    
    Entry<Long, URL> p = providers.entrySet().iterator().next();
    String value = p.getValue().getParameter("methods");
    if (value == null || value.length() == 0) {
        return ret;
    }
    String[] methods = value.split(ParseUtils.METHOD_SPLIT);
    if (methods == null || methods.length == 0) {
        return ret;
    }
    
    for(String m : methods) {
        ret.add(m);
    }
    return ret;
}
 
Example 10
Source Project: dubbox   Source File: TpsLimitFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = RpcException.class)
public void testFail() throws Exception {
    URL url = URL.valueOf("test://test");
    url = url.addParameter(Constants.INTERFACE_KEY,
                           "com.alibaba.dubbo.rpc.file.TpsService");
    url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5);
    Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
    Invocation invocation = new MockInvocation();
    for (int i = 0; i < 10; i++) {
        try {
            filter.invoke(invoker, invocation);
        } catch (Exception e) {
            assertTrue(i >= 5);
            throw e;
        }
    }
}
 
Example 11
Source Project: dubbo-2.6.5   Source File: MonitorFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
            RpcContext context = RpcContext.getContext(); // provider must fetch context before invoke() gets called
            String remoteHost = context.getRemoteHost();
            long start = System.currentTimeMillis(); // record start timestamp
            getConcurrent(invoker, invocation).incrementAndGet(); // count up
            try {
                Result result = invoker.invoke(invocation); // proceed invocation chain
                collect(invoker, invocation, result, remoteHost, start, false);
                return result;
            } catch (RpcException e) {
                collect(invoker, invocation, null, remoteHost, start, true);
                throw e;
            } finally {
                getConcurrent(invoker, invocation).decrementAndGet(); // count down
            }
        } else {
//            com.alibaba.dubbo.rpc.protocol.AbstractInvoker.invoke
            return invoker.invoke(invocation);
        }
    }
 
Example 12
Source Project: dubbox-hystrix   Source File: RegistryProtocol.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Invoker<T> refer(Class<T> 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);
       }

       // group="a,b" or group="*"
       Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY));
       String group = qs.get(Constants.GROUP_KEY);
       if (group != null && group.length() > 0 ) {
           if ( ( Constants.COMMA_SPLIT_PATTERN.split( group ) ).length > 1
                   || "*".equals( group ) ) {
               return doRefer( getMergeableCluster(), registry, type, url );
           }
       }
       return doRefer(cluster, registry, type, url);
   }
 
Example 13
Source Project: dubbo-2.6.5   Source File: AbstractConfig.java    License: Apache License 2.0 6 votes vote down vote up
protected static void checkMultiExtension(Class<?> type, String property, String value) {
    checkMultiName(property, value);
    if (value != null && value.length() > 0) {
        String[] values = value.split("\\s*[,]+\\s*");
        for (String v : values) {
            if (v.startsWith(Constants.REMOVE_VALUE_PREFIX)) {
                v = v.substring(1);
            }
            if (Constants.DEFAULT_KEY.equals(v)) {
                continue;
            }
            if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) {
                throw new IllegalStateException("No such extension " + v + " for " + property + "/" + type.getName());
            }
        }
    }
}
 
Example 14
Source Project: dubbox-hystrix   Source File: ConsistentHashLoadBalance.java    License: Apache License 2.0 6 votes vote down vote up
public ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
    this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
    this.identityHashCode = System.identityHashCode(invokers);
    URL url = invokers.get(0).getUrl();
    this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
    String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
    argumentIndex = new int[index.length];
    for (int i = 0; i < index.length; i ++) {
        argumentIndex[i] = Integer.parseInt(index[i]);
    }
    for (Invoker<T> invoker : invokers) {
        for (int i = 0; i < replicaNumber / 4; i++) {
            byte[] digest = md5(invoker.getUrl().toFullString() + i);
            for (int h = 0; h < 4; h++) {
                long m = hash(digest, h);
                virtualInvokers.put(m, invoker);
            }
        }
    }
}
 
Example 15
Source Project: dubbox   Source File: UrlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static URL getEmptyUrl(String service, String category) {
    String group = null;
    String version = null;
    int i = service.indexOf('/');
    if (i > 0) {
        group = service.substring(0, i);
        service = service.substring(i + 1);
    }
    i = service.lastIndexOf(':');
    if (i > 0) {
        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));
}
 
Example 16
Source Project: dubbo-2.6.5   Source File: InjvmProtocol.java    License: Apache License 2.0 6 votes vote down vote up
static Exporter<?> getExporter(Map<String, Exporter<?>> map, URL key) {
    Exporter<?> result = null;

    if (!key.getServiceKey().contains("*")) {
        result = map.get(key.getServiceKey());
    } else {
        if (map != null && !map.isEmpty()) {
            for (Exporter<?> exporter : map.values()) {
                if (UrlUtils.isServiceKeyMatch(key, exporter.getInvoker().getUrl())) {
                    result = exporter;
                    break;
                }
            }
        }
    }

    if (result == null) {
        return null;
    } else if (ProtocolUtils.isGeneric(
            result.getInvoker().getUrl().getParameter(Constants.GENERIC_KEY))) {
        return null;
    } else {
        return result;
    }
}
 
Example 17
Source Project: dubbox   Source File: DubboProtocol.java    License: Apache License 2.0 6 votes vote down vote up
private ExchangeServer createServer(URL url) {
    //默认开启server关闭时发送readonly事件
    url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString());
    //默认开启heartbeat
    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))
        throw new RpcException("Unsupported server type: " + str + ", url: " + url);

    url = url.addParameter(Constants.CODEC_KEY, Version.isCompatibleVersion() ? COMPATIBLE_CODEC_NAME : DubboCodec.NAME);
    ExchangeServer server;
    try {
        server = Exchangers.bind(url, requestHandler);
    } 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<String> supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions();
        if (!supportedTypes.contains(str)) {
            throw new RpcException("Unsupported client type: " + str);
        }
    }
    return server;
}
 
Example 18
Source Project: dubbo-2.6.5   Source File: ChanelHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClient() throws Throwable {
    // read server info from property
    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);
    int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60);

    final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout;
    ExchangeClient exchangeClient = initClient(url);
    Thread.sleep(sleep);
    closeClient(exchangeClient);
}
 
Example 19
Source Project: dubbo-2.6.5   Source File: MethodConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOnthrow() throws Exception {
    MethodConfig method = new MethodConfig();
    method.setOnthrow("on-throw-object");
    assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object"));
    Map<Object, Object> attribute = new HashMap<Object, Object>();
    MethodConfig.appendAttributes(attribute, method);
    assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object"));
    Map<String, String> parameters = new HashMap<String, String>();
    MethodConfig.appendParameters(parameters, method);
    assertThat(parameters.size(), is(0));
}
 
Example 20
Source Project: dubbox   Source File: AbstractLoadBalance.java    License: Apache License 2.0 5 votes vote down vote up
protected int getWeight(Invoker<?> invoker, Invocation invocation) {
    int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
    if (weight > 0) {
     long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L);
 	if (timestamp > 0L) {
 		int uptime = (int) (System.currentTimeMillis() - timestamp);
 		int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
 		if (uptime > 0 && uptime < warmup) {
 			weight = calculateWarmupWeight(uptime, warmup, weight);
 		}
 	}
    }
	return weight;
}
 
Example 21
Source Project: dubbox-hystrix   Source File: ProtocolUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isGeneric(String generic) {
    return generic != null
        && !"".equals(generic)
        && (Constants.GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic)  /* 正常的泛化调用 */
        || Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* 支持java序列化的流式泛化调用 */
        || Constants.GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic));
}
 
Example 22
Source Project: dubbo-2.6.5   Source File: AbstractClusterInvoker.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Select a invoker using loadbalance policy.</br>
     * a)Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or, 
     * if this invoker is unavailable, then continue step b (reselect), otherwise return the first selected invoker</br>
     * b)Reslection, the validation rule for reselection: selected > available. This rule guarantees that
     * the selected invoker has the minimum chance to be one in the previously selected list, and also 
     * guarantees this invoker is available.
     *
     * @param loadbalance load balance policy
     * @param invocation
     * @param invokers invoker candidates
     * @param selected  exclude selected invokers or not
     * @return
     * @throws RpcException
     * 使用loadbalance策略选择调用程序。a)首先,使用loadbalance选择一个调用程序。如果这个调用程序在前面选择的列表中,或者,如果这个调用程序不可用,那么继续步骤b (reselect),
     * 否则返回第一个选择的调用程序b)Reslection,重新选择的验证规则:选择的>可用。该规则保证所选的调用程序有最小的机会出现在前面选择的列表中,并保证该调用程序可用。
     */
    protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
        if (invokers == null || invokers.isEmpty())
            return null;
//        执行的方法名
        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 concurrency problem
            if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
                if (availablecheck && stickyInvoker.isAvailable()) {
                    return stickyInvoker;
                }
            }
        }
//        执行负载均衡策略=》
        Invoker<T> invoker = doSelect(loadbalance, invocation, invokers, selected);

        if (sticky) {
            stickyInvoker = invoker;
        }
        return invoker;
    }
 
Example 23
Source Project: dubbo-remoting-netty4   Source File: NettyCodecAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public NettyCodecAdapter(Codec2 codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) {
    this.codec = codec;
    this.url = url;
    this.handler = handler;
    int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE);
    this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE;
}
 
Example 24
Source Project: dubbo-2.6.5   Source File: AbstractEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
protected static Codec2 getChannelCodec(URL url) {
//        默认codec是telnet
        String codecName = url.getParameter(Constants.CODEC_KEY, "telnet");
        if (ExtensionLoader.getExtensionLoader(Codec2.class).hasExtension(codecName)) {
            return ExtensionLoader.getExtensionLoader(Codec2.class).getExtension(codecName);
        } else {
            return new CodecAdapter(ExtensionLoader.getExtensionLoader(Codec.class)
                    .getExtension(codecName));
        }
    }
 
Example 25
Source Project: dubbox-hystrix   Source File: Override.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, String> toParametersMap() {
	Map<String, String> map = StringUtils.parseQueryString(getParams());
	map.remove(Constants.INTERFACE_KEY);
	map.remove(Constants.GROUP_KEY);
	map.remove(Constants.VERSION_KEY);
	map.remove(Constants.APPLICATION_KEY);
	map.remove(Constants.CATEGORY_KEY);
	map.remove(Constants.DYNAMIC_KEY);
	map.remove(Constants.ENABLED_KEY);
	return map;
}
 
Example 26
Source Project: dubbo3   Source File: LimitedThreadPool.java    License: Apache License 2.0 5 votes vote down vote up
public Executor getExecutor(URL url) {
    String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);
    int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);
    int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
    int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);
    return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, 
    		queues == 0 ? new SynchronousQueue<>() :
    			(queues < 0 ? new LinkedBlockingQueue<>()
    					: new LinkedBlockingQueue<>(queues)),
    		new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));
}
 
Example 27
Source Project: dubbox   Source File: DubboInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 28
Source Project: dubbo3   Source File: RegistryProtocol.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过invoker的url 获取 providerUrl的地址
 * @param origininvoker
 * @return
 */
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;
}
 
Example 29
Source Project: dubbox-hystrix   Source File: ThriftProtocol.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 30
Source Project: dubbo3   Source File: DubboInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}