Java Code Examples for com.alibaba.dubbo.rpc.Invoker#invoke()

The following examples show how to use com.alibaba.dubbo.rpc.Invoker#invoke() . 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: FailbackClusterInvoker.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
void retryFailed() {
    if (failed.size() == 0) {
        return;
    }
    for (Map.Entry<Invocation, AbstractClusterInvoker<?>> entry : new HashMap<Invocation, AbstractClusterInvoker<?>>(
                                                                                                                     failed).entrySet()) {
        Invocation invocation = entry.getKey();
        Invoker<?> invoker = entry.getValue();
        try {
            invoker.invoke(invocation);
            failed.remove(invocation);
        } catch (Throwable e) {
            logger.error("Failed retry to invoke method " + invocation.getMethodName() + ", waiting again.", e);
        }
    }
}
 
Example 2
Source File: MockClusterInvokerTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_mock_false(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("mock","false")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getBoolean2");
	try {
		cluster.invoke(invocation);
		Assert.fail();
	} catch (RpcException e) {
		Assert.assertTrue(e.isTimeout());
	}
}
 
Example 3
Source File: ConsumerContextFilter.java    From dubbo3 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 4
Source File: MockClusterInvokerTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_force_throw(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getBoolean2.mock","force:throw ")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getBoolean2");
	try {
		cluster.invoke(invocation);
		Assert.fail();
	} catch (RpcException e) {
		Assert.assertFalse("not custem exception", e.isBiz());
	}
}
 
Example 5
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 6
Source File: CacheFilter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.CACHE_KEY))) {
        Cache cache = cacheFactory.getCache(invoker.getUrl().addParameter(Constants.METHOD_KEY, invocation.getMethodName()));
        if (cache != null) {
            String key = StringUtils.toArgumentString(invocation.getArguments());
            if (cache != null && key != null) {
                Object value = cache.get(key);
                if (value != null) {
                    return new RpcResult(value);
                }
                Result result = invoker.invoke(invocation);
                if (! result.hasException()) {
                    cache.put(key, result.getValue());
                }
                return result;
            }
        }
    }
    return invoker.invoke(invocation);
}
 
Example 7
Source File: AvailableClusterInvoker.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
    for (Invoker<T> invoker : invokers) {
        if (invoker.isAvailable()) {
            return invoker.invoke(invocation);
        }
    }
    throw new RpcException("No provider available in " + invokers);
}
 
Example 8
Source File: MockClusterInvokerTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_check_int(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getInt1.mock","force:return 1688")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getInt1");
       Result ret = cluster.invoke(invocation);
       Assert.assertTrue("result type must be integer but was : " + ret.getValue().getClass(), ret.getValue() instanceof Integer);
       Assert.assertEquals(new Integer(1688), (Integer)ret.getValue());
}
 
Example 9
Source File: ExecuteLimitFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    URL url = invoker.getUrl();
    String methodName = invocation.getMethodName();
    int max = url.getMethodParameter(methodName, Constants.EXECUTES_KEY, 0);
    if (max > 0) {
        RpcStatus count = RpcStatus.getStatus(url, invocation.getMethodName());
        if (count.getActive() >= max) {
            throw new RpcException("Failed to invoke method " + invocation.getMethodName() + " in provider " + url + ", cause: The service using threads greater than <dubbo:service executes=\"" + max + "\" /> limited.");
        }
    }
    long begin = System.currentTimeMillis();
    boolean isException = false;
    RpcStatus.beginCount(url, methodName);
    try {
        Result result = invoker.invoke(invocation);
        return result;
    } catch (Throwable t) {
        isException = true;
        if(t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        else {
            throw new RpcException("unexpected exception when ExecuteLimitFilter", t);
        }
    }
    finally {
        RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isException);
    }
}
 
Example 10
Source File: DeprecatedFilter.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String key = invoker.getInterface().getName() + "." + invocation.getMethodName();
    if (! logged.contains(key)) {
        logged.add(key);
        if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.DEPRECATED_KEY, false)) {
            LOGGER.error("The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl());
        }
    }
    return invoker.invoke(invocation);
}
 
Example 11
Source File: MockClusterInvokerTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_check_int(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getInt1.mock","force:return 1688")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getInt1");
       Result ret = cluster.invoke(invocation);
       Assert.assertTrue("result type must be integer but was : " + ret.getValue().getClass(), ret.getValue() instanceof Integer);
       Assert.assertEquals(new Integer(1688), (Integer)ret.getValue());
}
 
Example 12
Source File: TransactionServiceFilter.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Result wrapResultForProvider(Invoker<?> invoker, Invocation invocation, String propagatedBy,
		boolean attachRequired) {

	try {
		RpcResult result = (RpcResult) invoker.invoke(invocation);
		if (result.hasException()) {
			return this.createErrorResultForProvider(result.getException(), propagatedBy, attachRequired);
		} else {
			return this.convertResultForProvider(result, propagatedBy, attachRequired);
		}
	} catch (Throwable rex) {
		return this.createErrorResultForProvider(rex, propagatedBy, attachRequired);
	}

}
 
Example 13
Source File: TimeoutFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    long start = System.currentTimeMillis();
    Result result = invoker.invoke(invocation);
    long elapsed = System.currentTimeMillis() - start;
    if (invoker.getUrl() != null
            && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(),
                    "timeout", Integer.MAX_VALUE)) {
        if (logger.isWarnEnabled()) {
            logger.warn("invoke time out. method: " + invocation.getMethodName()
                    + "arguments: " + Arrays.toString(invocation.getArguments()) + " , url is "
                    + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms.");
        }
    }
    return result;
}
 
Example 14
Source File: MockClusterInvokerTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
/**
 * 测试mock策略是否正常-fail-mock
 */
@Test
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("mock","fail")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getSomething");
       Result ret = cluster.invoke(invocation);
       Assert.assertEquals("somethingmock", ret.getValue());
}
 
Example 15
Source File: TokenFilter.java    From dubbo3 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 16
Source File: MockClusterInvokerTest.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testMockInvokerFromOverride_Invoke_check_ListString_empty(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getListString.mock","force:return empty")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getListString");
       Result ret = cluster.invoke(invocation);
       Assert.assertEquals(0, ((List<String>)ret.getValue()).size());
}
 
Example 17
Source File: MockClusterInvokerTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 测试mock策略是否正常-fail-mock
 */
@Test
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("mock","force");
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getSomething");
       Result ret = cluster.invoke(invocation);
       Assert.assertEquals("somethingmock", ret.getValue());
}
 
Example 18
Source File: RouterProviderFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
	try {
		// RouterContext.put(RouterConsts.IS_PROVIDER, "true");
		// 接收到调用的时候以传入的为准
		String routerInfo = invocation.getAttachment(RouterConsts.ROUTER_KEY);
		if (routerInfo != null) {
			// 如果路由信息不为空则执行并传递该路由
			RouterContext.put(RouterConsts.ROUTER_KEY, RouterInfo.parse(routerInfo));
		}
		Result result = invoker.invoke(invocation);

		// 返回结果时进行判断,如果当前调用链中包含了路由信息则往回传递该路由
		// if (routerInfo != null) {
		// result.getAttachments().put(RouterConsts.ROUTER_KEY, routerInfo);
		// }

		// 如果线程上下文包含了路由信息,则往回传递该路由
		// if (RouterContext.containsKey(RouterConsts.ROUTER_KEY)) {
		// result.getAttachments().put(RouterConsts.ROUTER_KEY,
		// RouterContext.get(RouterConsts.ROUTER_KEY));
		// }
		return result;
	} catch (RuntimeException e) {
		logger.error("Got unchecked and undeclared exception which called by "
				+ RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName()
				+ ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": "
				+ e.getMessage(), e);
		throw e;
	} finally {
		RouterContext.cleanup(); // server端cleanup
	}
}
 
Example 19
Source File: ActiveLimitFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    URL url = invoker.getUrl();
    String methodName = invocation.getMethodName();
    int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0);
    RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
    if (max > 0) {
        long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, 0);
        long start = System.currentTimeMillis();
        long remain = timeout;
        int active = count.getActive();
        if (active >= max) {
            synchronized (count) {
                while ((active = count.getActive()) >= max) {
                    try {
                        count.wait(remain);
                    } catch (InterruptedException e) {
                    }
                    long elapsed = System.currentTimeMillis() - start;
                    remain = timeout - elapsed;
                    if (remain <= 0) {
                        throw new RpcException("Waiting concurrent invoke timeout in client-side for service:  "
                                               + invoker.getInterface().getName() + ", method: "
                                               + invocation.getMethodName() + ", elapsed: " + elapsed
                                               + ", timeout: " + timeout + ". concurrent invokes: " + active
                                               + ". max concurrent invoke limit: " + max);
                    }
                }
            }
        }
    }
    try {
        long begin = System.currentTimeMillis();
        RpcStatus.beginCount(url, methodName);
        try {
            Result result = invoker.invoke(invocation);
            RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, true);
            return result;
        } catch (RuntimeException t) {
            RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, false);
            throw t;
        }
    } finally {
        if(max>0){
            synchronized (count) {
                count.notify();
            } 
        }
    }
}
 
Example 20
Source File: CompatibleFilter.java    From dubbo-samples with Apache License 2.0 4 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    System.out.println("Filter executed!!");
    invoked = true;
    return invoker.invoke(invocation);
}