Java Code Examples for org.apache.dubbo.rpc.RpcContext

The following examples show how to use org.apache.dubbo.rpc.RpcContext. 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: dubbo-samples   Source File: HelloServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void invokeSayHelloAsync() throws InterruptedException {
    Object result = genericService.$invoke("sayHelloAsync", new String[]{"java.lang.String"}, new Object[]{"world"});
    CountDownLatch latch = new CountDownLatch(1);

    CompletableFuture<String> future = RpcContext.getContext().getCompletableFuture();
    future.whenComplete((value, t) -> {
        System.err.println("invokeSayHelloAsync(whenComplete): " + value);
        Object o = PojoUtils.realize(value, String.class);
        Assert.assertEquals("sayHelloAsync: world", o);
        latch.countDown();
    });

    System.err.println("invokeSayHelloAsync(return): " + result);
    Assert.assertNull(result);

    latch.await(7000, TimeUnit.MILLISECONDS);
}
 
Example 2
Source Project: apm-agent-java   Source File: ApacheMonitorFilterAdvice.java    License: 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 3
Source Project: apm-agent-java   Source File: DubboTestApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String asyncByAsyncContext(String arg1) {
    final AsyncContext asyncContext = RpcContext.startAsync();
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            doSomething();
            if ("error".equals(arg1)) {
                asyncContext.write(new BizException("error"));
                return;
            }
            asyncContext.write(arg1);
        }
    });
    return null;
}
 
Example 4
@Test
public void testAsync() throws Exception {
    String arg = "hello";
    DubboTestApi dubboTestApi = getDubboTestApi();
    String ret = dubboTestApi.async(arg);
    assertThat(ret).isNull();
    Future<Object> future = RpcContext.getContext().getFuture();
    assertThat(future).isNotNull();
    ret = (String) future.get();
    assertThat(ret).isEqualTo(arg);

    Transaction transaction = reporter.getFirstTransaction(1000);
    validateDubboTransaction(transaction, DubboTestApi.class, "async");

    assertThat(reporter.getFirstSpan(500)).isNotNull();
    List<Span> spans = reporter.getSpans();
    assertThat(spans.size()).isEqualTo(1);
}
 
Example 5
Source Project: sofa-tracer   Source File: DubboSofaTracerFilter.java    License: 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 6
Source Project: sofa-tracer   Source File: DubboSofaTracerFilter.java    License: Apache License 2.0 6 votes vote down vote up
private void appendRpcClientSpanTags(Invoker<?> invoker, SofaTracerSpan sofaTracerSpan) {
    if (sofaTracerSpan == null) {
        return;
    }
    RpcContext rpcContext = RpcContext.getContext();
    Map<String, String> tagsStr = sofaTracerSpan.getTagsWithStr();
    tagsStr.put(Tags.SPAN_KIND.getKey(), spanKind(rpcContext));
    String protocol = rpcContext.getUrl().getProtocol();
    tagsStr.put(CommonSpanTags.PROTOCOL, protocol == null ? BLANK : protocol);
    String service = invoker.getInterface().getName();
    tagsStr.put(CommonSpanTags.SERVICE, service == null ? BLANK : service);
    String methodName = rpcContext.getMethodName();
    tagsStr.put(CommonSpanTags.METHOD, methodName == null ? BLANK : methodName);
    tagsStr.put(CommonSpanTags.CURRENT_THREAD_NAME, Thread.currentThread().getName());
    String app = rpcContext.getUrl().getParameter(CommonConstants.APPLICATION_KEY);
    tagsStr.put(CommonSpanTags.LOCAL_APP, app == null ? BLANK : app);
    tagsStr.put(CommonSpanTags.REMOTE_HOST, rpcContext.getRemoteHost());
    tagsStr.put(CommonSpanTags.REMOTE_PORT, String.valueOf(rpcContext.getRemotePort()));
    tagsStr.put(CommonSpanTags.LOCAL_HOST, rpcContext.getLocalHost());
}
 
Example 7
@Test
public void testAttachment() {
    ApplicationConfig application = new ApplicationConfig();
    application.setName("api-generic-consumer");
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setUrl("dubbo://192.168.56.1:20880/org.apache.dubbo.samples.basic.api.DemoService");
    reference.setVersion("1.0.0");
    reference.setTimeout(2000);
    reference.setGeneric(true);
    reference.setApplication(application);
    reference.setInterface("com.jiuyescm.account.api.IUserService");
    GenericService genericService = reference.get();
    RpcContext.getContext().setAttachment("test.ningyu","this is attachmentValue");
    Object obj = genericService.$invoke("sayHello", new String[]{String.class.getName()}, new String[]{"ningyu"});
    String json = JsonUtils.toJson(obj);
    System.out.println(json);
}
 
Example 8
Source Project: dubbo-samples   Source File: HelloServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void invokeSayHello() throws InterruptedException {
    Object result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"world"});
    CountDownLatch latch = new CountDownLatch(1);

    CompletableFuture<String> future = RpcContext.getContext().getCompletableFuture();
    future.whenComplete((value, t) -> {
        System.err.println("invokeSayHello(whenComplete): " + value);
        Object o = PojoUtils.realize(value, String.class);
        Assert.assertEquals("sayHello: world", o);
        latch.countDown();
    });

    System.err.println("invokeSayHello(return): " + result);
    Assert.assertNull(result);

    latch.await(7000, TimeUnit.MILLISECONDS);
}
 
Example 9
Source Project: dubbo-samples   Source File: AsyncConsumer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/async-consumer.xml"});
        context.start();

        final AsyncService asyncService = (AsyncService) context.getBean("asyncService");

//        asyncService.sayHello("world");
//        CompletableFuture<String> helloFuture = RpcContext.getContext().getCompletableFuture();
//        helloFuture.whenComplete((retValue, exception) -> {
//            if (exception == null) {
//                System.out.println(retValue);
//            } else {
//                exception.printStackTrace();
//            }
//        });
//
        asyncService.sayHelloTimeout("timeout world");
        CompletableFuture<String> helloFuture = RpcContext.getContext().getCompletableFuture();
        helloFuture.get();

        System.in.read();
    }
 
Example 10
Source Project: dubbo-samples   Source File: AsyncServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String sayHello(String name) {
    AsyncContext asyncContext = RpcContext.startAsync();
    logger.info("sayHello start");

    new Thread(() -> {
        asyncContext.signalContextSwitch();
        logger.info("Attachment from consumer: " + RpcContext.getContext().getAttachment("consumer-key1"));
        logger.info("async start");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        asyncContext.write("Hello " + name + ", response from provider.");
        logger.info("async end");
    }).start();

    logger.info("sayHello end");
    return "hello, " + name;
}
 
Example 11
Source Project: dubbo-samples   Source File: AsyncConsumer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/async-consumer.xml");
    context.start();

    AsyncService asyncService = context.getBean("asyncService", AsyncService.class);
    RpcContext.getContext().setAttachment("consumer-key1", "consumer-value1");

    CompletableFuture<String> future = asyncService.sayHello("async call request");
    RpcContext savedServerContext = RpcContext.getServerContext();
    CountDownLatch latch = new CountDownLatch(1);
    future.whenComplete((v, t) -> {
        System.out.println((String) savedServerContext.getAttachment("server-key1"));
        if (t != null) {
            logger.warn("Exception: ", t);
        } else {
            logger.info("Response: " + v);
        }
        latch.countDown();
    });

    logger.info("Executed before response returns");
    latch.await();
}
 
Example 12
Source Project: dubbo-samples   Source File: AsyncServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<String> sayHello(String name) {
    RpcContext savedContext = RpcContext.getContext();
    RpcContext savedServerContext = RpcContext.getServerContext();
    return CompletableFuture.supplyAsync(() -> {
        String received = (String) savedContext.getAttachment("consumer-key1");
        logger.info("consumer-key1 from attachment: " + received);
        savedServerContext.setAttachment("server-key1", "server-" + received);

        received = (String) savedContext.getAttachment("filters");
        logger.info("filters from attachment: " + received);
        savedServerContext.setAttachment("filters", received);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "async response from provider.";
    });
}
 
Example 13
Source Project: dubbo-samples   Source File: LegacyBlockFilter.java    License: 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 14
Source Project: dubbo-samples   Source File: AsyncServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    RpcContext.getContext().setAttachment("consumer-key1", "consumer-value1");

    CompletableFuture<String> future = asyncService.sayHello("async call request");
    CountDownLatch latch = new CountDownLatch(1);
    future.whenComplete((v, t) -> {
        if (t != null) {
            t.printStackTrace();
            Assert.fail();
        } else {
            assertEquals("async response from provider.", v);
        }
        latch.countDown();
    });

    latch.await();
}
 
Example 15
Source Project: skywalking   Source File: DubboInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    dubboInterceptor = new DubboInterceptor();

    PowerMockito.mockStatic(RpcContext.class);

    when(invoker.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:20880/org.apache.skywalking.apm.test.TestDubboService"));
    when(invocation.getMethodName()).thenReturn("test");
    when(invocation.getParameterTypes()).thenReturn(new Class[] {String.class});
    when(invocation.getArguments()).thenReturn(new Object[] {"abc"});
    PowerMockito.when(RpcContext.getContext()).thenReturn(rpcContext);
    when(rpcContext.isConsumerSide()).thenReturn(true);
    allArguments = new Object[] {
        invoker,
        invocation
    };
    argumentTypes = new Class[] {
        invoker.getClass(),
        invocation.getClass()
    };
    Config.Agent.SERVICE_NAME = "DubboTestCases-APP";
}
 
Example 16
Source Project: pinpoint   Source File: ApacheDubboProviderInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private String getLocalHost(RpcContext rpcContext) {
    // Pinpoint finds caller - callee relation by matching caller's end point and callee's acceptor host.
    // https://github.com/naver/pinpoint/issues/1395
    // @Nullable
    final String localHost = NetworkUtils.getLocalHost();
    if (localHost == null) {
        logger.debug("NetworkUtils.getLocalHost() is null");
    }
    final String rpcContextLocalhost = rpcContext.getLocalHost();
    if (rpcContextLocalhost == null) {
        logger.debug("rpcContext.getLocalHost() is null");
    }
    if (localHost == null && rpcContextLocalhost == null) {
        logger.debug("localHost == null && rpcContextLocalhost == null");
        return null;
    }
    if (localHost == null) {
        logger.debug("return rpcContextLocalhost:{}", rpcContextLocalhost);
        return rpcContextLocalhost;
    }
    if (localHost.equals(rpcContextLocalhost)) {
        return rpcContext.getLocalAddressString();
    } else {
        return localHost + ":" + rpcContext.getLocalPort();
    }
}
 
Example 17
Source Project: brave   Source File: TestServer.java    License: Apache License 2.0 6 votes vote down vote up
TestServer(Propagation.Factory propagationFactory, ApplicationConfig application) {
  extractor = propagationFactory.get().extractor(Map::get);
  linkLocalIp = Platform.get().linkLocalIp();
  if (linkLocalIp != null) {
    // avoid dubbo's logic which might pick docker ip
    System.setProperty(CommonConstants.DUBBO_IP_TO_BIND, linkLocalIp);
    System.setProperty(Constants.DUBBO_IP_TO_REGISTRY, linkLocalIp);
  }
  service = new ServiceConfig<>();
  service.setApplication(application);
  service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
  service.setProtocol(new ProtocolConfig("dubbo", PickUnusedPort.get()));
  service.setInterface(GreeterService.class);
  service.setRef((method, parameterTypes, args) -> {
    requestQueue.add(extractor.extract(RpcContext.getContext().getAttachments()));
    return args[0];
  });
}
 
Example 18
Source Project: log-trace-spring-boot   Source File: EchoServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String echo(String message) {
    log.info("dubbo message={}", message);
    Object[] arguments = RpcContext.getContext().getArguments();
    log.info("dubbo log-trace-dubbo-consumers-demo={}", arguments);
    return "[echo version = \"1.0.0\"] Hello, " + message;
}
 
Example 19
@Test
public void testInvokeApplicationKey() {
    Invoker invoker = mock(Invoker.class);
    Invocation invocation = mock(Invocation.class);
    URL url = URL.valueOf("test://test:111/test?application=serviceA");
    when(invoker.getUrl()).thenReturn(url);

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

    String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
    assertEquals("serviceA", application);
}
 
Example 20
Source Project: dubbo-samples   Source File: AttachmentServiceIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAttachment() {
    RpcContext.getContext().setAttachment("index", "1");
    String result = service.sayHello("dubbo");
    Assert.assertTrue(result.startsWith("Hello dubbo"));
    Assert.assertTrue(result.endsWith("index: 1"));
    RpcContext.getContext().setAttachment("index", "2");
    result = service.sayHello("dubbo");
    Assert.assertTrue(result.endsWith("index: 2"));
    result = service.sayHello("dubbo");
    Assert.assertTrue(result.endsWith("index: null"));
}
 
Example 21
Source Project: brave   Source File: DubboParser.java    License: Apache License 2.0 5 votes vote down vote up
static boolean parseRemoteIpAndPort(Span span) {
  RpcContext rpcContext = RpcContext.getContext();
  InetSocketAddress remoteAddress = rpcContext.getRemoteAddress();
  if (remoteAddress == null) return false;
  return span.remoteIpAndPort(
      Platform.get().getHostString(remoteAddress),
      remoteAddress.getPort()
  );
}
 
Example 22
Source Project: dubbo-registry-nacos   Source File: DefaultService.java    License: Apache License 2.0 5 votes vote down vote up
public String sayName(String name) {
    RpcContext rpcContext = RpcContext.getContext();
    return String.format("Service [name :%s , port : %d] %s(\"%s\") : Hello,%s",
            serviceName,
            rpcContext.getLocalPort(),
            rpcContext.getMethodName(),
            name,
            name);
}
 
Example 23
Source Project: apm-agent-java   Source File: AsyncCallbackCreatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Result result, Throwable t) {
    AbstractSpan<?> span = (AbstractSpan<?>) RpcContext.getContext().get(DubboTraceHelper.SPAN_KEY);
    if (span != null) {
        try {
            RpcContext.getContext().remove(DubboTraceHelper.SPAN_KEY);
            span.captureException(t);
            if (result != null) {
                span.captureException(result.getException());
            }
        } finally {
            span.end();
        }
    }
}
 
Example 24
@Test
public void testAsyncException() throws Exception {
    DubboTestApi dubboTestApi = getDubboTestApi();
    String arg = "error";
    try {
        dubboTestApi.async(arg);
        Future<Object> future = RpcContext.getContext().getFuture();
        assertThat(future).isNotNull();
        future.get();
    } catch (Exception e) {
        // exception from Future will be wrapped as RpcException by dubbo implementation
        assertThat(e.getCause() instanceof BizException).isTrue();
        Transaction transaction = reporter.getFirstTransaction(1000);
        assertThat(reporter.getFirstSpan(500)).isNotNull();
        List<Span> spans = reporter.getSpans();
        assertThat(spans.size()).isEqualTo(1);

        List<ErrorCapture> errors = reporter.getErrors();
        assertThat(errors.size()).isEqualTo(2);
        for (ErrorCapture error : errors) {
            Throwable t = error.getException();
            assertThat(t instanceof BizException).isTrue();
        }
        return;
    }
    throw new RuntimeException("not ok");
}
 
Example 25
@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 26
@Test
public void testInvokeApplicationKey() {
    Invoker invoker = mock(Invoker.class);
    Invocation invocation = mock(Invocation.class);
    URL url = URL.valueOf("test://test:111/test?application=serviceA");
    when(invoker.getUrl()).thenReturn(url);

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

    String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
    assertEquals("serviceA", application);
}
 
Example 27
@Test
public void testInvokeNullApplicationKey() {
    Invoker invoker = mock(Invoker.class);
    Invocation invocation = mock(Invocation.class);
    URL url = URL.valueOf("test://test:111/test?application=");
    when(invoker.getUrl()).thenReturn(url);

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

    String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
    assertNull(application);
}
 
Example 28
Source Project: dubbo-samples   Source File: GenericCallConsumer.java    License: Apache License 2.0 5 votes vote down vote up
public static void invokeSayHelloAsyncGenericComplex() throws Exception {
    Object result = genericService.$invoke("sayHelloAsyncGenericComplex", new String[]{"java.lang.String"},
            new Object[]{"world"});
    CountDownLatch latch = new CountDownLatch(1);

    CompletableFuture<String> future = RpcContext.getContext().getCompletableFuture();
    future.whenComplete((value, t) -> {
        System.err.println("invokeSayHelloAsyncGenericComplex(whenComplete): " + value);
        latch.countDown();
    });

    System.err.println("invokeSayHelloAsyncGenericComplex(return): " + result);
    latch.await();
}
 
Example 29
Source Project: brave   Source File: ITTracingFilter_Provider.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void createsChildWhenJoinDisabled() {
  tracing = tracingBuilder(NEVER_SAMPLE).supportsJoin(false).build();
  init();

  TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);

  RpcContext.getContext().getAttachments().put("b3", B3SingleFormat.writeB3SingleFormat(parent));
  client.get().sayHello("jorge");

  MutableSpan span = testSpanHandler.takeRemoteSpan(SERVER);
  assertChildOf(span, parent);
  assertThat(span.id()).isNotEqualTo(parent.spanIdString());
}
 
Example 30
Source Project: Sentinel   Source File: DubboAppContextFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeApplicationKey() {
    Invoker invoker = mock(Invoker.class);
    Invocation invocation = mock(Invocation.class);
    URL url = URL.valueOf("test://test:111/test?application=serviceA");
    when(invoker.getUrl()).thenReturn(url);

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

    String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
    assertEquals("serviceA", application);
}