org.apache.dubbo.rpc.Result Java Examples

The following examples show how to use org.apache.dubbo.rpc.Result. 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 File: Resilience4jCircuitBreakerFilter.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    System.out.println("**************** Enter CircuitBreaker ****************");
    long countLong = count.incrementAndGet();
    long start = 0;
    try {
        CircuitBreakerUtils.isCallPermitted(circuitBreaker);
        start = System.nanoTime();
        Result result = invoker.invoke(invocation);
        if (result.hasException()) {
            doThrowException(result.getException(), start);
            return result;
        }
        long durationInNanos = System.nanoTime() - start;
        circuitBreaker.onSuccess(durationInNanos);
        return result;
    } catch (CircuitBreakerOpenException cbo) {

        doCircuitBreakerOpenException(cbo, countLong, breakCount.incrementAndGet());
        throw cbo;
    } catch (Throwable throwable) {
        doThrowException(throwable, start);
        throw throwable;
    }
}
 
Example #2
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterfaceLevelFollowControlAsync() throws InterruptedException {

    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();

    when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
    initFlowRule(DubboUtils.getInterfaceName(invoker));

    Result result1 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("normal", result1.getValue());

    // should fallback because the qps > 1
    Result result2 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("fallback", result2.getValue());

    // sleeping 1000 ms to reset qps
    Thread.sleep(1000);
    Result result3 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("normal", result3.getValue());

    verifyInvocationStructureForCallFinish(invoker, invocation);
}
 
Example #3
Source File: DubboSofaTracerFilter.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    // do not record
    if ("$echo".equals(invocation.getMethodName())) {
        return invoker.invoke(invocation);
    }

    RpcContext rpcContext = RpcContext.getContext();
    // get appName
    if (StringUtils.isBlank(this.appName)) {
        this.appName = SofaTracerConfiguration
            .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
    }
    // get span kind by rpc request type
    String spanKind = spanKind(rpcContext);
    Result result;
    if (spanKind.equals(Tags.SPAN_KIND_SERVER)) {
        result = doServerFilter(invoker, invocation);
    } else {
        result = doClientFilter(rpcContext, invoker, invocation);
    }
    return result;
}
 
Example #4
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvoke() {
    final Invoker invoker = mock(Invoker.class);
    when(invoker.getInterface()).thenReturn(DemoService.class);

    final Invocation invocation = mock(Invocation.class);
    Method method = DemoService.class.getMethods()[0];
    when(invocation.getMethodName()).thenReturn(method.getName());
    when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());

    final Result result = mock(Result.class);
    when(result.hasException()).thenReturn(false);
    when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
        verifyInvocationStructure(invoker, invocation);
        return result;
    });

    filter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #5
Source File: ApacheMonitorFilterAdvice.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onExitFilterInvoke(@Advice.Argument(1) Invocation invocation,
                                      @Advice.Return Result result,
                                      @Nullable @Advice.Local("span") final Span span,
                                      @Advice.Thrown Throwable t,
                                      @Nullable @Advice.Local("transaction") Transaction transaction) {

    RpcContext context = RpcContext.getContext();
    AbstractSpan<?> actualSpan = context.isConsumerSide() ? span : transaction;
    if (actualSpan == null) {
        return;
    }

    actualSpan.deactivate();
    if (result instanceof AsyncRpcResult) {
        AsyncCallbackCreator callbackCreator = asyncCallbackCreatorClassManager.getForClassLoaderOfClass(Result.class);
        if (callbackCreator == null) {
            actualSpan.end();
            return;
        }
        context.set(DubboTraceHelper.SPAN_KEY, actualSpan);
        result.whenCompleteWithContext(callbackCreator.create(actualSpan));
    } else {
        actualSpan.end();
    }
}
 
Example #6
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodFlowControlAsync() {

    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();

    when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
    initFlowRule(consumerFilter.getMethodName(invoker, invocation));
    invokeDubboRpc(false, invoker, invocation);
    invokeDubboRpc(false, invoker, invocation);

    Invocation invocation2 = DubboTestUtil.getDefaultMockInvocationTwo();
    Result result2 = invokeDubboRpc(false, invoker, invocation2);
    verifyInvocationStructureForCallFinish(invoker, invocation2);
    assertEquals("normal", result2.getValue());

    // the method of invocation should be blocked
    Result fallback = invokeDubboRpc(false, invoker, invocation);
    assertEquals("fallback", fallback.getValue());
    verifyInvocationStructureForCallFinish(invoker, invocation);


}
 
Example #7
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeAsync() {

    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();

    when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
    final Result result = mock(Result.class);
    when(result.hasException()).thenReturn(false);
    when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
        verifyInvocationStructureForAsyncCall(invoker, invocation);
         return result;
    });
    consumerFilter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    Context context = ContextUtil.getContext();
    assertNotNull(context);
}
 
Example #8
Source File: LegacyBlockFilter.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext context = RpcContext.getContext();
    String filters = (String) context.getAttachment("filters");
    if (StringUtils.isEmpty(filters)) {
        filters = "";
    }
    filters += " legacy-block-filter";
    context.setAttachment("filters", filters);

    Result result = invoker.invoke(invocation);

    logger.info("This is the default return value: " + result.getValue());

    if (result.hasException()) {
        System.out.println("LegacyBlockFilter: This will only happen when the real exception returns: " + result.getException());
        logger.warn("This will only happen when the real exception returns", result.getException());
    }

    logger.info("LegacyBlockFilter: This msg should not be blocked.");
    return result;
}
 
Example #9
Source File: ITTracingFilter_Provider.java    From brave with Apache License 2.0 6 votes vote down vote up
@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)
      .serverResponseParser((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(SERVER).tags())
      .containsEntry("dubbo.result_value", javaResult);
}
 
Example #10
Source File: ITTracingFilter_Consumer.java    From brave with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeSync() {

    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();

    final Result result = mock(Result.class);
    when(result.hasException()).thenReturn(false);
    when(result.getException()).thenReturn(new Exception());
    when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
        verifyInvocationStructure(invoker, invocation);
        return result;
    });

    consumerFilter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #12
Source File: SentinelDubboConsumerFilterTest.java    From dubbo-sentinel-support with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvoke() {
    final Invoker invoker = mock(Invoker.class);
    when(invoker.getInterface()).thenReturn(DemoService.class);

    final Invocation invocation = mock(Invocation.class);
    Method method = DemoService.class.getMethods()[0];
    when(invocation.getMethodName()).thenReturn(method.getName());
    when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());

    final Result result = mock(Result.class);
    when(result.hasException()).thenReturn(false);
    when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
        verifyInvocationStructure(invoker, invocation);
        return result;
    });

    filter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #13
Source File: FinishSpan.java    From brave with Apache License 2.0 5 votes vote down vote up
static FinishSpan create(TracingFilter filter, DubboRequest request, Result result, Span span) {
  if (request instanceof DubboClientRequest) {
    return new FinishClientSpan(
      span, result, filter.clientHandler, (DubboClientRequest) request);
  }
  return new FinishServerSpan(span, result, filter.serverHandler, (DubboServerRequest) request);
}
 
Example #14
Source File: SentinelDubboProviderFilterTest.java    From dubbo-sentinel-support with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvoke() {
    final String originApplication = "consumerA";

    final Invoker invoker = mock(Invoker.class);
    when(invoker.getInterface()).thenReturn(DemoService.class);

    final Invocation invocation = mock(Invocation.class);
    Method method = DemoService.class.getMethods()[0];
    when(invocation.getMethodName()).thenReturn(method.getName());
    when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
    when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
        .thenReturn(originApplication);

    final Result result = mock(Result.class);
    when(result.hasException()).thenReturn(false);
    when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
        verifyInvocationStructure(originApplication, invoker, invocation);
        return result;
    });

    filter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #15
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private Result invokeDubboRpc(boolean exception, Invoker invoker, Invocation invocation) {
    Result result = null;
    InvokeMode invokeMode = RpcUtils.getInvokeMode(invoker.getUrl(), invocation);
    if (InvokeMode.SYNC == invokeMode) {
        result = exception ? new AppResponse(new Exception("error")) : new AppResponse("normal");
    } else {
        result = exception ? AsyncRpcResult.newDefaultAsyncResult(new Exception("error"), invocation) : AsyncRpcResult.newDefaultAsyncResult("normal", invocation);
    }
    when(invoker.invoke(invocation)).thenReturn(result);
    return consumerFilter.invoke(invoker, invocation);
}
 
Example #16
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void initFallback() {
    DubboFallbackRegistry.setConsumerFallback(new DubboFallback() {
        @Override
        public Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex) {
            boolean async = RpcUtils.isAsync(invoker.getUrl(), invocation);
            Result fallbackResult = null;
            fallbackResult = AsyncRpcResult.newDefaultAsyncResult("fallback", invocation);
            return fallbackResult;
        }
    });
}
 
Example #17
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testDegradeSync() throws InterruptedException {

    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
    initDegradeRule(DubboUtils.getInterfaceName(invoker));

    Result result = invokeDubboRpc(false, invoker, invocation);
    verifyInvocationStructureForCallFinish(invoker, invocation);
    assertEquals("normal", result.getValue());

    // inc the clusterNode's exception to trigger the fallback
    for (int i = 0; i < 5; i++) {
        invokeDubboRpc(true, invoker, invocation);
        verifyInvocationStructureForCallFinish(invoker, invocation);
    }

    Result result2 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("fallback", result2.getValue());

    // sleeping 1000 ms to reset exception
    Thread.sleep(1000);
    Result result3 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("normal", result3.getValue());

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #18
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testDegradeAsync() throws InterruptedException {

    Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
    Invoker invoker = DubboTestUtil.getDefaultMockInvoker();

    when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
    initDegradeRule(DubboUtils.getInterfaceName(invoker));

    Result result = invokeDubboRpc(false, invoker, invocation);
    verifyInvocationStructureForCallFinish(invoker, invocation);
    assertEquals("normal", result.getValue());


    // inc the clusterNode's exception to trigger the fallback
    for (int i = 0; i < 5; i++) {
        invokeDubboRpc(true, invoker, invocation);
        verifyInvocationStructureForCallFinish(invoker, invocation);
    }

    Result result2 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("fallback", result2.getValue());

    // sleeping 1000 ms to reset exception
    Thread.sleep(1000);
    Result result3 = invokeDubboRpc(false, invoker, invocation);
    assertEquals("normal", result3.getValue());

    Context context = ContextUtil.getContext();
    assertNull(context);
}
 
Example #19
Source File: DubboAppContextFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
    if (application != null) {
        RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
    }
    return invoker.invoke(invocation);
}
 
Example #20
Source File: OnResponseThrowableAsyncFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
    System.out.println("onResponse received value : " + appResponse.getValue());
    if (invocation != null) {
        throw new RuntimeException("Exception from onResponse");
    }
}
 
Example #21
Source File: FinishSpan.java    From brave with Apache License 2.0 5 votes vote down vote up
static void finish(TracingFilter filter,
  DubboRequest request, @Nullable Result result, @Nullable Throwable error, Span span) {
  if (request instanceof RpcClientRequest) {
    filter.clientHandler.handleReceive(
      new DubboClientResponse((DubboClientRequest) request, result, error), span);
  } else {
    filter.serverHandler.handleSend(
      new DubboServerResponse((DubboServerRequest) request, result, error), span);
  }
}
 
Example #22
Source File: DubboClientResponse.java    From brave with Apache License 2.0 5 votes vote down vote up
DubboClientResponse(
  DubboClientRequest request, @Nullable Result result, @Nullable Throwable error) {
  if (request == null) throw new NullPointerException("request == null");
  this.request = request;
  this.result = result;
  this.error = error;
}
 
Example #23
Source File: ThrowableAsyncFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (invocation != null) {
        throw new RuntimeException("exception before invoke()");
    }
    return invoker.invoke(invocation);
}
 
Example #24
Source File: DubboServerResponse.java    From brave with Apache License 2.0 5 votes vote down vote up
DubboServerResponse(
  DubboServerRequest request, @Nullable Result result, @Nullable Throwable error) {
  if (request == null) throw new NullPointerException("request == null");
  this.request = request;
  this.result = result;
  this.error = error;
}
 
Example #25
Source File: FinishSpanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void create_error_but_null_result_value_DubboServerRequest() {
  Span span = tracing.tracer().nextSpan().kind(SERVER).start();

  Throwable error = new RuntimeException("melted");
  FinishSpan.create(filter, serverRequest, mock(Result.class), span)
      .accept(null, error);

  testSpanHandler.takeRemoteSpanWithError(SERVER, error);
}
 
Example #26
Source File: DubboInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) throws Throwable {
    Result result = (Result) ret;
    if (result != null && result.getException() != null) {
        dealException(result.getException());
    }

    ContextManager.stopSpan();
    return ret;
}
 
Example #27
Source File: AsyncPostprocessFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext context = RpcContext.getContext();
    String filters = (String) context.getAttachment("filters");
    if (StringUtils.isEmpty(filters)) {
        filters = "";
    }
    filters += " async-post-process-filter";
    context.setAttachment("filters", filters);

    return invoker.invoke(invocation);
}
 
Example #28
Source File: BirdExceptionFilter.java    From bird-java with MIT License 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    try {
        return invoker.invoke(invocation);
    } catch (RuntimeException e) {
        logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()
                + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
        throw e;
    }
}
 
Example #29
Source File: Resilience4jRateLimiterFilter.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    try {
        System.out.println("**************** Enter RateLimiter ****************");
        RateLimiter.waitForPermission(rateLimiter);
        return invoker.invoke(invocation);
    } catch (RequestNotPermitted rnp) {
        System.err.println("---------------- Rate Limiter! Try it later! ----------------");
        throw rnp;
    } catch (Throwable throwable) {
        System.err.println("........" + throwable.getMessage());
        throw throwable;
    }
}
 
Example #30
Source File: FinishSpanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void create_error_but_null_result_value_DubboClientRequest() {
  Span span = tracing.tracer().nextSpan().kind(CLIENT).start();

  Throwable error = new RuntimeException("melted");
  FinishSpan.create(filter, clientRequest, mock(Result.class), span)
      .accept(null, error);

  testSpanHandler.takeRemoteSpanWithError(CLIENT, error);
}