com.alibaba.dubbo.rpc.RpcContext Java Examples

The following examples show how to use com.alibaba.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: ImplicitCallBackTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_Async_Future_Multi() throws Exception {
    initOrResetUrl(true);
    destroyService();
    exportService();
    referService();
    
    int requestId1 = 1;
    Person ret = demoProxy.get(requestId1);
    Assert.assertEquals(null, ret);
    Future<Person> p1Future = RpcContext.getContext().getFuture();
    
    int requestId2 = 1;
    Person ret2 = demoProxy.get(requestId2);
    Assert.assertEquals(null, ret2);
    Future<Person> p2Future = RpcContext.getContext().getFuture();
    
    ret = p1Future.get(1000, TimeUnit.MICROSECONDS);
    ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS);
    Assert.assertEquals(requestId1, ret.getId());
    Assert.assertEquals(requestId2, ret.getId());
    destroyService();
}
 
Example #2
Source File: MonitorFilter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
        RpcContext context = RpcContext.getContext(); // 提供方必须在invoke()之前获取context信息
        long start = System.currentTimeMillis(); // 记录起始时间戮
        getConcurrent(invoker, invocation).incrementAndGet(); // 并发计数
        try {
            Result result = invoker.invoke(invocation); // 让调用链往下执行
            collect(invoker, invocation, result, context, start, false);
            return result;
        } catch (RpcException e) {
            collect(invoker, invocation, null, context, start, true);
            throw e;
        } finally {
            getConcurrent(invoker, invocation).decrementAndGet(); // 并发计数
        }
    } else {
        return invoker.invoke(invocation);
    }
}
 
Example #3
Source File: MonitorFilterTest.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilter() throws Exception {
    MonitorFilter monitorFilter = new MonitorFilter();
    monitorFilter.setMonitorFactory(monitorFactory);
    Invocation invocation = new RpcInvocation("aaa", new Class<?>[0], new Object[0]);
    RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345);
    monitorFilter.invoke(serviceInvoker, invocation);
    while (lastStatistics == null) {
        Thread.sleep(10);
    }
    Assert.assertEquals("abc", lastStatistics.getParameter(MonitorService.APPLICATION));
    Assert.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(MonitorService.INTERFACE));
    Assert.assertEquals("aaa", lastStatistics.getParameter(MonitorService.METHOD));
    Assert.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER));
    Assert.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress());
    Assert.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER));
    Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0));
    Assert.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0));
    Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0));
    Assert.assertEquals(invocation, lastInvocation);
}
 
Example #4
Source File: DubboSofaTracerFilter.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
/**
 * set rpc client span tags
 * @param invoker
 * @param sofaTracerSpan
 */
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(Constants.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: CompensablePrimaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Result providerInvoke(Invoker<?> invoker, Invocation invocation) throws RpcException, RemotingException {
	String interfaceClazz = RpcContext.getContext().getUrl().getServiceInterface();

	boolean participantFlag = TransactionParticipant.class.getName().equals(interfaceClazz);
	boolean xaResourceFlag = XAResource.class.getName().equals(interfaceClazz);
	boolean coordinatorFlag = RemoteCoordinator.class.getName().equals(interfaceClazz);

	if (participantFlag == false && xaResourceFlag == false && coordinatorFlag == false) {
		return this.providerInvokeForSVC(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_RESOURCE_START)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_IDENTIFIER)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_APPLICATION)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTEADDR)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTENODE)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else {
		return this.providerInvokeForTCC(invoker, invocation);
	}
}
 
Example #6
Source File: ExceptionFilterTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);
    
    EasyMock.replay(logger, invoker);
    
    try {
        exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
        assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
}
 
Example #7
Source File: ConsumerContextFilter.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext.getContext()
            .setInvoker(invoker)
            .setInvocation(invocation)
            .setLocalAddress(NetUtils.getLocalHost(), 0)
            .setRemoteAddress(invoker.getUrl().getHost(), 
                              invoker.getUrl().getPort());
    if (invocation instanceof RpcInvocation) {
        ((RpcInvocation)invocation).setInvoker(invoker);
    }
    try {
        return invoker.invoke(invocation);
    } finally {
        RpcContext.getContext().clearAttachments();
    }
}
 
Example #8
Source File: HessianProtocolTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericInvokeWithRpcContext() {
    RpcContext.getContext().setAttachment("myContext", "123");

    HessianServiceImpl server = new HessianServiceImpl();
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    URL url = URL.valueOf("hessian://127.0.0.1:5342/" + HessianService.class.getName() + "?version=1.0.0");
    Exporter<HessianService> exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url));
    Invoker<GenericService> invoker = protocol.refer(GenericService.class, url);
    GenericService client = proxyFactory.getProxy(invoker, true);
    String result = (String) client.$invoke("context", new String[]{"java.lang.String"}, new Object[]{"haha"});
    Assert.assertEquals("Hello, haha context, 123", result);
    invoker.destroy();
    exporter.unexport();
}
 
Example #9
Source File: ContextFilterTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSetContext() {
    invocation = EasyMock.createMock(Invocation.class);
    EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes();
    EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
    EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
    EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes();
    EasyMock.replay(invocation);
    invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setValue("High");
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    contextFilter.invoke(invoker, invocation);
    assertNull(RpcContext.getContext().getInvoker());
}
 
Example #10
Source File: AsyncConsumer.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
    context.start();
    
    final AsyncService asyncService = (AsyncService)context.getBean("asyncService");
    
    Future<String> f = RpcContext.getContext().asyncCall(new Callable<String>() {
        public String call() throws Exception {
            return asyncService.sayHello("async call request");
        }
    });
    
    System.out.println("async call ret :" + f.get());
    
    RpcContext.getContext().asyncCall(new Runnable() {
        public void run() {
            asyncService.sayHello("oneway call request1");
            asyncService.sayHello("oneway call request2");
        }
    });
    
    System.in.read();
}
 
Example #11
Source File: TestServer.java    From brave with Apache License 2.0 6 votes vote down vote up
TestServer(Propagation.Factory propagationFactory) {
  extractor = propagationFactory.get().extractor(Map::get);
  linkLocalIp = Platform.get().linkLocalIp();
  if (linkLocalIp != null) {
    // avoid dubbo's logic which might pick docker ip
    System.setProperty(Constants.DUBBO_IP_TO_BIND, linkLocalIp);
    System.setProperty(Constants.DUBBO_IP_TO_REGISTRY, linkLocalIp);
  }
  service = new ServiceConfig<>();
  service.setApplication(new ApplicationConfig("bean-provider"));
  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 #12
Source File: SimpleRegistryService.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public void subscribe(URL url, NotifyListener listener) {
    if (getUrl().getPort() == 0) {
        URL registryUrl = RpcContext.getContext().getUrl();
        if (registryUrl != null && registryUrl.getPort() > 0
        		&& RegistryService.class.getName().equals(registryUrl.getPath())) {
            super.setUrl(registryUrl);
            super.register(registryUrl);
        }
    }
    String client = RpcContext.getContext().getRemoteAddressString();
    ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
    if (clientListeners == null) {
        remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
        clientListeners = remoteSubscribed.get(client);
    }
    Set<NotifyListener> listeners = clientListeners.get(url);
    if (listeners == null) {
        clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
        listeners = clientListeners.get(url);
    }
    listeners.add(listener);
    super.subscribe(url, listener);
    subscribed(url, listener);
}
 
Example #13
Source File: SimpleRegistryService.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void subscribe(URL url, NotifyListener listener) {
    if (getUrl().getPort() == 0) {
        URL registryUrl = RpcContext.getContext().getUrl();
        if (registryUrl != null && registryUrl.getPort() > 0
        		&& RegistryService.class.getName().equals(registryUrl.getPath())) {
            super.setUrl(registryUrl);
            super.register(registryUrl);
        }
    }
    String client = RpcContext.getContext().getRemoteAddressString();
    ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
    if (clientListeners == null) {
        remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
        clientListeners = remoteSubscribed.get(client);
    }
    Set<NotifyListener> listeners = clientListeners.get(url);
    if (listeners == null) {
        clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
        listeners = clientListeners.get(url);
    }
    listeners.add(listener);
    super.subscribe(url, listener);
    subscribed(url, listener);
}
 
Example #14
Source File: SimpleRegistryService.java    From tutorials with MIT License 6 votes vote down vote up
public void subscribe(URL url, NotifyListener listener) {
    if (getUrl().getPort() == 0) {
        URL registryUrl = RpcContext.getContext().getUrl();
        if (registryUrl != null && registryUrl.getPort() > 0
                && RegistryService.class.getName().equals(registryUrl.getPath())) {
            super.setUrl(registryUrl);
            super.register(registryUrl);
        }
    }
    String client = RpcContext.getContext().getRemoteAddressString();
    ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
    if (clientListeners == null) {
        remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
        clientListeners = remoteSubscribed.get(client);
    }
    Set<NotifyListener> listeners = clientListeners.get(url);
    if (listeners == null) {
        clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
        listeners = clientListeners.get(url);
    }
    listeners.add(listener);
    super.subscribe(url, listener);
    subscribed(url, listener);
}
 
Example #15
Source File: Consumer.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException, ExecutionException {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-consumer.xml");
	context.start();
	DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理

	// System.out.println(demoService.syncSayHello("world"));
	System.out.println(demoService.asyncSayHello("world"));
	Future<String> futrue = RpcContext.getContext().getFuture();
	System.out.println(futrue.get());

	// System.out.println(demoService.sayHello(new TestBean("zhaohui", 99,
	// "nanjing")));

	// Map<String, String> map = (Map<String, String>)
	// context.getBean("redis");
	// map.put("haha", "vvv1");
	//
	// System.out.println(map.get("haha"));
}
 
Example #16
Source File: ImplicitCallBackTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_Async_Future_Multi() throws Exception {
    initOrResetUrl(true);
    destroyService();
    exportService();
    referService();
    
    int requestId1 = 1;
    Person ret = demoProxy.get(requestId1);
    Assert.assertEquals(null, ret);
    Future<Person> p1Future = RpcContext.getContext().getFuture();
    
    int requestId2 = 1;
    Person ret2 = demoProxy.get(requestId2);
    Assert.assertEquals(null, ret2);
    Future<Person> p2Future = RpcContext.getContext().getFuture();
    
    ret = p1Future.get(1000, TimeUnit.MICROSECONDS);
    ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS);
    Assert.assertEquals(requestId1, ret.getId());
    Assert.assertEquals(requestId2, ret.getId());
    destroyService();
}
 
Example #17
Source File: ConsumerContextFilter.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcContext.getContext()
                .setInvoker(invoker)
                .setInvocation(invocation)
                .setLocalAddress(NetUtils.getLocalHost(), 0)
                .setRemoteAddress(invoker.getUrl().getHost(),
                        invoker.getUrl().getPort());
        if (invocation instanceof RpcInvocation) {
            ((RpcInvocation) invocation).setInvoker(invoker);
        }
        try {
//            com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper.buildInvokerChain com.alibaba.dubbo.rpc.Invoker.invoke()
            RpcResult result = (RpcResult) invoker.invoke(invocation);
            RpcContext.getServerContext().setAttachments(result.getAttachments());
            return result;
        } finally {
            RpcContext.getContext().clearAttachments();
        }
    }
 
Example #18
Source File: SimpleRegistryService.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
public void unsubscribe(String service, URL url, NotifyListener listener) {
    super.unsubscribe(service, url, listener);
    String client = RpcContext.getContext().getRemoteAddressString();
    Map<String, NotifyListener> listeners = remoteListeners.get(client);
    if (listeners != null && listeners.size() > 0) {
        listeners.remove(service);
    }
    List<URL> urls = getRegistered().get(service);
    if (urls != null && urls.size() > 0) {
        listener.notify(urls);
    }
}
 
Example #19
Source File: FailSafeClusterInvokerTest.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeExceptoin() {
    resetInvokerToException();
    FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic);
    invoker.invoke(invocation);
    Assert.assertNull(RpcContext.getContext().getInvoker());
}
 
Example #20
Source File: Tracer.java    From dubbo-plus with Apache License 2.0 5 votes vote down vote up
private void setAttachment() {
    RpcContext rpcContext = RpcContext.getContext();
    String traceId = ContextHolder.getTraceId();
    rpcContext.setAttachment(DstConstants.DST_IS_SAMPLE,ContextHolder.isSample()+"");
    if (traceId != null) {
        rpcContext.setAttachment(DstConstants.DST_TRACE_ID, traceId);
    }
    Span span = ContextHolder.getSpan();
    if (span != null) {
        rpcContext.setAttachment(DstConstants.DST_SPAN_ID, span.getId());
        rpcContext.setAttachment(DstConstants.DST_PARENT_SPAN_ID, span.getParentId());
    }
}
 
Example #21
Source File: DefaultCalculateService.java    From tech-weekly with Apache License 2.0 5 votes vote down vote up
@Override
@GET
@Path("/divide")
public int divide(@QueryParam("a") int a, @QueryParam("b") int b) {
    int result = a / b;
    System.out.printf(
            "[port : %s] CalculateService.divide( a= %d, b = %d ) = %d\n",
            RpcContext.getContext().getLocalPort(), a, b, result
    );
    return result;
}
 
Example #22
Source File: ITTracingFilter_Consumer.java    From brave with Apache License 2.0 5 votes vote down vote up
/** Ensures the span completes on asynchronous invocation. */
@Test public void test_async_invoke() throws Exception {
  client.setAsync(true);
  String jorge = client.get().sayHello("jorge");
  assertThat(jorge).isNull();
  Object o = RpcContext.getContext().getFuture().get();
  assertThat(o).isNotNull();

  testSpanHandler.takeRemoteSpan(CLIENT);
}
 
Example #23
Source File: SimpleRegistryService.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void unregister(URL url) {
    String client = RpcContext.getContext().getRemoteAddressString();
    Set<URL> urls = remoteRegistered.get(client);
    if (urls != null && urls.size() > 0) {
        urls.remove(url);
    }
    super.unregister(url);
    unregistered(url);
}
 
Example #24
Source File: DemoServiceImpl.java    From cicada with MIT License 5 votes vote down vote up
public String sayHello(final String name) {
  System.out.println(demoService2.sayWorld(name));
  // System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new
  // Date()) + "] Hello " + name
  // + ", request from consumer: " +
  // RpcContext.getContext().getRemoteAddress());
  return "Hello " + name + ", response form provider: " + RpcContext.getContext().getLocalAddress();
}
 
Example #25
Source File: ImplicitCallBackTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_Async_Future() throws Exception {
    initOrResetUrl(true);
    destroyService();
    exportService();
    referService();

    int requestId = 2;
    Person ret = demoProxy.get(requestId);
    Assert.assertEquals(null, ret);
    Future<Person> pFuture = RpcContext.getContext().getFuture();
    ret = pFuture.get(1000 * 1000, TimeUnit.MICROSECONDS);
    Assert.assertEquals(requestId, ret.getId());
    destroyService();
}
 
Example #26
Source File: DubboServerHandler.java    From brave-instrumentation-dubbo with Apache License 2.0 5 votes vote down vote up
public Span handleReceive(TraceContext.Extractor extractor) {
  Span span = nextSpan(extractor.extract(RpcContext.getContext().getAttachments()));
  if (span.isNoop()) return span;
  span.kind(Span.Kind.SERVER);
  Tracer.SpanInScope ws = tracer.withSpanInScope(span);
  try {
    parser.request(adapter, RpcContext.getContext(), span);
  } finally {
    ws.close();
  }
  return span.start();
}
 
Example #27
Source File: InjvmInvoker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Result doInvoke(Invocation invocation) throws Throwable {
    Exporter<?> exporter = InjvmProtocol.getExporter(exporterMap, getUrl());
    if (exporter == null)  {
        throw new RpcException("Service [" + key + "] not found.");
    }
    RpcContext.getContext().setRemoteAddress(NetUtils.LOCALHOST, 0);
    return exporter.getInvoker().invoke(invocation);
}
 
Example #28
Source File: TokenFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation inv)
		throws RpcException {
    String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY);
    if (ConfigUtils.isNotEmpty(token)) {
        Class<?> serviceType = invoker.getInterface();
        Map<String, String> attachments = inv.getAttachments();
   		String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY);
   		if (! token.equals(remoteToken)) {
   			throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider "  + RpcContext.getContext().getLocalHost());
   		}
    }
	return invoker.invoke(inv);
}
 
Example #29
Source File: ThriftProtocol.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
public Object reply( ExchangeChannel channel, Object msg ) throws RemotingException {

    if ( msg instanceof Invocation ) {
        Invocation inv = ( Invocation ) msg;
        String serviceName = inv.getAttachments().get(Constants.INTERFACE_KEY);
        String serviceKey = serviceKey( channel.getLocalAddress().getPort(),
                                        serviceName, null, null );
        DubboExporter<?> exporter = (DubboExporter<?>) exporterMap.get( serviceKey );
        if (exporter == null) {
            throw new RemotingException(channel,
                                        "Not found exported service: "
                                                + serviceKey
                                                + " in "
                                                + exporterMap.keySet()
                                                + ", may be version or group mismatch "
                                                + ", channel: consumer: "
                                                + channel.getRemoteAddress()
                                                + " --> provider: "
                                                + channel.getLocalAddress()
                                                + ", message:"+ msg);
        }

        RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress());
        return exporter.getInvoker().invoke( inv );

    }

    throw new RemotingException(channel,
                                "Unsupported request: "
                                        + (msg.getClass().getName() + ": " + msg)
                                        + ", channel: consumer: "
                                        + channel.getRemoteAddress()
                                        + " --> provider: "
                                        + channel.getLocalAddress());
}
 
Example #30
Source File: SimpleRegistryService.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void register(URL url) {
    String client = RpcContext.getContext().getRemoteAddressString();
    Set<URL> urls = remoteRegistered.get(client);
    if (urls == null) {
        remoteRegistered.putIfAbsent(client, new ConcurrentHashSet<URL>());
        urls = remoteRegistered.get(client);
    }
    urls.add(url);
    super.register(url);
    registered(url);
}