AOP+Redisson 延时队列,实现缓存延时双删策略

一、缓存延时双删

关于缓存和数据库中的数据保持一致有很多种方案,但不管是单独在修改数据库之前,还是之后去删除缓存都会有一定的风险导致数据不一致。而延迟双删是一种相对简单并且收益比较高的实现最终一致性的方式,即在删除缓存之后,间隔一个短暂的时间后再删除缓存一次。这样可以避免并发更新时,假如缓存在第一次被删除后,被其他线程读到旧的数据更新到了缓存,第二次删除还可以补救,从而时间最终一致性。

实现延时双删的方案也有很多,有本地用 Thread.sleep(); 睡眠的方式做延时,也有借助第三方消息中间件做延时消息等等,本文基于 Redisson 中的延时队列进行实验。

Redisson 中提供了 RDelayedQueue 可以迅速实现延时消息,本文所使用的 Redisson 版本为 3.19.0

二、Redisson 实现延时消息

新建 SpringBoot 项目,在 pom 中加入下面依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.19.0</version>
</dependency>

yum 配置中,增加 redis 的信息:

spring:
  redis:
    timeout: 6000
    password:
    cluster:
      max-redirects:
      nodes:
        - 192.168.72.120:7001
        - 192.168.72.121:7001
        - 192.168.72.122:7001

声明 RedissonClient

@Configuration
public class RedissonConfig {

    @Bean
    public RedissonClient getRedisson(RedisProperties redisProperties) {
        Config config = new Config();
        String[] nodes = redisProperties.getCluster().getNodes().stream().filter(StringUtils::isNotBlank).map(node -> "redis://" + node).collect(Collectors.toList()).toArray(new String[]{});
        ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(nodes);
        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            clusterServersConfig.setPassword(redisProperties.getPassword());
        }
        clusterServersConfig.setConnectTimeout((int) (redisProperties.getTimeout().getSeconds() * 1000));
        clusterServersConfig.setScanInterval(2000);
        return Redisson.create(config);
    }
}

延时队列实现延时消息:

@Slf4j
@Component
public class MsgQueue {

    @Resource
    RedissonClient redissonClient;

    public static final String QUEUE_KEY = "DELAY-QUEUE";

    // 发送消息
    public void send(String msg, Long time, TimeUnit unit) {
        // 获取队列
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(QUEUE_KEY);
        // 延时队列
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        // 添加数据
        delayedQueue.offer(msg, time, unit);
    }

    // 消息监听
    @PostConstruct
    public void listen() {
        CompletableFuture.runAsync(() -> {
            RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(MsgQueue.QUEUE_KEY);
            log.info("延时消息监听!");
            while (true) {
                try {
                    consumer(blockingQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    // 消费消息
    public void consumer(String msg) {
        log.info("收到延时消息: {} , 当前时间: {} ", msg, LocalDateTime.now().toString());
    }
    
}

测试延时消息:

@Slf4j
@RestController
@RequestMapping("/msg")
public class MsgController {
    @Resource
    MsgQueue queue;

    @GetMapping("/test")
    public void test() {
        String msg = "你好";
        queue.send(msg, 5L, TimeUnit.SECONDS);
    }

}

上面发送了延时5秒的消息,运行后可以看到日志:

在这里插入图片描述

三、AOP+延时队列,实现延时双删策略

缓存延时删除队列:

@Slf4j
@Component
public class CacheQueue {

    @Resource
    RedissonClient redissonClient;

    public static final String QUEUE_KEY = "CACHE-DELAY-QUEUE";

    // 延时删除
    public void delayedDeletion(String key, Long time, TimeUnit unit) {
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(QUEUE_KEY);
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        log.info("延时删除key: {} , 当前时间: {} ", key, LocalDateTime.now().toString());
        delayedQueue.offer(key, time, unit);
    }

    // 消息监听
    @PostConstruct
    public void listen() {
        CompletableFuture.runAsync(() -> {
            RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(CacheQueue.QUEUE_KEY);
            while (true) {
                try {
                    consumer(blockingQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    // 消费消息
    public void consumer(String key) {
        log.info("删除key: {} , 当前时间: {} ", key, LocalDateTime.now().toString());
        redissonClient.getBucket("key").delete();
    }
}

定义缓存和删除缓存注解:

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.METHOD)
public @interface Cache {
    String name() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.METHOD)
public @interface DeleteCache {
    String name() default "";
}

缓存AOP逻辑:

@Aspect
@Component
public class CacheAspect {

    @Resource
    RedissonClient redissonClient;

    private final Long validityTime = 2L;


    @Pointcut("@annotation(com.bxc.retrydemo.anno.Cache)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        Cache ann = ((MethodSignature) pjp.getSignature()).getMethod().getDeclaredAnnotation(Cache.class);
        if (Objects.nonNull(ann) && StringUtils.isNotBlank(ann.name())) {
            Object proceed = redissonClient.getBucket(ann.name()).get();
            if (Objects.nonNull(proceed)){
                return proceed;
            }
        }
        Object proceed = pjp.proceed();
        if (Objects.nonNull(ann) && StringUtils.isNotBlank(ann.name())) {
            redissonClient.getBucket(ann.name()).set(proceed, validityTime, TimeUnit.HOURS);
        }
        return proceed;
    }
}

延时双删 AOP 逻辑:

@Aspect
@Component
public class DeleteCacheAspect {

    @Resource
    RedissonClient redissonClient;

    @Resource
    CacheQueue cacheQueue;

    private final Long delayedTime = 3L;


    @Pointcut("@annotation(com.bxc.retrydemo.anno.DeleteCache)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        // 第一次删除缓存
        DeleteCache ann = ((MethodSignature) pjp.getSignature()).getMethod().getDeclaredAnnotation(DeleteCache.class);
        if (Objects.nonNull(ann) && StringUtils.isNotBlank(ann.name())) {
            redissonClient.getBucket(ann.name()).delete();
        }
        // 执行业务逻辑
        Object proceed = pjp.proceed();
        //延时删除
        if (Objects.nonNull(ann) && StringUtils.isNotBlank(ann.name())) {
            cacheQueue.delayedDeletion(ann.name(), delayedTime, TimeUnit.SECONDS);
        }
        return proceed;
    }
}

伪业务逻辑使用:

@Slf4j
@Service
public class MsgServiceImpl implements MsgService {

    @Cache(name = "you key")
    @Override
    public String find() {
        // 数据库操作
        // ....
        // 数据库操作结束
        return "数据结果";
    }


    @DeleteCache(name = "you key")
    @Override
    public void update() {
        // 数据库操作
        // ....
        // 数据库操作结束
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

前端实现界面切换

样式切换主题 常用的主题切换实现方式之一&#xff0c;就是通过 link 标签的 rel 属性来实现的 当 rel 标签的值是 alternate&#xff0c;就代表该样式是可以替换的 title 属性要加就全加上或者全不加&#xff0c;因为 title 会导致系统直接识别成样式文件&#xff0c;意思就是…

DevSecOps 度量指标介绍

目录 一、度量指标概述 1.1 概述 二、度量指标内容介绍 2.1 指标概览 2.1.1 指标概览说明 2.1.2 指标概览图 2.1.3 指标概览图说明 2.2 必选指标 2.2.1 必选指标含义说明 2.2.2 必选指标内容 2.3 可选指标 2.3.1 可选指标含义说明 2.3.2 可选指标内容 一、度量指标…

北京大学:警惕ChatGPT等大模型遏制人类的创新能力

‍ 导语&#xff1a;这篇论文通过实验和跟踪调查&#xff0c;探讨了ChatGPT在有无的情况下对创新能力的影响。虽然ChatGPT能提升人的创新表现&#xff0c;但是当它停止工作时&#xff0c;创新性会回归基线。更为重要的是&#xff0c;使用ChatGPT可能导致内容同质化&#xff0c;…

C#使用DateTime结构的ParseExact方法和Parse方法分别将字符串转化为日期格式

目录 一、涉及到的知识点 1.ParseExact(String, String, IFormatProvider) 2.DateTime.ToLongDateString 方法 3.Parse(String)方法 二、实例1&#xff1a;ParseExact方法 1.源码 2.生成效果 3.示例2 三、实例2&#xff1a;Parse方法 在程序设计过程中&#xff0c;经…

有趣的css - 好看的呼吸灯效果

整体效果 这个效果主要用 css3 的 animation 属性来实现的。 这个效果可以用作在网站的整体 Loading&#xff0c;也可以放在网站首屏当一个 banner 的背景也是非常棒的&#xff01; 代码部分 html 部分代码&#xff1a; <div class"app"><span class&quo…

4. MySQL 多表查询

重点&#xff1a; MySQL 的 三种安装方式&#xff1a;包安装&#xff0c;二进制安装&#xff0c;源码编译安装。 MySQL 的 基本使用 MySQL 多实例 DDLcreate alter drop DML insert update delete DQL select 3.5&#xff09;DDL 语句 表&#xff1a;二维关系 设计表&…

SAR图像目标识别的可解释性问题探讨

源自&#xff1a;雷达学报 作者&#xff1a;郭炜炜, 张增辉, 郁文贤&#xff0c;孙效华 “人工智能技术与咨询” 发布 摘 要 合成孔径雷达(SAR)图像目标识别是实现微波视觉的关键技术之一。尽管深度学习技术已被成功应用于解决SAR图像目标识别问题&#xff0c;并显著超越了…

扫描电子显微镜电子束辐射损伤和如何减轻

扫描电镜&#xff08;Scanning Electron Microscope, SEM&#xff09;是一种常用的材料表征技术&#xff0c;它通过聚焦电子束扫描样品表面&#xff0c;利用电子与样品相互作用产生的信号来获得高分辨率的形貌图像。然而&#xff0c;电子束的辐射可能会对样品造成损伤&#xff…

初探 Backstage:快速上手指南

坦白说&#xff0c;虽然我之前阅读过相关文档&#xff0c;但实际上从未亲自尝试运行 Backstage。我一直有种感觉&#xff0c;Backstage 不过是一个开发者门户而非开发者平台。上周在 分享我对平台工程的理解 后&#xff0c;朋友圈中有人提议我写一篇关于 Backstage 入门的文章。…

(M)unity受伤反弹以及死亡动画

受伤反弹 1.在人物控制脚本中添加受伤后速度将为0&#xff0c;并添加一个反弹的力 在刷新移动时&#xff0c;需要在没有受伤的状态 public bool isHurt; public float hurtForce; private void FixedUpdate() {if(!isHurt)Move(); }public void GetHurt(Transform attacker) …

11.1 StringBuffer类(血干JAVA系列)

StringBuffer类 11.1.1 认识 StringBuffer 类1.实例操作1——字符串连接操作(append)【例11.1】通过append()方法连接各种类型的数据【例11.2】验证StringBuffer的内容是可以修改的 2.实例操作2——在任意位置处为StringBuffer添加内容&#xff08;insert&#xff09;【例11.3】…

Mac本上快速搭建redis服务指南

文章目录 前言1. 查看可用版本2.安装指定版本的redis3.添加redis到PATH3.1 按照执行brew install命令后输出的提示信息执行如下命令将redis添加到PATH3.2 执行命令要添加的redis环境信息生效: 4. 增加密码4.1 在文件中找到requirepass所在位置4.2 去掉注释并将requirepass值替换…

微信小程序开发如何实现阴影/悬浮效果

显示&#xff1a; 实现&#xff1a; <view style"width: 100%;height: 500rpx; display: flex; justify-content:space-evenly;align-items: center; "><view style"width: 200rpx;height:100rpx;background-color: aqua; display: flex; align-item…

使用antdesign3.0、echarts制作固定资产后台管理系统原型

学了半个月Axure,周末用半天时间&#xff0c;照着网上的模板做了一个固定资产后台管理系统的原型。重点是内联框架的使用&#xff0c;和对echarts表格js代码的调试。原型链接&#xff1a;https://qoz5rv.axshare.com 资产管理系统

SpringBoot 3.1.7集成 Redis 6.2.13及Redis哨兵模式安装

一、背景 我们在开发互联网项目时&#xff0c;常常需要需要用到分布式缓存&#xff0c;目前最流行的分布式缓存就是Redis了&#xff0c;没有之一&#xff0c;接下来&#xff0c;开始我们的Redis实战之旅吧 二、安装单机Redis 1 版本选择 打开Redis官网&#xff0c;找一个版…

JVM篇----第十三篇

系列文章目录 文章目录 系列文章目录前言一、Parallel Old 收集器(多线程标记整理算法)二、CMS 收集器(多线程标记清除算法)三、G1 收集器前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看…

四川古力未来科技公司抖音小店选品攻略从零到一

随着抖音的日益火爆&#xff0c;抖音小店也应运而生&#xff0c;成为了电商行业的新宠儿。但对于许多新手商家来说&#xff0c;如何从众多的商品中挑选出适合自己店铺的商品&#xff0c;却是一件非常头疼的事情。本文将为你揭秘抖音小店的选品攻略&#xff0c;让你轻松玩转电商…

免费分享一套微信小程序外卖跑腿点餐(订餐)系统(uni-app+SpringBoot后端+Vue管理端技术实现) ,帅呆了~~

大家好&#xff0c;我是java1234_小锋老师&#xff0c;看到一个不错的微信小程序外卖跑腿点餐(订餐)系统(uni-appSpringBoot后端Vue管理端技术实现) &#xff0c;分享下哈。 项目视频演示 【免费】微信小程序外卖跑腿点餐(订餐)系统(uni-appSpringBoot后端Vue管理端技术实现)…

好友管理系统----Python实例练习

题目描述 如今的社交软件层出不穷&#xff0c;虽然功能千变万化&#xff0c;但都具有好友管理系统的基本功能&#xff0c;包括添加好友&#xff0c;删除好友&#xff0c;备注好友&#xff0c;展示好友等。次案例要求用Python中的列表知识实现。 程序代码 print("欢迎使…

js引入jqury实现数字滚动效果

页面展示 需要滚动的数字 加个类名 eg:counter <div class"desc_item"><div class"desc_top"><span class"counter">20</span>年</div><div class"desc_btm">20年软件开发经验</div></d…
最新文章