org.apache.dubbo.rpc.RpcContext Java Examples
The following examples show how to use
org.apache.dubbo.rpc.RpcContext.
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: LegacyBlockFilter.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #2
Source File: DubboSofaTracerFilter.java From sofa-tracer with Apache License 2.0 | 6 votes |
@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 #3
Source File: AsyncServiceIT.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #4
Source File: DubboSofaTracerFilter.java From sofa-tracer with Apache License 2.0 | 6 votes |
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 #5
Source File: ApacheDubboInstrumentationTest.java From apm-agent-java with Apache License 2.0 | 6 votes |
@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 #6
Source File: DubboTestApiImpl.java From apm-agent-java with Apache License 2.0 | 6 votes |
@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 #7
Source File: GenericServiceTest.java From jmeter-plugins-for-apache-dubbo with Apache License 2.0 | 6 votes |
@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 File: ApacheMonitorFilterAdvice.java From apm-agent-java with Apache License 2.0 | 6 votes |
@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 #9
Source File: HelloServiceIT.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #10
Source File: AsyncServiceImpl.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #11
Source File: AsyncConsumer.java From dubbo-samples with Apache License 2.0 | 6 votes |
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 File: DubboInterceptorTest.java From skywalking with Apache License 2.0 | 6 votes |
@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 #13
Source File: ApacheDubboProviderInterceptor.java From pinpoint with Apache License 2.0 | 6 votes |
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 #14
Source File: TestServer.java From brave with Apache License 2.0 | 6 votes |
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 #15
Source File: AsyncServiceImpl.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #16
Source File: AsyncConsumer.java From dubbo-samples with Apache License 2.0 | 6 votes |
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 #17
Source File: HelloServiceIT.java From dubbo-samples with Apache License 2.0 | 6 votes |
@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 #18
Source File: BasicConsumer.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-demo-consumer.xml"); context.start(); DemoService demoService = context.getBean("demoService", DemoService.class); DemoService2 demoService2 = context.getBean("demoService2", DemoService2.class); RpcContext.getContext().setAttachment(TAG_KEY, "tag1"); String hello = demoService.sayHello("world"); System.out.println(hello); RpcContext.getContext().setAttachment(FORCE_USE_TAG, "true"); RpcContext.getContext().setAttachment(TAG_KEY, "tag2"); String hello2 = demoService2.sayHello("world again"); System.out.println(hello2); }
Example #19
Source File: DemoServiceIT.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Test public void testDemoService2() throws Exception { for (int i = 0; i < 10; i++) { RpcContext.getContext().setAttachment(FORCE_USE_TAG, "true"); RpcContext.getContext().setAttachment(TAG_KEY, "tag2"); Assert.assertTrue(demoService.sayHello("world").contains("20880")); } }
Example #20
Source File: DemoServiceIT.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Test public void testDemoService1() throws Exception { for (int i = 0; i < 10; i++) { RpcContext.getContext().setAttachment(FORCE_USE_TAG, "true"); RpcContext.getContext().setAttachment(TAG_KEY, "tag1"); Assert.assertTrue(demoService.sayHello("world").contains("20881")); } }
Example #21
Source File: DemoServiceIT.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Test public void testDemoService1() throws Exception { for (int i = 0; i < 10; i++) { RpcContext.getContext().setAttachment(FORCE_USE_TAG, "true"); RpcContext.getContext().setAttachment(TAG_KEY, "tag1"); Assert.assertTrue(demoService.sayHello("world").contains("20881")); } }
Example #22
Source File: GenericCallConsumer.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static 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); latch.countDown(); }); System.err.println("invokeSayHello(return): " + result); latch.await(); }
Example #23
Source File: DemoServiceImpl.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Override public int echoI32(int arg) throws TException { Map<String, String> attachments = RpcContext.getContext().getAttachments(); String parm = (String) attachments.get("parm"); System.out.println("parm:" + parm); return arg; }
Example #24
Source File: ApacheDubboProviderInterceptor.java From pinpoint with Apache License 2.0 | 5 votes |
/** * clear {@link org.apache.dubbo.rpc.RpcContext#getAttachments()} trace header. * you should to know,since apache dubbo 2.6.2 version. * {@link org.apache.dubbo.rpc.protocol.AbstractInvoker#invoke(org.apache.dubbo.rpc.Invocation)} * will force put {@link org.apache.dubbo.rpc.RpcContext#getAttachments()} to current Invocation * replace origin invocation.addAttachmentsIfAbsent(context) method; * to imagine if application(B) methodB called by application(A), application(B) is dubbo provider, methodB call next dubbo application(C). * when application(C) received trace header is overwrite by application(B) received trace header. * * @param rpcContext */ private void clearAttachments(RpcContext rpcContext) { Map<String, String> attachments = rpcContext.getAttachments(); if (attachments != null) { attachments.remove(ApacheDubboConstants.META_TRANSACTION_ID); attachments.remove(ApacheDubboConstants.META_SPAN_ID); attachments.remove(ApacheDubboConstants.META_PARENT_SPAN_ID); attachments.remove(ApacheDubboConstants.META_PARENT_APPLICATION_TYPE); attachments.remove(ApacheDubboConstants.META_PARENT_APPLICATION_NAME); attachments.remove(ApacheDubboConstants.META_FLAGS); attachments.remove(ApacheDubboConstants.META_HOST); } }
Example #25
Source File: DemoServiceImpl.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Override public String sayHello(String name, long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); }
Example #26
Source File: EchoServiceImpl.java From log-trace-spring-boot with Apache License 2.0 | 5 votes |
@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 #27
Source File: DemoServiceImpl.java From dubbo-samples with Apache License 2.0 | 5 votes |
@Override public String sayHello(String name) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); }
Example #28
Source File: AsyncPostprocessFilter.java From dubbo-samples with Apache License 2.0 | 5 votes |
@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 #29
Source File: ApacheDubboProviderInterceptor.java From pinpoint with Apache License 2.0 | 5 votes |
private void recordRequest(SpanRecorder recorder, Object target, Object[] args) { final RpcInvocation invocation = (RpcInvocation) args[0]; final RpcContext rpcContext = RpcContext.getContext(); // Record rpc name, client address, server address. recorder.recordRpcName(invocation.getInvoker().getInterface().getSimpleName() + ":" + invocation.getMethodName()); recorder.recordEndPoint(rpcContext.getLocalAddressString()); if (rpcContext.getRemoteHost() != null) { recorder.recordRemoteAddress(rpcContext.getRemoteAddressString()); } else { recorder.recordRemoteAddress("Unknown"); } // If this transaction did not begin here, record parent(client who sent this request) information if (!recorder.isRoot()) { final String parentApplicationName = invocation.getAttachment(ApacheDubboConstants.META_PARENT_APPLICATION_NAME); if (parentApplicationName != null) { final short parentApplicationType = NumberUtils.parseShort(invocation.getAttachment(ApacheDubboConstants.META_PARENT_APPLICATION_TYPE), ServiceType.UNDEFINED.getCode()); recorder.recordParentApplication(parentApplicationName, parentApplicationType); final String host = invocation.getAttachment(ApacheDubboConstants.META_HOST); if (host != null) { recorder.recordAcceptorHost(host); } else { // old version fallback final String estimatedLocalHost = getLocalHost(rpcContext); if (estimatedLocalHost != null) { recorder.recordAcceptorHost(estimatedLocalHost); } } } } //clear attachments this.clearAttachments(rpcContext); }
Example #30
Source File: AsyncConsumer.java From dubbo-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/async-consumer.xml"); context.start(); RpcContext.getContext().setAttachment("consumer-key1", "consumer-value1"); AsyncService asyncService = context.getBean("asyncService", AsyncService.class); System.out.println(asyncService.sayHello("async call request")); }