Search in sources :

Example 21 with Invocation

use of org.apache.dubbo.rpc.Invocation in project dubbo by alibaba.

the class RpcUtilsTest method testAttachInvocationIdIfAsync_sync.

/**
 * scenario: sync invocation, no attachment added by default
 * verify: no id attribute added in attachment
 */
@Test
public void testAttachInvocationIdIfAsync_sync() {
    URL url = URL.valueOf("dubbo://localhost/");
    Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {});
    RpcUtils.attachInvocationIdIfAsync(url, inv);
    assertNull(RpcUtils.getInvocationId(inv));
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) Invocation(org.apache.dubbo.rpc.Invocation) RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) URL(org.apache.dubbo.common.URL) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 22 with Invocation

use of org.apache.dubbo.rpc.Invocation in project dubbo by alibaba.

the class TagRouter method route.

@Override
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    if (CollectionUtils.isEmpty(invokers)) {
        return invokers;
    }
    // since the rule can be changed by config center, we should copy one to use.
    final TagRouterRule tagRouterRuleCopy = tagRouterRule;
    if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
        return filterUsingStaticTag(invokers, url, invocation);
    }
    List<Invoker<T>> result = invokers;
    String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) : invocation.getAttachment(TAG_KEY);
    // if we are requesting for a Provider with a specific tag
    if (StringUtils.isNotEmpty(tag)) {
        List<String> addresses = tagRouterRuleCopy.getTagnameToAddresses().get(tag);
        // filter by dynamic tag group first
        if (CollectionUtils.isNotEmpty(addresses)) {
            result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
            // if result is not null OR it's null but force=true, return result directly
            if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) {
                return result;
            }
        } else {
            // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by
            // dynamic tag group but force=false. check static tag
            result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
        }
        // to false, which means it will invoke any providers without a tag unless it's explicitly disallowed.
        if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) {
            return result;
        } else // FAILOVER: return all Providers without any tags.
        {
            List<Invoker<T>> tmp = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses()));
            return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
        }
    } else {
        // List<String> addresses = tagRouterRule.filter(providerApp);
        // return all addresses in dynamic tag group.
        List<String> addresses = tagRouterRuleCopy.getAddresses();
        if (CollectionUtils.isNotEmpty(addresses)) {
            result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
            // 1. all addresses are in dynamic tag group, return empty list.
            if (CollectionUtils.isEmpty(result)) {
                return result;
            }
        // 2. if there are some addresses that are not in any dynamic tag group, continue to filter using the
        // static tag group.
        }
        return filterInvoker(result, invoker -> {
            String localTag = invoker.getUrl().getParameter(TAG_KEY);
            return StringUtils.isEmpty(localTag) || !tagRouterRuleCopy.getTagNames().contains(localTag);
        });
    }
}
Also used : ConfigurationListener(org.apache.dubbo.common.config.configcenter.ConfigurationListener) LoggerFactory(org.apache.dubbo.common.logger.LoggerFactory) Logger(org.apache.dubbo.common.logger.Logger) Predicate(java.util.function.Predicate) CollectionUtils(org.apache.dubbo.common.utils.CollectionUtils) Invocation(org.apache.dubbo.rpc.Invocation) Invoker(org.apache.dubbo.rpc.Invoker) RpcException(org.apache.dubbo.rpc.RpcException) NetUtils(org.apache.dubbo.common.utils.NetUtils) TagRouterRule(org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule) Collectors(java.util.stream.Collectors) CommonConstants(org.apache.dubbo.common.constants.CommonConstants) StringUtils(org.apache.dubbo.common.utils.StringUtils) ConfigChangedEvent(org.apache.dubbo.common.config.configcenter.ConfigChangedEvent) URL(org.apache.dubbo.common.URL) List(java.util.List) FORCE_USE_TAG(org.apache.dubbo.rpc.Constants.FORCE_USE_TAG) ANYHOST_VALUE(org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE) ConfigChangeType(org.apache.dubbo.common.config.configcenter.ConfigChangeType) AbstractRouter(org.apache.dubbo.rpc.cluster.router.AbstractRouter) DynamicConfiguration(org.apache.dubbo.common.config.configcenter.DynamicConfiguration) TAG_KEY(org.apache.dubbo.common.constants.CommonConstants.TAG_KEY) TagRuleParser(org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser) Invoker(org.apache.dubbo.rpc.Invoker) TagRouterRule(org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule)

Example 23 with Invocation

use of org.apache.dubbo.rpc.Invocation in project dubbo by alibaba.

the class MemcachedProtocol method protocolBindingRefer.

@Override
public <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
    try {
        String address = url.getAddress();
        String backup = url.getParameter(RemotingConstants.BACKUP_KEY);
        if (backup != null && backup.length() > 0) {
            address += "," + backup;
        }
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(address));
        final MemcachedClient memcachedClient = builder.build();
        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");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                try {
                    Object value = null;
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        value = memcachedClient.get(String.valueOf(invocation.getArguments()[0]));
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The memcached set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.set(String.valueOf(invocation.getArguments()[0]), expiry, invocation.getArguments()[1]);
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.delete(String.valueOf(invocation.getArguments()[0]));
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in memcached service.");
                    }
                    return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke memcached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof TimeoutException || t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof MemcachedException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    }
                    throw re;
                }
            }

            @Override
            public void destroy() {
                super.destroy();
                try {
                    memcachedClient.shutdown();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer memcached service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) MemcachedClientBuilder(net.rubyeye.xmemcached.MemcachedClientBuilder) Invocation(org.apache.dubbo.rpc.Invocation) AbstractInvoker(org.apache.dubbo.rpc.protocol.AbstractInvoker) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedClient(net.rubyeye.xmemcached.MemcachedClient) RpcException(org.apache.dubbo.rpc.RpcException) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedException(net.rubyeye.xmemcached.exception.MemcachedException)

Example 24 with Invocation

use of org.apache.dubbo.rpc.Invocation in project dubbo by alibaba.

the class RedisProtocol method protocolBindingRefer.

@Override
protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
    try {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
        config.setTestOnReturn(url.getParameter("test.on.return", false));
        config.setTestWhileIdle(url.getParameter("test.while.idle", false));
        if (url.getParameter("max.idle", 0) > 0) {
            config.setMaxIdle(url.getParameter("max.idle", 0));
        }
        if (url.getParameter("min.idle", 0) > 0) {
            config.setMinIdle(url.getParameter("min.idle", 0));
        }
        if (url.getParameter("max.active", 0) > 0) {
            config.setMaxTotal(url.getParameter("max.active", 0));
        }
        if (url.getParameter("max.total", 0) > 0) {
            config.setMaxTotal(url.getParameter("max.total", 0));
        }
        if (url.getParameter("max.wait", 0) > 0) {
            config.setMaxWaitMillis(url.getParameter("max.wait", 0));
        }
        if (url.getParameter("num.tests.per.eviction.run", 0) > 0) {
            config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
        }
        if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) {
            config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
        }
        if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) {
            config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));
        }
        final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(), url.getParameter("db.index", 0));
        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");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                Jedis jedis = null;
                try {
                    jedis = jedisPool.getResource();
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes());
                        if (value == null) {
                            return AsyncRpcResult.newDefaultAsyncResult(invocation);
                        }
                        ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value));
                        return AsyncRpcResult.newDefaultAsyncResult(oin.readObject(), invocation);
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes();
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        ObjectOutput value = getSerialization(url).serialize(url, output);
                        value.writeObject(invocation.getArguments()[1]);
                        jedis.set(key, output.toByteArray());
                        if (expiry > 1000) {
                            jedis.expire(key, expiry / 1000);
                        }
                        return AsyncRpcResult.newDefaultAsyncResult(invocation);
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes());
                        return AsyncRpcResult.newDefaultAsyncResult(invocation);
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service.");
                    }
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke redis service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof JedisConnectionException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    } else if (t instanceof JedisDataException) {
                        re.setCode(RpcException.SERIALIZATION_EXCEPTION);
                    }
                    throw re;
                } finally {
                    if (jedis != null) {
                        try {
                            jedis.close();
                        } catch (Throwable t) {
                            logger.warn("returnResource error: " + t.getMessage(), t);
                        }
                    }
                }
            }

            @Override
            public void destroy() {
                super.destroy();
                try {
                    jedisPool.destroy();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : Invocation(org.apache.dubbo.rpc.Invocation) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) AbstractInvoker(org.apache.dubbo.rpc.protocol.AbstractInvoker) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JedisDataException(redis.clients.jedis.exceptions.JedisDataException) Jedis(redis.clients.jedis.Jedis) SocketTimeoutException(java.net.SocketTimeoutException) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) RpcException(org.apache.dubbo.rpc.RpcException) JedisPool(redis.clients.jedis.JedisPool) ObjectInput(org.apache.dubbo.common.serialize.ObjectInput) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Example 25 with Invocation

use of org.apache.dubbo.rpc.Invocation in project dubbo by alibaba.

the class JCacheFactoryTest method testJCacheGetExpired.

@Test
public void testJCacheGetExpired() throws Exception {
    URL url = URL.valueOf("test://test:12/test?cache=jacache&cache.write.expire=1");
    AbstractCacheFactory cacheFactory = getCacheFactory();
    Invocation invocation = new RpcInvocation();
    Cache cache = cacheFactory.getCache(url, invocation);
    cache.put("testKey", "testValue");
    Thread.sleep(10);
    assertNull(cache.get("testKey"));
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) Invocation(org.apache.dubbo.rpc.Invocation) RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) AbstractCacheFactory(org.apache.dubbo.cache.support.AbstractCacheFactory) URL(org.apache.dubbo.common.URL) Cache(org.apache.dubbo.cache.Cache) Test(org.junit.jupiter.api.Test) AbstractCacheFactoryTest(org.apache.dubbo.cache.support.AbstractCacheFactoryTest)

Aggregations

Invocation (org.apache.dubbo.rpc.Invocation)98 Test (org.junit.jupiter.api.Test)78 URL (org.apache.dubbo.common.URL)77 Invoker (org.apache.dubbo.rpc.Invoker)44 RpcInvocation (org.apache.dubbo.rpc.RpcInvocation)44 Result (org.apache.dubbo.rpc.Result)33 AppResponse (org.apache.dubbo.rpc.AppResponse)29 RpcException (org.apache.dubbo.rpc.RpcException)18 MockInvocation (org.apache.dubbo.rpc.support.MockInvocation)17 HashMap (java.util.HashMap)16 AsyncRpcResult (org.apache.dubbo.rpc.AsyncRpcResult)13 BlockMyInvoker (org.apache.dubbo.rpc.support.BlockMyInvoker)11 MyInvoker (org.apache.dubbo.rpc.support.MyInvoker)10 ArrayList (java.util.ArrayList)8 Person (org.apache.dubbo.rpc.support.Person)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 IMetricManager (com.alibaba.metrics.IMetricManager)5 Method (java.lang.reflect.Method)5 DemoService (org.apache.dubbo.monitor.dubbo.service.DemoService)5 FastCompass (com.alibaba.metrics.FastCompass)4