Dubbo如何用管程实现异步转同步?

2024-06-04 03:48

本文主要是介绍Dubbo如何用管程实现异步转同步?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

总览

Dubbo在调用服务的时候使用了DefaultFuture这个类,其中有一个概念是异步调用转成同步调用。核心思想就是管程。而实现方式就是使用lock和condition。
condition 是java 并发包中的一个类, 在java内置管程中是一个条件变量的,而condition是可以实现一个管程多个条件变量。 lock是java的重入锁。
关于管程和condtion可以参考:https://blog.csdn.net/u011296165/article/details/89944540
关于lock重入锁可以参考 : https://blog.csdn.net/u011296165/article/details/89873493
java 并发包是使用lock和condition实现的管程。

关于同步异步

在调用方法的时候,调用方是否需要等待返回结果才能执行下一步。如果需要等待就是同步,不需要等待就是异步。
关于java异步方式实现有两种方式

  1. 调用方创建一个线程,这种调用我们称为异步调用。
  2. 实现方法的时候开启一个线程去执行主要逻辑 ,主线程直接return,这种方法我们称为异步方法。

dubbo源码

以下是dubbo的源码,我自己跟了一点点代码,并将代码注释,一部分引入了别的累的东西,我将代码截图粘到下面


/*** DefaultFuture.*/
public class DefaultFuture implements ResponseFuture {private static final Logger logger = LoggerFactory.getLogger(DefaultFuture.class);/*** @Author 田培融* @Description 管程去调用远程服务* @Date 18:31 2019/5/15* @Param* @return**/private static final Map<Long, Channel> CHANNELS = new ConcurrentHashMap<>();/*** @Author 田培融* @Description 多个线程去调用返回不同的结果* @Date 18:31 2019/5/15* @Param* @return**/private static final Map<Long, DefaultFuture> FUTURES = new ConcurrentHashMap<>();// 超时时间public static final Timer TIME_OUT_TIMER = new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true),30,TimeUnit.MILLISECONDS);// invoke id.private final long id;// dubbo 自定义的管道private final Channel channel;// dubbo 自定义的请求对象private final Request request;// 超时时间private final int timeout;// java并发包中的重入锁(管程中的入口队列和看门人)private final Lock lock = new ReentrantLock();// java并发包中的条件变量(管程中的条件变量队列)private final Condition done = lock.newCondition();// 开始时间private final long start = System.currentTimeMillis();// 使用volatile关键字去修饰以达到多线程内存可见private volatile long sent;// dubbo 自定义的响应体private volatile Response response;// dubbo中自定义的响应体回调接口private volatile ResponseCallback callback;/*** @Author 田培融* @Description 构造方法,需要传* @Date 18:38 2019/5/15* @Param [channel, request, timeout]* @return**/private DefaultFuture(Channel channel, Request request, int timeout) {this.channel = channel;this.request = request;this.id = request.getId();this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);// put into waiting map.FUTURES.put(id, this);CHANNELS.put(id, channel);}/*** check time out of the future*/private static void timeoutCheck(DefaultFuture future) {TimeoutCheckTask task = new TimeoutCheckTask(future);TIME_OUT_TIMER.newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS);}/*** init a DefaultFuture* 1.init a DefaultFuture* 2.timeout check** @param channel channel* @param request the request* @param timeout timeout* @return a new DefaultFuture*/public static DefaultFuture newFuture(Channel channel, Request request, int timeout) {final DefaultFuture future = new DefaultFuture(channel, request, timeout);// timeout checktimeoutCheck(future);return future;}/*** @Author 田培融* @Description 在futuresMap中获取* @Date 18:57 2019/5/15* @Param [id]* @return org.apache.dubbo.remoting.exchange.support.DefaultFuture**/public static DefaultFuture getFuture(long id) {return FUTURES.get(id);}/*** @Author 田培融* @Description 判断channel是否在管道map中* @Date 18:58 2019/5/15* @Param [channel]* @return boolean**/public static boolean hasFuture(Channel channel) {return CHANNELS.containsValue(channel);}/*** @Author 田培融* @Description 发送请求* 1. 先在futures队列中获取futures 在调用 dosent方法将sent值设置为当前系统时间* @Date 18:59 2019/5/15* @Param [channel, request]* @return void**/public static void sent(Channel channel, Request request) {DefaultFuture future = FUTURES.get(request.getId());if (future != null) {future.doSent();}}/*** close a channel when a channel is inactive* directly return the unfinished requests.* 关闭管程** @param channel channel to close*/public static void closeChannel(Channel channel) {for (Map.Entry<Long, Channel> entry : CHANNELS.entrySet()) {if (channel.equals(entry.getValue())) {DefaultFuture future = getFuture(entry.getKey());if (future != null && !future.isDone()) {Response disconnectResponse = new Response(future.getId());disconnectResponse.setStatus(Response.CHANNEL_INACTIVE);disconnectResponse.setErrorMessage("Channel " +channel +" is inactive. Directly return the unFinished request : " +future.getRequest());DefaultFuture.received(channel, disconnectResponse);}}}}/*** @Author 田培融* @Description 在响应中取值 如果就调用doReceived释放掉在条件对列中等待的线程* @Date 19:09 2019/5/15* @Param [channel, response]* @return void**/public static void received(Channel channel, Response response) {try {DefaultFuture future = FUTURES.remove(response.getId());if (future != null) {future.doReceived(response);} else {logger.warn("The timeout response finally returned at "+ (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()))+ ", response " + response+ (channel == null ? "" : ", channel: " + channel.getLocalAddress()+ " -> " + channel.getRemoteAddress()));}} finally {CHANNELS.remove(response.getId());}}@Overridepublic Object get() throws RemotingException {return get(timeout);}/*** @Author 田培融* @Description 线程通过这个方法去获取响应* @Date 19:22 2019/5/15* @Param [timeout]* @return java.lang.Object**/@Overridepublic Object get(int timeout) throws RemotingException {if (timeout <= 0) {timeout = DEFAULT_TIMEOUT;}if (!isDone()) {long start = System.currentTimeMillis();lock.lock();try {while (!isDone()) {done.await(timeout, TimeUnit.MILLISECONDS);if (isDone() || System.currentTimeMillis() - start > timeout) {break;}}} catch (InterruptedException e) {throw new RuntimeException(e);} finally {lock.unlock();}if (!isDone()) {throw new TimeoutException(sent > 0, channel, getTimeoutMessage(false));}}return returnFromResponse();}public void cancel() {Response errorResult = new Response(id);errorResult.setErrorMessage("request future has been canceled.");response = errorResult;FUTURES.remove(id);CHANNELS.remove(id);}@Overridepublic boolean isDone() {return response != null;}/*** @Author 田培融* @Description 线程通过这个方法去将直接获取到的响应结果放到这个类中的成员变量,并去唤醒在条件队列中等待的线程* @Date 19:25 2019/5/15* @Param [callback]* @return void**/@Overridepublic void setCallback(ResponseCallback callback) {if (isDone()) {invokeCallback(callback);} else {boolean isdone = false;lock.lock();try {if (!isDone()) {this.callback = callback;} else {isdone = true;}} finally {lock.unlock();}if (isdone) {invokeCallback(callback);}}}private static class TimeoutCheckTask implements TimerTask {private DefaultFuture future;TimeoutCheckTask(DefaultFuture future) {this.future = future;}@Overridepublic void run(Timeout timeout) {if (future == null || future.isDone()) {return;}// create exception response.Response timeoutResponse = new Response(future.getId());// set timeout status.timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT);timeoutResponse.setErrorMessage(future.getTimeoutMessage(true));// handle response.DefaultFuture.received(future.getChannel(), timeoutResponse);}}/*** @Author 田培融* @Description 直正去执行获取到的返回值放到response中* @Date 19:25 2019/5/15* @Param [c]* @return void**/private void invokeCallback(ResponseCallback c) {ResponseCallback callbackCopy = c;if (callbackCopy == null) {throw new NullPointerException("callback cannot be null.");}Response res = response;if (res == null) {throw new IllegalStateException("response cannot be null. url:" + channel.getUrl());}if (res.getStatus() == Response.OK) {try {callbackCopy.done(res.getResult());} catch (Exception e) {logger.error("callback invoke error .result:" + res.getResult() + ",url:" + channel.getUrl(), e);}} else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) {try {TimeoutException te = new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage());callbackCopy.caught(te);} catch (Exception e) {logger.error("callback invoke error ,url:" + channel.getUrl(), e);}} else {try {RuntimeException re = new RuntimeException(res.getErrorMessage());callbackCopy.caught(re);} catch (Exception e) {logger.error("callback invoke error ,url:" + channel.getUrl(), e);}}}private Object returnFromResponse() throws RemotingException {Response res = response;if (res == null) {throw new IllegalStateException("response cannot be null");}if (res.getStatus() == Response.OK) {return res.getResult();}if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) {throw new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage());}throw new RemotingException(channel, res.getErrorMessage());}private long getId() {return id;}private Channel getChannel() {return channel;}private boolean isSent() {return sent > 0;}public Request getRequest() {return request;}private int getTimeout() {return timeout;}private long getStartTimestamp() {return start;}private void doSent() {sent = System.currentTimeMillis();}/*** @Author 田培融* @Description 实现管程的一部分,直释放到等待的线程* @Date 19:29 2019/5/15* @Param [res]* @return void**/private void doReceived(Response res) {lock.lock();try {response = res;done.signalAll();} finally {lock.unlock();}if (callback != null) {invokeCallback(callback);}}private String getTimeoutMessage(boolean scan) {long nowTimestamp = System.currentTimeMillis();return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side")+ (scan ? " by scan timer" : "") + ". start time: "+ (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: "+ (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ","+ (sent > 0 ? " client elapsed: " + (sent - start)+ " ms, server elapsed: " + (nowTimestamp - sent): " elapsed: " + (nowTimestamp - start)) + " ms, timeout: "+ timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress()+ " -> " + channel.getRemoteAddress();}
}

获取request中的id
在这里插入图片描述

将id值 初始化进入Response中
在这里插入图片描述

现在将代码需求重新说一下,就是线程T1在调用 Rpc之后就将线程阻塞住,当返回结果后就在将T1线程唤醒。这里使用的是管程,。因为业务牵扯过多,为了节省时间就把关于管程的代码就节取了出来 。

// 创建锁与条件变量
private final Lock lock = new ReentrantLock();
private final Condition done = lock.newCondition();private private volatile Response response;// 调用方通过该方法等待结果
Object get(int timeout){long start = System.nanoTime();lock.lock();try {while (!isDone()) {done.await(timeout);long cur=System.nanoTime();if (isDone() || cur-start > timeout){break;}}} finally {lock.unlock();}if (!isDone()) {throw new TimeoutException();}return returnFromResponse();
}
// RPC 结果是否已经返回
boolean isDone() {return response != null;
}
// RPC 结果返回时调用该方法   
private void doReceived(Response res) {lock.lock();try {response = res;if (done != null) {done.signal();}} finally {lock.unlock();}
}

代码流程分析
线程T1在调用 get()方法后调用 lock锁进入管程,使用while()循环进入等待。使用finally调用释放锁。 当rpc返回结果后在调用doReceived()方法进行附值。并能知条件变量中等待的线程。

这里在对成员变量的修饰符进行解释

假如T2线程为rpc线程,T2线程会接收一个t1线程new出的对象。并将对象放到自己的线程栈内存中,因此lock需要使用final修饰(final 如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。)Lock就是一个引用类型的变量这样t2线程中的lock变量就是指向的t1线程中new出的Lock对象。

response是用volatile修饰的,当t2线程获取值并对response进行操作后,response由于volatile修改,因此t1线程也可以读取到。这里是使用volatile修改的变量保证了内存可见性,就是说volatile修改的变量,线程都会去堆内存中去直接操作,而不是将变量拉到栈空间中操作。这样所有的线程都是操作的同一个变量。

这篇关于Dubbo如何用管程实现异步转同步?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1028977

相关文章

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、