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 必须处理请求集合中,才允许放入。或者直接忽略丢弃。 
  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 基础

2020-07-02 15:32:23

Kubernetes容器架构

2019-01-18 12:39:45

云计算PaaS公有云

2018-04-18 07:01:59

Docker容器虚拟机

2015-11-17 16:11:07

Code Review

2021-10-27 08:10:15

Java 客户端 Java 基础

2010-05-26 17:35:08

配置Xcode SVN

2018-09-14 17:16:22

云计算软件计算机网络

2015-05-06 09:36:05

Java语言从零开始学习

2015-10-15 14:16:24

2011-04-06 15:55:50

开发webOS程序webOS

2024-04-10 07:48:41

搜索引擎场景

2015-08-24 14:59:06

Java线程

2018-03-14 11:15:06

2019-08-12 09:36:49

点赞
收藏

51CTO技术栈公众号