Dubbo中异步转同步

TCP协议本身就是异步的,在TCP协议层面,我们发完RPC请求后,并不会等待RPC的响应结果,那么框架帮助我们做了,那是怎么做的呢?
我们可以首先想到的就是等待-通知。

  1. private final Lock lock
  2. = new ReentrantLock();
  3. private final Condition done
  4. = lock.newCondition();
  5. while(终止条件){
  6. done.await(); // 等待
  7. }
  8. done.sigall();//唤醒
  1. String response = "";// 是我们的返回结果
  2. // 创建锁与条件变量
  3. private final Lock lock
  4. = new ReentrantLock();
  5. private final Condition done
  6. = lock.newCondition();
  7. Boolean isDone(){
  8. return respnes != null;
  9. }
  10. long start = System.nanoTime(); // 开始时间
  11. lock.lock(); // 上锁
  12. try{
  13. while(!isDone){ // 为空一致循环
  14. done.await(timeOut); // 等待超时时间
  15. long cur=System.nanoTime(); // 当前时间
  16. if(isDone || cur - strat > timeOut){ // RPC返回了信息 或 等待超时 就break
  17. }final{
  18. lock.unlock();
  19. }
  20. if (!isDone()) {
  21. throw new TimeoutException(); // 超时
  22. }

dubbo中的实现

  1. // 创建锁与条件变量
  2. private final Lock lock
  3. = new ReentrantLock();
  4. private final Condition done
  5. = lock.newCondition();
  6. // 调用方通过该方法等待结果
  7. Object get(int timeout){
  8. long start = System.nanoTime();
  9. lock.lock();
  10. try {
  11. while (!isDone()) {
  12. done.await(timeout);
  13. long cur=System.nanoTime();
  14. if (isDone() ||
  15. cur-start > timeout){
  16. break;
  17. }
  18. }
  19. } finally {
  20. lock.unlock();
  21. }
  22. if (!isDone()) {
  23. throw new TimeoutException();
  24. }
  25. return returnFromResponse();
  26. }
  27. // RPC结果是否已经返回
  28. boolean isDone() {
  29. return response != null;
  30. }
  31. // RPC结果返回时调用该方法
  32. private void doReceived(Response res) {
  33. lock.lock();
  34. try {
  35. response = res;
  36. if (done != null) {
  37. done.signal();
  38. }
  39. } finally {
  40. lock.unlock();
  41. }
  42. }