基于Redis6.0 tracking客户端缓存实现本地缓存

2024-02-03 16:52

本文主要是介绍基于Redis6.0 tracking客户端缓存实现本地缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

自己搭建了个小博客,本文与这篇文章同步:

基于Redis6.0 tracking客户端缓存实现本地缓存

1.需求背景

有一种业务场景:数据变更频率低、数据量不大,实时性要求低,但是查询频率很高。现在大部分的Java应用都是分布式,所以常见的做法是使用Redis远程缓存方案,但是那样的话当访问数据频率很频繁的时候我们的网络I/O开销会很高。如果换成本地缓存的话效果会更好,因为本地缓存没有网络开销,访问速度快,但受限于内存,不适合存储大量数据。但是如果使用本地缓存,如何能保证多个应用实例的本地缓存和远程缓存的数据一致性?

所以我们的需求就变更为我们需要使用本地缓存,但是当Redis远程缓存出现数据变更的时候,所有Java应用实例的本地缓存都需要得到通知并刷新它本地缓存的数据。

到了Redis6+后,官方推出了一个Client-side caching in Redis

客户端缓存是一种用于创建高性能服务的技术,它可以利用应用服务器上的可用内存(这些服务器通常是一些不同于数据库服务器的节点),在应用服务端商直接存储数据库中的一些信息。与访问数据库等网络服务相比,访问本地内存所需要的时间消耗要少得多,因此这个模式可以大大缩短应用程序获取数据的延迟,同时也能减轻数据库的负载压力。

2.项目实战
pom依赖

redis6.x才开始支持客户端缓存功能,lettuce依赖也需要使用6.x的版本


<!--SpringDataRedis的2.3.9版本并不支持Redis 6.2提供的GEOSEARCH命令,因此我们需要提示其版本,修改自己的POM-->
<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>2.6.2</version>
</dependency><dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId><version>6.1.6.RELEASE</version>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.3.9.RELEASE</version>
</dependency><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>2.8.8</version>
</dependency>
CaffeineCacheAccessor
package cn.edu.gxust.redis.context;import com.github.benmanes.caffeine.cache.Cache;
import io.lettuce.core.support.caching.CacheAccessor;
import lombok.extern.slf4j.Slf4j;/*** @author zhaoyijie* @since 2024/1/21 10:07*/
@Slf4j
public class CaffeineCacheAccessor implements CacheAccessor {private Cache cache;public CaffeineCacheAccessor(Cache cache) {this.cache = cache;}@Overridepublic Object get(Object key) {log.info("caffeine get => {}", key);return cache.getIfPresent(key);}@Overridepublic void put(Object key, Object value) {log.info("caffeine put=>{}:{}", key, value);cache.put(key, value);}@Overridepublic void evict(Object key) {log.info("caffeine evict => {}", key);cache.invalidate(key);}
}
CacheFrontendContext
package cn.edu.gxust.redis.context;import com.github.benmanes.caffeine.cache.Cache;
import io.lettuce.core.RedisClient;
import io.lettuce.core.TrackingArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.support.caching.CacheFrontend;
import io.lettuce.core.support.caching.ClientSideCaching;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;import java.util.List;/*** @author zhaoyijie* @since 2024/1/21 09:57*/
@Slf4j
public class CacheFrontendContext {@Getterprivate CacheFrontend cacheFrontend;private final RedisClient redisClient;private final Cache cache;private StatefulRedisConnection<String, String> connection;public CacheFrontendContext(RedisClient redisClient, Cache cache) {this.redisClient = redisClient;this.cache = cache;}public void check() {if (connection != null) {if (connection.isOpen()) {return;}}try {connection = redisClient.connect();this.cacheFrontend = ClientSideCaching.enable(new CaffeineCacheAccessor(cache), connection, TrackingArgs.Builder.enabled());connection.addListener(message -> {List<Object> content = message.getContent(StringCodec.UTF8::decodeKey);log.info("type:{},content:{}", message.getType(), content);if (message.getType().equals("invalidate")) {List<String> keys = (List<String>) content.get(1);for (String key : keys) {cache.invalidate(key);}}});log.warn("The redis client side connection had been reconnected.");} catch (Exception e) {log.error("The redis client side connection 'had been disconnected,waiting reconnect...");}}}
RedisClientCacheConfiguration
package cn.edu.gxust.redis.config;import cn.edu.gxust.redis.context.CacheFrontendContext;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;import java.util.concurrent.TimeUnit;/*** @author zhaoyijie* @since 2024/1/21 09:47*/
@Slf4j
@Configuration
public class RedisClientCacheConfiguration {@Beanpublic CommandLineRunner init(@Autowired CacheFrontendContext cacheFrontendContext) {return args -> {while (true) {cacheFrontendContext.check();Thread.sleep(1000);}};}@Beanpublic Cache<String, Object> localCache() {return Caffeine.newBuilder()//设置最后一次写入或访间后经过固定时间过期.expireAfterWrite(5, TimeUnit.MINUTES)//初始的缓存空间大小.initialCapacity(100)//缓存的最大条数.maximumSize(1000).build();}@Beanpublic RedisClient redisClient(LettuceConnectionFactory lettuceConnectionFactory) {return (RedisClient) lettuceConnectionFactory.getNativeClient();}@Beanpublic CacheFrontendContext cacheFrontendContext(@Autowired RedisClient redisClient, @Autowired Cache cache) {return new CacheFrontendContext(redisClient, cache);}
}
RedisTestController
package cn.edu.gxust.redis.controller;import cn.edu.gxust.redis.context.CacheFrontendContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;/*** @author zhaoyijie* @since 2023/11/24 14:54*/
@Api(tags = "redis相关")
@Slf4j
@RestController
@RequestMapping(value = "/redis/test/api")
public class RedisTestController {@Autowiredprivate CacheFrontendContext cacheFrontendContext;@ApiOperation(value = "测试2")@GetMapping(value = "/test")public String test2(@RequestParam(value = "key") String key, @RequestParam(value = "value") String value) {redisTemplate.opsForValue().set(key, value);Object o = cacheFrontendContext.getCacheFrontend().get(key);return o == null ? null : o.toString();}@ApiOperation(value = "测试3")@GetMapping(value = "/test3")public String test3(@RequestParam(value = "key") String key) {Object o = cacheFrontendContext.getCacheFrontend().get(key);return o == null ? null : o.toString();}
}
验证

首先先往里面写数据:

然后利用redis管理工具修改数据:

查看控制台打印信息:

我们可以发现Redis客户端数据发生变更的时候,本地缓存这边接受到了数据变更的消息,然后将变更数据的key置为了失效。
我们获取下数据:

这次我们拿到的数据为最新的数据
查看下控制台打印:

可以得知key失效后,我们再次获取数据的时候,本地缓存从Redis远程缓存中获取到数据先返回数据再put进本地缓存里

最后我们可以得到结果,当远程缓存的数据发生变更的时候,本地缓存就会收到变更通知,并更新本地缓存的数据。

但是注意:
上面说的应用必须在Redis单机模式下(或者主从、Sentinel模式),遗憾的是,目前发现Lettuce(6.1.5版本)还没有支持Redis Cluster下的客户端缓存。

开启客户端缓存后,Redis连接不能断开。如果Redis连接断了,并且客户端自动重连,那么新的连接是没有开启Tracking机制的,该连接查询的键不会受到失效消息,后果很严重。
同样,开启Tracking的连接和查询缓存键的连接必须是同一个,不能使用A连接开启Tracking机制,使用B连接去查询缓存键(所以客户端不能使用连接池)

这篇关于基于Redis6.0 tracking客户端缓存实现本地缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

缓存雪崩问题

缓存雪崩是缓存中大量key失效后当高并发到来时导致大量请求到数据库,瞬间耗尽数据库资源,导致数据库无法使用。 解决方案: 1、使用锁进行控制 2、对同一类型信息的key设置不同的过期时间 3、缓存预热 1. 什么是缓存雪崩 缓存雪崩是指在短时间内,大量缓存数据同时失效,导致所有请求直接涌向数据库,瞬间增加数据库的负载压力,可能导致数据库性能下降甚至崩溃。这种情况往往发生在缓存中大量 k

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现