Java Code Examples for com.alibaba.dubbo.rpc.RpcContext

The following examples show how to use com.alibaba.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: brave   Source File: TestServer.java    License: 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 2
Source Project: dubbox   Source File: ExceptionFilterTest.java    License: 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 3
Source Project: dubbox   Source File: MonitorFilter.java    License: 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 4
Source Project: dubbo3   Source File: MonitorFilterTest.java    License: 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 5
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 Project: dubbo-2.6.5   Source File: HessianProtocolTest.java    License: 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 7
Source Project: dubbox   Source File: ContextFilterTest.java    License: 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 8
Source Project: dubbo-2.6.5   Source File: ConsumerContextFilter.java    License: 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 9
Source Project: dubbox-hystrix   Source File: AsyncConsumer.java    License: 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 10
Source Project: dubbox   Source File: ImplicitCallBackTest.java    License: 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 11
Source Project: tutorials   Source File: SimpleRegistryService.java    License: 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 12
Source Project: dubbox   Source File: SimpleRegistryService.java    License: 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 Project: dubbox-hystrix   Source File: SimpleRegistryService.java    License: 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 Project: dubbox   Source File: ImplicitCallBackTest.java    License: 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 15
Source Project: blog   Source File: Consumer.java    License: 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 Project: dubbox-hystrix   Source File: ConsumerContextFilter.java    License: 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 17
Source Project: sofa-tracer   Source File: DubboSofaTracerFilter.java    License: 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 18
Source Project: dubbox   Source File: ThriftProtocol.java    License: 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 19
Source Project: dubbox   Source File: ConsumerContextFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetContext(){
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    Invoker<DemoService> invoker = new MyInvoker<DemoService>(url);
    Invocation invocation = new MockInvocation();
    consumerContextFilter.invoke(invoker, invocation);
    assertEquals(invoker,RpcContext.getContext().getInvoker());
    assertEquals(invocation,RpcContext.getContext().getInvocation());
    assertEquals(NetUtils.getLocalHost() + ":0",RpcContext.getContext().getLocalAddressString());
    assertEquals("test:11",RpcContext.getContext().getRemoteAddressString());
    
}
 
Example 20
Source Project: dubbox   Source File: FailbackClusterInvokerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeExceptoin() {
    resetInvokerToException();
    FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
                                                                                                                        dic);
    invoker.invoke(invocation);
    Assert.assertNull(RpcContext.getContext().getInvoker());
}
 
Example 21
Source Project: dubbox-hystrix   Source File: ConsumerContextFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetContext(){
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
    Invoker<DemoService> invoker = new MyInvoker<DemoService>(url);
    Invocation invocation = new MockInvocation();
    consumerContextFilter.invoke(invoker, invocation);
    assertEquals(invoker,RpcContext.getContext().getInvoker());
    assertEquals(invocation,RpcContext.getContext().getInvocation());
    assertEquals(NetUtils.getLocalHost() + ":0",RpcContext.getContext().getLocalAddressString());
    assertEquals("test:11",RpcContext.getContext().getRemoteAddressString());
    
}
 
Example 22
Source Project: dubbox   Source File: HessianProtocol.java    License: Apache License 2.0 5 votes vote down vote up
public void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String uri = request.getRequestURI();
    HessianSkeleton skeleton = skeletonMap.get(uri);
    if (! request.getMethod().equalsIgnoreCase("POST")) {
        response.setStatus(500);
    } else {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
        try {
            skeleton.invoke(request.getInputStream(), response.getOutputStream());
        } catch (Throwable e) {
            throw new ServletException(e);
        }
    }
}
 
Example 23
Source Project: dubbox   Source File: UserRestServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@GET
    @Path("{id : \\d+}")
    public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest request*/) {
        // test context injection
//        System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : ""));
//        System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString());
        if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) {
            System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr());
        }
        if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) {
            System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class));
        }
        return userService.getUser(id);
    }
 
Example 24
Source Project: dubbox-hystrix   Source File: HttpProtocol.java    License: Apache License 2.0 5 votes vote down vote up
public void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String uri = request.getRequestURI();
    HttpInvokerServiceExporter skeleton = skeletonMap.get(uri);
    if (! request.getMethod().equalsIgnoreCase("POST")) {
        response.setStatus(500);
    } else {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
        try {
            skeleton.handleRequest(request, response);
        } catch (Throwable e) {
            throw new ServletException(e);
        }
    }
}
 
Example 25
Source Project: dubbox   Source File: HttpProtocol.java    License: Apache License 2.0 5 votes vote down vote up
public void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String uri = request.getRequestURI();
    HttpInvokerServiceExporter skeleton = skeletonMap.get(uri);
    if (! request.getMethod().equalsIgnoreCase("POST")) {
        response.setStatus(500);
    } else {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
        try {
            skeleton.handleRequest(request, response);
        } catch (Throwable e) {
            throw new ServletException(e);
        }
    }
}
 
Example 26
Source Project: dubbox   Source File: TokenFilter.java    License: 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 27
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.DUBBO_APPLICATION_KEY);
    assertEquals("serviceA", application);
}
 
Example 28
Source Project: dubbox   Source File: FailbackClusterInvokerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test()
public void testRetryFailed() {

    resetInvokerToException();

    FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<FailbackClusterInvokerTest>(
                                                                                                                        dic);
    invoker.invoke(invocation);
    Assert.assertNull(RpcContext.getContext().getInvoker());
    invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked invoker,so
                          // it can be invoke successfully
}
 
Example 29
Source Project: dubbox   Source File: ScriptRouter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
 
Example 30
Source Project: dubbox   Source File: UserRestServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    public User getUser(@Min(value = 1L, message = "User ID must be greater than 1") @PathParam("id") Long id) {
        // test context injection
//        System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : ""));
//        System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString());
        if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) {
            System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr());
        }
        if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) {
            System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class));
        }
        return userService.getUser(id);
    }