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

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三

Redis中Set结构使用过程与原理说明

《Redis中Set结构使用过程与原理说明》本文解析了RedisSet数据结构,涵盖其基本操作(如添加、查找)、集合运算(交并差)、底层实现(intset与hashtable自动切换机制)、典型应用场... 目录开篇:从购物车到Redis Set一、Redis Set的基本操作1.1 编程常用命令1.2 集

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、