Dubbo异步调用的实现介绍

来自:网络
时间:2022-12-30
阅读:
目录

前言

Dubbo不只提供了堵塞式的的同步调用,同时提供了异步调用的方式。这种方式主要应用于提供者接口响应耗时明显,消费者端可以利用调用接口的时间去做一些其他的接口调用,利用Future 模式来异步等待和获取结果即可。这种方式可以大大的提升消费者端的利用率。 目前这种方式可以通过XML的方式进行引入。

1、异步调用实现

(1)为了能够模拟等待,通过 int timeToWait参数,标明需要休眠多少毫秒后才会进行返回。

String sayHello(String name, int timeToWait);

(2)接口实现 为了模拟调用耗时 可以让线程等待一段时间

(3)在消费者端,配置异步调用 注意消费端默认超时时间1000毫秒 如果提供端耗时大于1000毫秒会出现超时

可以通过改变消费端的超时时间 通过timeout属性设置即可单位毫秒

<dubbo:reference id="helloService" interface="com.lagou.service.HelloService">
        <!--添加异步调用方式,注解方式不支持-->
        <dubbo:method name="sayHello" async="true" />
</dubbo:reference>

(4)测试,我们休眠100毫秒,然后再去进行获取结果。方法在同步调用时的返回值是空,我们可以通过RpcContext.getContext().getFuture() 来进行获取Future对象来进行后续的结果等待操作。

package com.lagou;
import com.lagou.bean.ConsumerComponent;
import com.lagou.service.HelloService;
import com.sun.org.apache.xpath.internal.functions.FuncTrue;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.util.concurrent.Future;
public class XMLConsumerMain {
    public static void main(String[] args) throws IOException, InterruptedException {
        ClassPathXmlApplicationContext   app  = new ClassPathXmlApplicationContext("consumer.xml");
        HelloService  service = app.getBean(HelloService.class);
        while (true) {
            System.in.read();
            try {
                String hello = service.sayHello("world", 100);
                // 利用Future 模式来获取
                Future<Object>  future  = RpcContext.getContext().getFuture();
                System.out.println("result :" + hello);
                System.out.println("future result:"+future.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

2、异步调用特殊说明

需要特别说明的是,该方式的使用,请确保dubbo的版本在2.5.4及以后的版本使用。 原因在于在2.5.3及之前的版本使用的时候,会出现异步状态传递问题。

比如我们的服务调用关系是A -> B -> C , 这时候如果A向B发起了异步请求,在错误的版本时,B向C发起的请求也会连带的产生异步请求。这是因为在底层实现层面,他是通过RPCContext 中的attachment 实现的。在A向B发起异步请求时,会在attachment 中增加一个异步标示字段来表明异步等待结果。B在接受到A中的请求时,会通过该字段来判断是否是异步处理。但是由于值传递问题,B向C发起时同样会将该值进行传递,导致C误以为需要异步结果,导致返回空。这个问题在2.5.4及以后的版本进行了修正。

返回顶部
顶部