基于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

相关文章

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

Python中bisect_left 函数实现高效插入与有序列表管理

《Python中bisect_left函数实现高效插入与有序列表管理》Python的bisect_left函数通过二分查找高效定位有序列表插入位置,与bisect_right的区别在于处理重复元素时... 目录一、bisect_left 基本介绍1.1 函数定义1.2 核心功能二、bisect_left 与

VSCode设置python SDK路径的实现步骤

《VSCode设置pythonSDK路径的实现步骤》本文主要介绍了VSCode设置pythonSDK路径的实现步骤,包括命令面板切换、settings.json配置、环境变量及虚拟环境处理,具有一定... 目录一、通过命令面板快速切换(推荐方法)二、通过 settings.json 配置(项目级/全局)三、

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

java中BigDecimal里面的subtract函数介绍及实现方法

《java中BigDecimal里面的subtract函数介绍及实现方法》在Java中实现减法操作需要根据数据类型选择不同方法,主要分为数值型减法和字符串减法两种场景,本文给大家介绍java中BigD... 目录Java中BigDecimal里面的subtract函数的意思?一、数值型减法(高精度计算)1.

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

C/C++中OpenCV 矩阵运算的实现

《C/C++中OpenCV矩阵运算的实现》本文主要介绍了C/C++中OpenCV矩阵运算的实现,包括基本算术运算(标量与矩阵)、矩阵乘法、转置、逆矩阵、行列式、迹、范数等操作,感兴趣的可以了解一下... 目录矩阵的创建与初始化创建矩阵访问矩阵元素基本的算术运算 ➕➖✖️➗矩阵与标量运算矩阵与矩阵运算 (逐元

C/C++的OpenCV 进行图像梯度提取的几种实现

《C/C++的OpenCV进行图像梯度提取的几种实现》本文主要介绍了C/C++的OpenCV进行图像梯度提取的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录预www.chinasem.cn备知识1. 图像加载与预处理2. Sobel 算子计算 X 和 Y

C/C++和OpenCV实现调用摄像头

《C/C++和OpenCV实现调用摄像头》本文主要介绍了C/C++和OpenCV实现调用摄像头,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录准备工作1. 打开摄像头2. 读取视频帧3. 显示视频帧4. 释放资源5. 获取和设置摄像头属性