Redis系列之简单实现watchDog自动续期机制

2023-12-13 07:28

本文主要是介绍Redis系列之简单实现watchDog自动续期机制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在分布锁的实际使用中,可能会遇到一种情况,一个业务执行时间很长,已经超过redis加锁的时间,也就是锁已经释放了,但是业务还没执行完成,这时候其它线程还是可以获取锁,那就没保证线程安全

项目环境:

  • JDK 1.8

  • SpringBoot 2.2.1

  • Maven 3.2+

  • Mysql 8.0.26

  • spring-boot-starter-data-redis 2.2.1

  • jedis3.1.0

  • 开发工具

    • IntelliJ IDEA

    • smartGit

先搭建一个springboot集成jedis的例子工程,参考我之前的博客,

抽象类,实现一些共用的逻辑

package com.example.jedis.common;import lombok.extern.slf4j.Slf4j;import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;import static com.example.jedis.common.RedisConstant.DEFAULT_EXPIRE;
import static com.example.jedis.common.RedisConstant.DEFAULT_TIMEOUT;@Slf4j
public abstract class AbstractDistributedLock implements DistributedLock {@Overridepublic boolean acquire(String lockKey, String requestId, int expireTime, int timeout) {expireTime = expireTime <= 0 ? DEFAULT_EXPIRE : expireTime;timeout = timeout < 0 ? DEFAULT_TIMEOUT : timeout * 1000;long start = System.currentTimeMillis();try {do {if (doAcquire(lockKey, requestId, expireTime)) {watchDog(lockKey, requestId, expireTime);return true;}TimeUnit.MILLISECONDS.sleep(100);} while (System.currentTimeMillis() - start < timeout);} catch (Exception e) {Throwable cause = e.getCause();if (cause instanceof SocketTimeoutException) {// ignore exceptionlog.error("sockTimeout exception:{}", e);}else if (cause instanceof  InterruptedException) {// ignore exceptionlog.error("Interrupted exception:{}", e);}else {log.error("lock acquire exception:{}", e);}throw new LockException(e.getMessage(), e);}return false;}@Overridepublic boolean release(String lockKey, String requestId) {try {return doRelease(lockKey, requestId);} catch (Exception e) {log.error("lock release exception:{}", e);throw new LockException(e.getMessage(), e);}}protected abstract boolean doAcquire(String lockKey, String requestId, int expireTime);protected abstract boolean doRelease(String lockKey, String requestId);protected abstract void watchDog(String lockKey, String requestId, int expireTime);}

具体的实现,主要是基于一个定时任务,时间间隔一定要比加锁时间少一点,这里暂时少1s,加上一个lua脚本进行检测,检测不到数据,就关了定时任务

package com.example.jedis.common;import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;@Component
@Slf4j
public class JedisLockTemplate extends AbstractRedisLock implements InitializingBean {private String UNLOCK_LUA = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";private String WATCH_DOG_LUA = "local lock_key=KEYS[1]\n" +"local lock_value=ARGV[1]\n" +"local lock_ttl=ARGV[2]\n" +"local current_value=redis.call('get',lock_key)\n" +"local result=0\n" +"if lock_value==current_value then\n" +"    redis.call('expire',lock_key,lock_ttl)\n" +"    result=1\n" +"end\n" +"return result";private static final Long UNLOCK_SUCCESS = 1L;private static final Long RENEWAL_SUCCESS = 1L;@Autowiredprivate JedisTemplate jedisTemplate;private ScheduledThreadPoolExecutor scheduledExecutorService;@Overridepublic void afterPropertiesSet() throws Exception {this.UNLOCK_LUA = jedisTemplate.scriptLoad(UNLOCK_LUA);this.WATCH_DOG_LUA = jedisTemplate.scriptLoad(WATCH_DOG_LUA);scheduledExecutorService = new ScheduledThreadPoolExecutor(1);}@Overridepublic boolean doAcquire(String lockKey, String requestId, int expire) {return jedisTemplate.setnxex(lockKey, requestId, expire);}@Overridepublic boolean doRelease(String lockKey, String requestId) {Object eval = jedisTemplate.evalsha(UNLOCK_LUA, CollUtil.newArrayList(lockKey), CollUtil.newArrayList(requestId));if (UNLOCK_SUCCESS.equals(eval)) {scheduledExecutorService.shutdown();return true;}return false;}@Overridepublic void watchDog(String lockKey, String requestId, int expire) {int period = getPeriod(expire);if (scheduledExecutorService.isShutdown()) {scheduledExecutorService = new ScheduledThreadPoolExecutor(1);}scheduledExecutorService.scheduleAtFixedRate(new WatchDogTask(scheduledExecutorService, CollUtil.newArrayList(lockKey), CollUtil.newArrayList(requestId, Convert.toStr(expire))),1,period,TimeUnit.SECONDS);}class WatchDogTask implements Runnable {private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;private List<String> keys;private List<String> args;public WatchDogTask(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor, List<String> keys, List<String> args) {this.scheduledThreadPoolExecutor = scheduledThreadPoolExecutor;this.keys = keys;this.args = args;}@Overridepublic void run() {log.info("watch dog for renewal...");Object evalsha = jedisTemplate.evalsha(WATCH_DOG_LUA, keys, args);if (!evalsha.equals(RENEWAL_SUCCESS)) {scheduledThreadPoolExecutor.shutdown();}log.info("renewal result:{}, keys:{}, args:{}", evalsha, keys, args);}}private int getPeriod(int expire) {if (expire < 1)throw new LockException("expire不允许小于1");return expire - 1;}}

写一个测试Controller类,开始用SpringBoot测试类的,但是发现有时候还是经常出现一些连接超时情况,这个可能是框架兼容的bug

package com.example.jedis.controller;import com.example.jedis.common.JedisLockTemplate;
import com.example.jedis.common.Lock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;@RestController
@Slf4j
public class TestController {private static final String REDIS_KEY = "test:lock";@Autowiredprivate JedisLockTemplate jedisLockTemplate;@GetMapping("test")public void test(@RequestParam("threadNum")Integer threadNum) throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(threadNum);IntStream.range(0, threadNum).forEach(e->{new Thread(new RunnableTask(countDownLatch)).start();});countDownLatch.await();}@GetMapping("testLock")@Lock(lockKey = "test:api", requestId = "123", expire = 5, timeout = 3)public void testLock() throws InterruptedException {doSomeThing();}class RunnableTask implements Runnable {CountDownLatch countDownLatch;public RunnableTask(CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;}@Overridepublic void run() {redisLock();countDownLatch.countDown();}}private void redisLock() {String requestId = getRequestId();Boolean lock = jedisLockTemplate.acquire(REDIS_KEY, requestId, 5, 3);if (lock) {try {doSomeThing();} catch (Exception e) {jedisLockTemplate.release(REDIS_KEY, requestId);} finally {jedisLockTemplate.release(REDIS_KEY, requestId);}} else {log.warn("获取锁失败!");}}private void doSomeThing() throws InterruptedException {log.info("do some thing");Thread.sleep(15 * 1000);}private String getRequestId() {String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";Random random=new Random();StringBuffer sb=new StringBuffer();for(int i=0;i<32;i++){int number=random.nextInt(62);sb.append(str.charAt(number));}return sb.toString();}}
# 模拟100个并发请求
curl http://127.0.0.1:8080/springboot-jedis/test?threadNum=100

长事务还没执行完成,会自动进行续期

在这里插入图片描述

模拟100个线程的场景,只有一个线程会获取到锁

在这里插入图片描述

参考资料:

  • https://github.com/finefuture/RedisLock-with-WatchDog/blob/master/RedisLock.java
  • https://www.cnblogs.com/crazymakercircle/p/14731826.html
  • https://blog.csdn.net/Cocoxzq000/article/details/121575272

这篇关于Redis系列之简单实现watchDog自动续期机制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Redis MCP 安装与配置指南

《RedisMCP安装与配置指南》本文将详细介绍如何安装和配置RedisMCP,包括快速启动、源码安装、Docker安装、以及相关的配置参数和环境变量设置,感兴趣的朋友一起看看吧... 目录一、Redis MCP 简介二、安www.chinasem.cn装 Redis MCP 服务2.1 快速启动(推荐)2.

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库