Search in sources :

Example 41 with Result

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

the class MergeableClusterInvoker method doInvoke.

@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
    checkInvokers(invokers, invocation);
    String merger = getUrl().getMethodParameter(invocation.getMethodName(), MERGER_KEY);
    if (ConfigUtils.isEmpty(merger)) {
        // If a method doesn't have a merger, only invoke one Group
        for (final Invoker<T> invoker : invokers) {
            if (invoker.isAvailable()) {
                try {
                    return invoker.invoke(invocation);
                } catch (RpcException e) {
                    if (e.isNoInvokerAvailableAfterFilter()) {
                        log.debug("No available provider for service" + getUrl().getServiceKey() + " on group " + invoker.getUrl().getParameter(GROUP_KEY) + ", will continue to try another group.");
                    } else {
                        throw e;
                    }
                }
            }
        }
        return invokers.iterator().next().invoke(invocation);
    }
    Class<?> returnType;
    try {
        returnType = getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()).getReturnType();
    } catch (NoSuchMethodException e) {
        returnType = null;
    }
    Map<String, Result> results = new HashMap<>();
    for (final Invoker<T> invoker : invokers) {
        RpcInvocation subInvocation = new RpcInvocation(invocation, invoker);
        subInvocation.setAttachment(ASYNC_KEY, "true");
        results.put(invoker.getUrl().getServiceKey(), invoker.invoke(subInvocation));
    }
    Object result = null;
    List<Result> resultList = new ArrayList<Result>(results.size());
    for (Map.Entry<String, Result> entry : results.entrySet()) {
        Result asyncResult = entry.getValue();
        try {
            Result r = asyncResult.get();
            if (r.hasException()) {
                log.error("Invoke " + getGroupDescFromServiceKey(entry.getKey()) + " failed: " + r.getException().getMessage(), r.getException());
            } else {
                resultList.add(r);
            }
        } catch (Exception e) {
            throw new RpcException("Failed to invoke service " + entry.getKey() + ": " + e.getMessage(), e);
        }
    }
    if (resultList.isEmpty()) {
        return AsyncRpcResult.newDefaultAsyncResult(invocation);
    } else if (resultList.size() == 1) {
        return AsyncRpcResult.newDefaultAsyncResult(resultList.get(0).getValue(), invocation);
    }
    if (returnType == void.class) {
        return AsyncRpcResult.newDefaultAsyncResult(invocation);
    }
    if (merger.startsWith(".")) {
        merger = merger.substring(1);
        Method method;
        try {
            method = returnType.getMethod(merger, returnType);
        } catch (NoSuchMethodException e) {
            throw new RpcException("Can not merge result because missing method [ " + merger + " ] in class [ " + returnType.getName() + " ]");
        }
        ReflectUtils.makeAccessible(method);
        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());
                }
            } else {
                for (Result r : resultList) {
                    method.invoke(result, r.getValue());
                }
            }
        } catch (Exception e) {
            throw new RpcException("Can not merge result: " + e.getMessage(), e);
        }
    } else {
        Merger resultMerger;
        if (ConfigUtils.isDefault(merger)) {
            resultMerger = MergerFactory.getMerger(returnType);
        } else {
            resultMerger = ExtensionLoader.getExtensionLoader(Merger.class).getExtension(merger);
        }
        if (resultMerger != null) {
            List<Object> rets = new ArrayList<Object>(resultList.size());
            for (Result r : resultList) {
                rets.add(r.getValue());
            }
            result = resultMerger.merge(rets.toArray((Object[]) Array.newInstance(returnType, 0)));
        } else {
            throw new RpcException("There is no merger to merge result.");
        }
    }
    return AsyncRpcResult.newDefaultAsyncResult(result, invocation);
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) RpcException(org.apache.dubbo.rpc.RpcException) AsyncRpcResult(org.apache.dubbo.rpc.AsyncRpcResult) Result(org.apache.dubbo.rpc.Result) Merger(org.apache.dubbo.rpc.cluster.Merger) RpcException(org.apache.dubbo.rpc.RpcException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 42 with Result

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

the class FailfastClusterInvokerTest method testInvokeNoException.

@Test()
public void testInvokeNoException() {
    resetInvoker1ToNoException();
    FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
    Result ret = invoker.invoke(invocation);
    Assertions.assertSame(result, ret);
}
Also used : Result(org.apache.dubbo.rpc.Result) Test(org.junit.jupiter.api.Test)

Example 43 with Result

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

the class CacheFilter method invoke.

/**
 * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store
 * then it will return otherwise call the remote method and return value. If remote method's return value has error
 * then it will not cache the value.
 * @param invoker    service
 * @param invocation invocation.
 * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method.
 * @throws RpcException
 */
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) {
        Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation);
        if (cache != null) {
            String key = StringUtils.toArgumentString(invocation.getArguments());
            Object value = cache.get(key);
            if (value != null) {
                if (value instanceof ValueWrapper) {
                    return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation);
                } else {
                    return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
                }
            }
            Result result = invoker.invoke(invocation);
            if (!result.hasException()) {
                cache.put(key, new ValueWrapper(result.getValue()));
            }
            return result;
        }
    }
    return invoker.invoke(invocation);
}
Also used : Cache(org.apache.dubbo.cache.Cache) AsyncRpcResult(org.apache.dubbo.rpc.AsyncRpcResult) Result(org.apache.dubbo.rpc.Result)

Example 44 with Result

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

the class ServerExceptionTest method testServerException.

@Test
public void testServerException() throws Exception {
    Assertions.assertThrows(RpcException.class, () -> {
        Assertions.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);
    });
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) Result(org.apache.dubbo.rpc.Result) Test(org.junit.jupiter.api.Test)

Example 45 with Result

use of org.apache.dubbo.rpc.Result in project brave by openzipkin.

the class ITTracingFilter_Consumer method customParser.

@Test
public void customParser() {
    Tag<DubboResponse> javaValue = new Tag<DubboResponse>("dubbo.result_value") {

        @Override
        protected String parseValue(DubboResponse input, TraceContext context) {
            Result result = input.result();
            if (result == null)
                return null;
            return String.valueOf(result.getValue());
        }
    };
    RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).clientResponseParser((res, context, span) -> {
        RpcResponseParser.DEFAULT.parse(res, context, span);
        if (res instanceof DubboResponse) {
            javaValue.tag((DubboResponse) res, span);
        }
    }).build();
    init().setRpcTracing(rpcTracing);
    String javaResult = client.get().sayHello("jorge");
    assertThat(testSpanHandler.takeRemoteSpan(CLIENT).tags()).containsEntry("dubbo.result_value", javaResult);
}
Also used : ExtensionLoader(org.apache.dubbo.common.extension.ExtensionLoader) RpcResponseParser(brave.rpc.RpcResponseParser) RpcContext(org.apache.dubbo.rpc.RpcContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ALWAYS_SAMPLE(brave.sampler.Sampler.ALWAYS_SAMPLE) AssertableCallback(brave.test.util.AssertableCallback) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) RpcRuleSampler(brave.rpc.RpcRuleSampler) After(org.junit.After) ReferenceConfig(org.apache.dubbo.config.ReferenceConfig) RpcRequestMatchers.methodEquals(brave.rpc.RpcRequestMatchers.methodEquals) RpcRequestMatchers.serviceEquals(brave.rpc.RpcRequestMatchers.serviceEquals) Before(org.junit.Before) DubboBootstrap(org.apache.dubbo.config.bootstrap.DubboBootstrap) CLIENT(brave.Span.Kind.CLIENT) Test(org.junit.Test) RpcException(org.apache.dubbo.rpc.RpcException) TraceContext(brave.propagation.TraceContext) Result(org.apache.dubbo.rpc.Result) Clock(brave.Clock) RpcTracing(brave.rpc.RpcTracing) MutableSpan(brave.handler.MutableSpan) NEVER_SAMPLE(brave.sampler.Sampler.NEVER_SAMPLE) Scope(brave.propagation.CurrentTraceContext.Scope) Tag(brave.Tag) Filter(org.apache.dubbo.rpc.Filter) SamplingFlags(brave.propagation.SamplingFlags) TraceContext(brave.propagation.TraceContext) RpcTracing(brave.rpc.RpcTracing) Tag(brave.Tag) Result(org.apache.dubbo.rpc.Result) Test(org.junit.Test)

Aggregations

Result (org.apache.dubbo.rpc.Result)97 Test (org.junit.jupiter.api.Test)74 URL (org.apache.dubbo.common.URL)55 RpcInvocation (org.apache.dubbo.rpc.RpcInvocation)39 Invocation (org.apache.dubbo.rpc.Invocation)33 AsyncRpcResult (org.apache.dubbo.rpc.AsyncRpcResult)31 AppResponse (org.apache.dubbo.rpc.AppResponse)28 Invoker (org.apache.dubbo.rpc.Invoker)27 RpcException (org.apache.dubbo.rpc.RpcException)22 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)7 RpcContext (org.apache.dubbo.rpc.RpcContext)7 BlockMyInvoker (org.apache.dubbo.rpc.support.BlockMyInvoker)6 DemoService (org.apache.dubbo.rpc.support.DemoService)6 List (java.util.List)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Protocol (org.apache.dubbo.rpc.Protocol)5 Person (org.apache.dubbo.rpc.support.Person)5 Method (java.lang.reflect.Method)4 MockProtocol (org.apache.dubbo.rpc.support.MockProtocol)4