成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Java 從零開始手寫 RPC-timeout 超時處理

開發 后端
前面我們實現了通用的 rpc,但是存在一個問題,同步獲取響應的時候沒有超時處理。如果 server 掛掉了,或者處理太慢,客戶端也不可能一直傻傻的等。

必要性

前面我們實現了通用的 rpc,但是存在一個問題,同步獲取響應的時候沒有超時處理。

如果 server 掛掉了,或者處理太慢,客戶端也不可能一直傻傻的等。

當外部的調用超過指定的時間后,就直接報錯,避免無意義的資源消耗。

思路

調用的時候,將開始時間保留。

獲取的時候檢測是否超時。

同時創建一個線程,用來檢測是否有超時的請求。

實現

思路

調用的時候,將開始時間保留。

獲取的時候檢測是否超時。

同時創建一個線程,用來檢測是否有超時的請求。

超時檢測線程

為了不影響正常業務的性能,我們另起一個線程檢測調用是否已經超時。

  1. package com.github.houbb.rpc.client.invoke.impl; 
  2.  
  3.  
  4. import com.github.houbb.heaven.util.common.ArgUtil; 
  5. import com.github.houbb.rpc.common.rpc.domain.RpcResponse; 
  6. import com.github.houbb.rpc.common.rpc.domain.impl.RpcResponseFactory; 
  7. import com.github.houbb.rpc.common.support.time.impl.Times; 
  8.  
  9.  
  10. import java.util.Map; 
  11. import java.util.concurrent.ConcurrentHashMap; 
  12.  
  13.  
  14. /** 
  15.  * 超時檢測線程 
  16.  * @author binbin.hou 
  17.  * @since 0.0.7 
  18.  */ 
  19. public class TimeoutCheckThread implements Runnable{ 
  20.  
  21.  
  22.     /** 
  23.      * 請求信息 
  24.      * @since 0.0.7 
  25.      */ 
  26.     private final ConcurrentHashMap<String, Long> requestMap; 
  27.  
  28.  
  29.     /** 
  30.      * 請求信息 
  31.      * @since 0.0.7 
  32.      */ 
  33.     private final ConcurrentHashMap<String, RpcResponse> responseMap; 
  34.  
  35.  
  36.     /** 
  37.      * 新建 
  38.      * @param requestMap  請求 Map 
  39.      * @param responseMap 結果 map 
  40.      * @since 0.0.7 
  41.      */ 
  42.     public TimeoutCheckThread(ConcurrentHashMap<String, Long> requestMap, 
  43.                               ConcurrentHashMap<String, RpcResponse> responseMap) { 
  44.         ArgUtil.notNull(requestMap, "requestMap"); 
  45.         this.requestMap = requestMap; 
  46.         this.responseMap = responseMap; 
  47.     } 
  48.  
  49.  
  50.     @Override 
  51.     public void run() { 
  52.         for(Map.Entry<String, Long> entry : requestMap.entrySet()) { 
  53.             long expireTime = entry.getValue(); 
  54.             long currentTime = Times.time(); 
  55.  
  56.  
  57.             if(currentTime > expireTime) { 
  58.                 final String key = entry.getKey(); 
  59.                 // 結果設置為超時,從請求 map 中移除 
  60.                 responseMap.putIfAbsent(key, RpcResponseFactory.timeout()); 
  61.                 requestMap.remove(key); 
  62.             } 
  63.         } 
  64.     } 
  65.  
  66.  
  67.  

這里主要存儲請求,響應的時間,如果超時,則移除對應的請求。

線程啟動

在 DefaultInvokeService 初始化時啟動:

  1. final Runnable timeoutThread = new TimeoutCheckThread(requestMap, responseMap); 
  2. Executors.newScheduledThreadPool(1) 
  3.                 .scheduleAtFixedRate(timeoutThread,60, 60, TimeUnit.SECONDS); 

DefaultInvokeService

原來的設置結果,獲取結果是沒有考慮時間的,這里加一下對應的判斷。

設置請求時間

•添加請求 addRequest

會將過時的時間直接放入 map 中。

因為放入是一次操作,查詢可能是多次。

所以時間在放入的時候計算完成。

  1. @Override 
  2. public InvokeService addRequest(String seqId, long timeoutMills) { 
  3.     LOG.info("[Client] start add request for seqId: {}, timeoutMills: {}", seqId, 
  4.             timeoutMills); 
  5.     final long expireTime = Times.time()+timeoutMills; 
  6.     requestMap.putIfAbsent(seqId, expireTime); 
  7.     return this; 

設置請求結果

•添加響應 addResponse

1.如果 requestMap 中已經不存在這個請求信息,則說明可能超時,直接忽略存入結果。

2.此時檢測是否出現超時,超時直接返回超時信息。

3.放入信息后,通知其他等待的所有進程。

  1. @Override 
  2. public InvokeService addResponse(String seqId, RpcResponse rpcResponse) { 
  3.     // 1. 判斷是否有效 
  4.     Long expireTime = this.requestMap.get(seqId); 
  5.     // 如果為空,可能是這個結果已經超時了,被定時 job 移除之后,響應結果才過來。直接忽略 
  6.     if(ObjectUtil.isNull(expireTime)) { 
  7.         return this; 
  8.     } 
  9.  
  10.  
  11.     //2. 判斷是否超時 
  12.     if(Times.time() > expireTime) { 
  13.         LOG.info("[Client] seqId:{} 信息已超時,直接返回超時結果。", seqId); 
  14.         rpcResponse = RpcResponseFactory.timeout(); 
  15.     } 
  16.  
  17.  
  18.     // 這里放入之前,可以添加判斷。 
  19.     // 如果 seqId 必須處理請求集合中,才允許放入?;蛘咧苯雍雎詠G棄。 
  20.     // 通知所有等待方 
  21.     responseMap.putIfAbsent(seqId, rpcResponse); 
  22.     LOG.info("[Client] 獲取結果信息,seqId: {}, rpcResponse: {}", seqId, rpcResponse); 
  23.     LOG.info("[Client] seqId:{} 信息已經放入,通知所有等待方", seqId); 
  24.     // 移除對應的 requestMap 
  25.     requestMap.remove(seqId); 
  26.     LOG.info("[Client] seqId:{} remove from request map", seqId); 
  27.     synchronized (this) { 
  28.         this.notifyAll(); 
  29.     } 
  30.     return this; 

獲取請求結果

•獲取相應 getResponse

1.如果結果存在,直接返回響應結果

2.否則進入等待。

3.等待結束后獲取結果。

  1. @Override 
  2. public RpcResponse getResponse(String seqId) { 
  3.     try { 
  4.         RpcResponse rpcResponse = this.responseMap.get(seqId); 
  5.         if(ObjectUtil.isNotNull(rpcResponse)) { 
  6.             LOG.info("[Client] seq {} 對應結果已經獲取: {}", seqId, rpcResponse); 
  7.             return rpcResponse; 
  8.         } 
  9.         // 進入等待 
  10.         while (rpcResponse == null) { 
  11.             LOG.info("[Client] seq {} 對應結果為空,進入等待", seqId); 
  12.             // 同步等待鎖 
  13.             synchronized (this) { 
  14.                 this.wait(); 
  15.             } 
  16.             rpcResponse = this.responseMap.get(seqId); 
  17.             LOG.info("[Client] seq {} 對應結果已經獲取: {}", seqId, rpcResponse); 
  18.         } 
  19.         return rpcResponse; 
  20.     } catch (InterruptedException e) { 
  21.         throw new RpcRuntimeException(e); 
  22.     } 

可以發現獲取部分的邏輯沒變,因為超時會返回一個超時對象:RpcResponseFactory.timeout();

這是一個非常簡單的實現,如下:

  1. package com.github.houbb.rpc.common.rpc.domain.impl; 
  2.  
  3.  
  4. import com.github.houbb.rpc.common.exception.RpcTimeoutException; 
  5. import com.github.houbb.rpc.common.rpc.domain.RpcResponse; 
  6.  
  7.  
  8. /** 
  9.  * 響應工廠類 
  10.  * @author binbin.hou 
  11.  * @since 0.0.7 
  12.  */ 
  13. public final class RpcResponseFactory { 
  14.  
  15.  
  16.     private RpcResponseFactory(){} 
  17.  
  18.  
  19.     /** 
  20.      * 超時異常信息 
  21.      * @since 0.0.7 
  22.      */ 
  23.     private static final DefaultRpcResponse TIMEOUT; 
  24.  
  25.  
  26.     static { 
  27.         TIMEOUT = new DefaultRpcResponse(); 
  28.         TIMEOUT.error(new RpcTimeoutException()); 
  29.     } 
  30.  
  31.  
  32.     /** 
  33.      * 獲取超時響應結果 
  34.      * @return 響應結果 
  35.      * @since 0.0.7 
  36.      */ 
  37.     public static RpcResponse timeout() { 
  38.         return TIMEOUT; 
  39.     } 
  40.  
  41.  

 響應結果指定一個超時異常,這個異常會在代理處理結果時拋出:

  1. RpcResponse rpcResponse = proxyContext.invokeService().getResponse(seqId); 
  2. Throwable error = rpcResponse.error(); 
  3. if(ObjectUtil.isNotNull(error)) { 
  4.     throw error; 
  5. return rpcResponse.result(); 

測試代碼

服務端

我們故意把服務端的實現添加沉睡,其他保持不變。

  1. public class CalculatorServiceImpl implements CalculatorService { 
  2.  
  3.  
  4.     public CalculateResponse sum(CalculateRequest request) { 
  5.         int sum = request.getOne()+request.getTwo(); 
  6.  
  7.  
  8.         // 故意沉睡 3s 
  9.         try { 
  10.             TimeUnit.SECONDS.sleep(3); 
  11.         } catch (InterruptedException e) { 
  12.             e.printStackTrace(); 
  13.         } 
  14.  
  15.  
  16.         return new CalculateResponse(truesum); 
  17.     } 
  18.  
  19.  

客戶端

設置對應的超時時間為 1S,其他不變:

  1. public static void main(String[] args) { 
  2.     // 服務配置信息 
  3.     ReferenceConfig<CalculatorService> config = new DefaultReferenceConfig<CalculatorService>(); 
  4.     config.serviceId(ServiceIdConst.CALC); 
  5.     config.serviceInterface(CalculatorService.class); 
  6.     config.addresses("localhost:9527"); 
  7.     // 設置超時時間為1S 
  8.     config.timeout(1000); 
  9.  
  10.  
  11.     CalculatorService calculatorService = config.reference(); 
  12.     CalculateRequest request = new CalculateRequest(); 
  13.     request.setOne(10); 
  14.     request.setTwo(20); 
  15.  
  16.  
  17.     CalculateResponse response = calculatorService.sum(request); 
  18.     System.out.println(response); 

 日志如下:

  1. .log.integration.adaptors.stdout.StdOutExImpl' adapter. 
  2. [INFO] [2021-10-05 14:59:40.974] [main] [c.g.h.r.c.c.RpcClient.connect] - RPC 服務開始啟動客戶端 
  3. ... 
  4. [INFO] [2021-10-05 14:59:42.504] [main] [c.g.h.r.c.c.RpcClient.connect] - RPC 服務啟動客戶端完成,監聽地址 localhost:9527 
  5. [INFO] [2021-10-05 14:59:42.533] [main] [c.g.h.r.c.p.ReferenceProxy.invoke] - [Client] start call remote with request: DefaultRpcRequest{seqId='62e126d9a0334399904509acf8dfe0bb', createTime=1633417182525, serviceId='calc', methodName='sum', paramTypeNames=[com.github.houbb.rpc.server.facade.model.CalculateRequest], paramValues=[CalculateRequest{one=10, two=20}]} 
  6. [INFO] [2021-10-05 14:59:42.534] [main] [c.g.h.r.c.i.i.DefaultInvokeService.addRequest] - [Client] start add request for seqId: 62e126d9a0334399904509acf8dfe0bb, timeoutMills: 1000 
  7. [INFO] [2021-10-05 14:59:42.535] [main] [c.g.h.r.c.p.ReferenceProxy.invoke] - [Client] start call channel id: 00e04cfffe360988-000004bc-00000000-1178e1265e903c4c-7975626f 
  8. ... 
  9. Exception in thread "main" com.github.houbb.rpc.common.exception.RpcTimeoutException 
  10.     at com.github.houbb.rpc.common.rpc.domain.impl.RpcResponseFactory.<clinit>(RpcResponseFactory.java:23) 
  11.     at com.github.houbb.rpc.client.invoke.impl.DefaultInvokeService.addResponse(DefaultInvokeService.java:72) 
  12.     at com.github.houbb.rpc.client.handler.RpcClientHandler.channelRead0(RpcClientHandler.java:43) 
  13.     at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) 
  14.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) 
  15.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) 
  16.     at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) 
  17.     at io.netty.handler.logging.LoggingHandler.channelRead(LoggingHandler.java:241) 
  18.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) 
  19.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) 
  20.     at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) 
  21.     at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:310) 
  22.     at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:284) 
  23.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) 
  24.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) 
  25.     at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) 
  26.     at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) 
  27.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) 
  28.     at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) 
  29.     at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) 
  30.     at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:138) 
  31.     at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645) 
  32.     at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580) 
  33.     at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497) 
  34.     at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459) 
  35.     at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) 
  36.     at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) 
  37.     at java.lang.Thread.run(Thread.java:748) 
  38. ... 
  39. [INFO] [2021-10-05 14:59:45.615] [nioEventLoopGroup-2-1] [c.g.h.r.c.i.i.DefaultInvokeService.addResponse] - [Client] seqId:62e126d9a0334399904509acf8dfe0bb 信息已超時,直接返回超時結果。 
  40. [INFO] [2021-10-05 14:59:45.617] [nioEventLoopGroup-2-1] [c.g.h.r.c.i.i.DefaultInvokeService.addResponse] - [Client] 獲取結果信息,seqId: 62e126d9a0334399904509acf8dfe0bb, rpcResponse: DefaultRpcResponse{seqId='null', error=com.github.houbb.rpc.common.exception.RpcTimeoutException, result=null
  41. [INFO] [2021-10-05 14:59:45.617] [nioEventLoopGroup-2-1] [c.g.h.r.c.i.i.DefaultInvokeService.addResponse] - [Client] seqId:62e126d9a0334399904509acf8dfe0bb 信息已經放入,通知所有等待方 
  42. [INFO] [2021-10-05 14:59:45.618] [nioEventLoopGroup-2-1] [c.g.h.r.c.i.i.DefaultInvokeService.addResponse] - [Client] seqId:62e126d9a0334399904509acf8dfe0bb remove from request map 
  43. [INFO] [2021-10-05 14:59:45.618] [nioEventLoopGroup-2-1] [c.g.h.r.c.c.RpcClient.channelRead0] - [Client] response is :DefaultRpcResponse{seqId='62e126d9a0334399904509acf8dfe0bb', error=null, result=CalculateResponse{success=truesum=30}} 
  44. [INFO] [2021-10-05 14:59:45.619] [main] [c.g.h.r.c.i.i.DefaultInvokeService.getResponse] - [Client] seq 62e126d9a0334399904509acf8dfe0bb 對應結果已經獲取: DefaultRpcResponse{seqId='null', error=com.github.houbb.rpc.common.exception.RpcTimeoutException, result=null
  45. ... 

可以發現,超時異常。

不足之處

對于超時的處理可以拓展為雙向的,比如服務端也可以指定超時限制,避免資源的浪費。

 

責任編輯:姜華 來源: 今日頭條
相關推薦

2021-10-13 08:21:52

Java websocket Java 基礎

2021-10-20 08:05:18

Java 序列化 Java 基礎

2021-10-19 08:58:48

Java 語言 Java 基礎

2021-10-21 08:21:10

Java Reflect Java 基礎

2019-09-23 19:30:27

reduxreact.js前端

2021-10-14 08:39:17

Java Netty Java 基礎

2015-11-17 16:11:07

Code Review

2019-01-18 12:39:45

云計算PaaS公有云

2018-04-18 07:01:59

Docker容器虛擬機

2024-12-06 17:02:26

2020-07-02 15:32:23

Kubernetes容器架構

2024-09-18 08:10:06

2024-10-05 00:00:06

HTTP請求處理容器

2010-05-26 17:35:08

配置Xcode SVN

2018-09-14 17:16:22

云計算軟件計算機網絡

2024-05-15 14:29:45

2021-10-27 08:10:15

Java 客戶端 Java 基礎

2011-04-06 15:55:50

開發webOS程序webOS

2015-10-15 14:16:24

2024-04-10 07:48:41

搜索引擎場景
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲36d大奶网 | 国产精品久久在线 | 夜夜夜操 | 亚洲永久免费观看 | 国产av毛片 | 欧美13videosex性极品 | 久久久入口 | 久久综合一区 | 国产精品高潮呻吟久久 | 一区二区三区亚洲 | 91久久精品国产91久久 | 国产免费福利小视频 | 日韩精品1区2区3区 国产精品国产成人国产三级 | 国产黄色一级电影 | 久久国产精品色av免费观看 | 久草在线在线精品观看 | 男女一区二区三区 | 亚洲精品自在在线观看 | 国产午夜视频 | 大学生a级毛片免费视频 | 国产亚洲精品综合一区 | 日韩在线观看中文字幕 | 亚洲精品一区二区三区中文字幕 | 国产免费一级片 | 成人久久 | 自拍偷拍第一页 | www.天天操 | 亚洲精品成人 | 国产精品黄视频 | 99久久99 | 成人在线精品 | 久久99精品久久久 | 国产高清视频一区 | 黄网站免费在线看 | 在线色网| 国产电影一区二区在线观看 | 91网站在线观看视频 | 四虎影院新网址 | 国产亚洲成av人片在线观看桃 | 女人毛片a毛片久久人人 | 亚洲一区二区三区久久久 |