redis相关异常之RedisConnectionExceptionRedisCommandTimeoutException

本文只是分析Letture类型的Redis 池化连接出现的连接超时异常、读超时异常问题。

1.RedisConnectionException

默认是10秒。
通过如下可以配置:

public class MyLettuceClientConfigurationBuilderCustomizer implements LettuceClientConfigurationBuilderCustomizer {@Overridepublic void customize(LettuceClientConfiguration.LettuceClientConfigurationBuilder clientConfigurationBuilder) {
//        spring.redis.timeout等价clientConfigurationBuilder.commandTimeout(Duration.ofSeconds(100));
//        控制连接超时时间,默认是10秒ClientOptions.Builder builder = ClientOptions.builder().socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(10)).build());clientConfigurationBuilder.clientOptions(builder.build());}
}

2.RedisCommandTimeoutException

结论:抛出RedisCommandTimeoutException异常并非数据的写一定失败。只不过Redis内部超时逻辑跟写逻辑是异步处理,所以存在写成功后仍然抛出异常的情况。但是只要出现该异常必须得处理。

io.lettuce.core.RedisCommandTimeoutException: Command timed out after 2 second(s)

2.1.CommandHandler限制

CommandHandler是Netty中的handler。只不过其同时充当入栈、出栈handler。通俗点讲是Redis Write & Flush 数据到通道NioSocketChannel的必经之路。

AsyncCommand存在两大核心功能。其一是包裹用户数据,其二是实现了CompletableFuture接口,方便实现异步相关操作。

public class CommandHandler extends ChannelDuplexHandler implements HasQueuedCommands {private void writeSingleCommand(ChannelHandlerContext ctx, RedisCommand<?, ?, ?> command, ChannelPromise promise){if (!isWriteable(command)) {// 此处的就是判断是否存在超时的核心之处,借用CompletableFuture异步操作功能promise.trySuccess();// 此时说明数据写过程中超过用户设定的超时时间return;}...ctx.write(command, promise);// 数据正常写入,最终归宿是服务端}private static boolean isWriteable(RedisCommand<?, ?, ?> command) {return !command.isDone();}
}
public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {public boolean isDone() {return result != null;}
}

通过上述得知,只要CompletableFuture内部的变量result不为空,则就会按TimeoutException处理。所以result值何时赋值呢?

如下所示,CommandHandler处理完数据之后会通过如下方式设置result的值。

public class AsyncCommand<K, V, T> extends CompletableFuture<T> implements RedisCommand<K, V, T>, RedisFuture<T>,CompleteableCommand<T>, DecoratedCommand<K, V, T> {protected void completeResult() {if (command.getOutput() == null) {complete(null);} else if (command.getOutput().hasError()) {doCompleteExceptionally(ExceptionFactory.createExecutionException(command.getOutput().getError()));} else {// 成功发送则Output为字符串类型的“ok”complete(command.getOutput().get());}}
}

3.超时处理时机

3.1.阻塞等待超时

class FutureSyncInvocationHandler extends AbstractInvocationHandler {protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {try {Method targetMethod = this.translator.get(method);// CommandExpiryWriter#writerObject result = targetMethod.invoke(asyncApi, args);if (result instanceof RedisFuture<?>) {...long timeout = getTimeoutNs(command);//用户自定义的超时时间//command:AsyncCommand 利用CompletableFuture异步特性return LettuceFutures.awaitOrCancel(command, timeout, TimeUnit.NANOSECONDS);}return result;} catch (InvocationTargetException e) {throw e.getTargetException();}}
}
public class LettuceFutures {public static <T> T awaitOrCancel(RedisFuture<T> cmd, long timeout, TimeUnit unit) {try {//阻塞 其实内存调用的CompletableFuture#get阻塞方法。如果返回TimeoutExeception则说明AsyncCommand没有执行完毕,超时处理if (!cmd.await(timeout, unit)) {cmd.cancel(true);throw ExceptionFactory.createTimeoutException(Duration.ofNanos(unit.toNanos(timeout)));}return cmd.get();//这个方法还是调用CompletableFuture#get阻塞方法,但是该方法是根据内部属性result进行判断} catch (RuntimeException e) {throw e;} catch (ExecutionException e) {if (e.getCause() instanceof RedisCommandExecutionException) {throw ExceptionFactory.createExecutionException(e.getCause().getMessage(), e.getCause());}if (e.getCause() instanceof RedisCommandTimeoutException) {throw new RedisCommandTimeoutException(e.getCause());}throw new RedisException(e.getCause());} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new RedisCommandInterruptedException(e);} catch (Exception e) {throw ExceptionFactory.createExecutionException(null, e);}}
}

如下伪代码所示:如果result不为null,则根据result类型抛出相关异常。否则通过timedGet在规定时间内阻塞等待,超时则抛出TimeoutException。

public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {public T get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException {Object r;long nanos = unit.toNanos(timeout);return reportGet((r = result) == null ? timedGet(nanos) : r);}
}

3.2.定时任务超时处理

public class CommandExpiryWriter implements RedisChannelWriter {public <K, V, T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) {potentiallyExpire(command, getExecutorService());//开启定时任务return writer.write(command);//DefaultEndPoint#write}private void potentiallyExpire(RedisCommand<?, ?, ?> command, ScheduledExecutorService executors) {long timeout = applyConnectionTimeout ? this.timeout : source.getTimeout(command);//用户自定义的超时时间if (timeout <= 0) {return;}// 从 timeout 时间之后开始执行定时任务。此时result值如果存在值则说明超时ScheduledFuture<?> schedule = executors.schedule(() -> {if (!command.isDone()) {command.completeExceptionally(ExceptionFactory.createTimeoutException(Duration.ofNanos(timeUnit.toNanos(timeout))));}}, timeout, timeUnit);if (command instanceof CompleteableCommand) {((CompleteableCommand) command).onComplete((o, o2) -> {if (!schedule.isDone()) {schedule.cancel(false);}});}}
}

重点:定时任务判断成功与否的唯一条件就是result是否存在值。情况1,如果此时result = ok表明数据已经在服务端落盘成功,但是同样会抛出RedisCommandTimeoutException。情况2,发送之前出现异常则result值为Throwable类型的异常值。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/14231.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VUE3-04

1. 编写代码过程中的问题与解决 1.1 错误&#xff1a;cant read property of undefined(name) &#xff08;1&#xff09;首先定位错误的位置 &#xff08;2&#xff09;逐一排查问题&#xff1a;注释代码&#xff1b;debugger&#xff1b;console.log &#xff08;3&#xff0…

ComPDFKit PDF SDK库(支持Windows、Web、Android、iOS、Mac等平台)

ComPDFKit提供专业、全平台支持的PDF开发库&#xff0c;包括Windows、Mac、Linux、Android、iOS、Web平台。开发者可以快速、灵活整合PDF功能到各开发平台的软件、程序、系统中。丰富的功能&#xff0c;多种开发语言&#xff0c;灵活的部署方案可供选择&#xff0c;满足您对PDF…

数组传参,指针传参

文章目录 一维数组传参二维数组传参一级指针传参二级指针传参 一维数组传参 二维数组传参 一级指针传参 二级指针传参

基于stm32单片机的直流电机速度控制——LZW

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 目录 一、实验目的二、实验方法三、实验设计1.实验器材2.电路连接3.软件设计&#xff08;1&#xff09;实验变量&#xff08;2&#xff09;功能模块a&#xff09;电机接收信号…

AtCoder Beginner Contest 312(A~D)

A //语法题也要更仔细嘞&#xff0c;要不然也会wa #include <bits/stdc.h> // #pragma GCC optimize(3,"Ofast","inline") // #pragma GCC optimize(2) using namespace std; typedef long long LL; #define int LL typedef pair<int, int> …

代码随想录-回溯算法(分割问题)|ACM模式

目录 前言&#xff1a; 131. 分割回文串 题目描述&#xff1a; 输入输出描述&#xff1a; 思路和想法&#xff1a; 93. 复原 IP 地址 题目描述&#xff1a; 输入输出描述&#xff1a; 思路和想法&#xff1a; 前言&#xff1a; 回溯算法中的分割问题&#xff0c;是可以…

Java【Spring】项目创建、存储和获取 Bean 的基本方式

文章目录 前言一、创建 Spring 项目1, 创建 Maven 项目2, 添加 Spring 依赖3, 创建启动类 二、存储 Bean 的基本方式1, 创建 Bean2, 存储 Bean 三、获取 Bean 的基本方式1, 获取上下文对象2, 获取 Bean3, 使用 Bean 总结 前言 各位读者好, 我是小陈, 这是我的个人主页, 希望我的…

Python基础入门教程(上)

目录 一、你好Python 1.1、Python安装 win版 Linux版 1.2、第一个Python程序 二、Python基本语法 2.1、字面量 2.2、注释 2.3、变量 2.4、数据类型 type()函数 字符串类型的不同定义方式 2.5、数据类型转换 ​编辑 2.6、标识符 2.7、运算符 2.8、字符串扩展 …

基于aarch64分析kernel源码 三:启动代码分析

一、内核启动入口点 /** Kernel startup entry point.* ---------------------------** The requirements are:* MMU off, D-cache off, I-cache on or off,* x0 physical address to the FDT blob.* 这部分注释说明了内核启动入口点的要求和约束条件。* 要求包括&…

Vue2基础五、工程化开发

零、文章目录 Vue2基础五、工程化开发 1、工程化开发和脚手架 &#xff08;1&#xff09;开发 Vue 的两种方式 核心包传统开发模式&#xff1a;基于 html / css / js 文件&#xff0c;直接引入核心包&#xff0c;开发 Vue。工程化开发模式&#xff1a;基于构建工具&#xf…

【Python】数据分析+数据挖掘——探索Pandas中的索引与数据组织

前言 在数据科学和数据分析领域&#xff0c;Pandas是一个备受喜爱的Python库。它提供了丰富的数据结构和灵活的工具&#xff0c;帮助我们高效地处理和分析数据。其中&#xff0c;索引在Pandas中扮演着关键角色&#xff0c;它是一种强大的数据组织和访问机制&#xff0c;使我们…

【Unity2D】角色动画的切换

动画状态转换 第一种方法是设置一个中间状态&#xff0c;从中间状态向其余各种状态切换&#xff0c;且各状态向其他状态需要设置参数 实现动作转移时右键点击Make Transition即可 实现动画转移需要设置条件 点击一种动画到另一种动画的线 &#xff0c;然后点击加号添加Condi…

玩转LaTeX(三)【数学公式(基础)、​矩阵、多行公式】

数学公式基础 导言区&#xff08;引包&#xff09; \usepackage{amsmath} %带星号的eqution 正文区 \begin{document}%数学公式初步 \section{简介} \LaTeX{}将排版内容分为文本模式和数学模式。文本模式用于普通文本排版&#xff0c;数学模式用于数学公式排版。 …

【字节三面】41. 缺失的第一个正数

41. 缺失的第一个正数 解题思路 在原数组上进行操作 如果数字是2 将其放在索引为1的位置上数字x 放在索引为x - 1的位置上对于长度为n的数组 其中没有出现的最小正整数只能在[1,n 1]引入如果1 - n 这些数都出现了 那么答案就是n 1如果都没有出现完全 那么答案就在[1,n]中没…

【LeetCode】206.反转链表

题目 给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5] 输出&#xff1a;[5,4,3,2,1]示例 2&#xff1a; 输入&#xff1a;head [1,2] 输出&#xff1a;[2,1]示例 3&#xff1a; …

【LeetCode 热题 100】矩阵 专题(大多原地算法,需要一定思维)

解题思路 在 代码注释中&#xff01; 文章目录 73. 矩阵置零54. 螺旋矩阵48. 旋转图像240. 搜索二维矩阵 II 73. 矩阵置零 class Solution { public:void setZeroes(vector<vector<int>>& matrix) {// 难点&#xff1a;原地算法// 直接复用 matrix 第一行 和 …

oracle,获取每日24*60,所有分钟数

前言&#xff1a; 为规范用户的时间录入&#xff0c;因此我们采用下拉的方式&#xff0c;让用户选择需要的时间&#xff0c;因此我们需要将一天24小时的时间拆分为类似00:00,00:01...23:00,23:01,23:59。因此我们需要生成24*601440行的下拉复选值。具体效果如下图所示。 思路 1…

libuv库学习笔记-processes

Processes libuv提供了相当多的子进程管理函数&#xff0c;并且是跨平台的&#xff0c;还允许使用stream&#xff0c;或者说pipe完成进程间通信。 在UNIX中有一个共识&#xff0c;就是进程只做一件事&#xff0c;并把它做好。因此&#xff0c;进程通常通过创建子进程来完成不…

微信小程序 background-image直接设置本地图片路径,编辑器正常显示,真机运行不显示解决方法

项目场景 微信小程序&#xff0c;设置background-image直接设置本地图片路径。 问题描述 编辑器正常显示&#xff0c;真机运行不显示 原因分析 background-image只能用网络url或者base64图片编码。 解决方案 1、将本地图片转为网络url后设置到background-image上 例如&…

nestjs+typeorm+mysql基本使用学习

初始化项目 安装依赖 npm i -g nest/cli 新建项目 nest new project-name 命令行创建 创建Controller&#xff1a;nest g co test 创建Module&#xff1a;nest g mo test 创建Service&#xff1a;nest g service test 请求创建 123123 接口文档swagger 安装依赖 npm…