11、异步调用

异步调用只能在消费端配置

异步调用
  基于 NIO 的非阻塞实现并行调用,客户端不需要启动多线程即可完成并行调用多个远程服务,相对多线程开销较小。

1、配置xml,只需要在reference里面新增async=true即可。

<dubbo:reference interface="com.hdd.api.IHelloWorld" id="helloWorld" cache="lru" timeout="5000" async="true"></dubbo:reference>

2、代码调用

public void testAsync() throws InterruptedException, ExecutionException {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		IHelloWorld helloWorld = (IHelloWorld) applicationContext.getBean("helloWorld");
		
		long start = System.currentTimeMillis();
		//此时会立即返回null,同时设置Future到RpcContext中
		String name = helloWorld.get("helloWorld ");
		System.out.println("future.get()前:name:" + name);
		//获取Future,通过get方法获取返回值
		Future<String> future = RpcContext.getContext().getFuture();		
			
		//模拟本地操作需要4秒
		Thread.sleep(4000);
		String result = "local operator";
		
		//获得真正的返回值,线程wait,如果服务有返回值,会调用notify
		name = future.get();
		System.out.println("future.get()后:name:" + name);
		long end = System.currentTimeMillis();
		
		System.out.println(name + result + ",用时:" + (end - start)/1000);
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值