wordpress導(dǎo)航欄特效插件廈門seo外包
更多SpringBoot3內(nèi)容請(qǐng)關(guān)注我的專欄:《SpringBoot3》
期待您的點(diǎn)贊👍收藏?評(píng)論?
重學(xué)SpringBoot3-集成Redis(三)之注解緩存策略設(shè)置
- 1. 引入 Redis 依賴
- 2. 配置 RedisCacheManager 及自定義過期策略
- 2.1 示例代碼:自定義過期策略
- 3. 配置說明
- 4. 使用自定義的緩存區(qū)域
- 5. 驗(yàn)證
- 6. 總結(jié)
書接上回,重學(xué)SpringBoot3-集成Redis(二), Spring Boot 提供了對(duì)緩存的簡便支持,使得開發(fā)者能夠通過簡單的注解實(shí)現(xiàn)緩存操作,減少重復(fù)代碼的編寫。本文將繼續(xù)介紹如何在 Spring Boot 3 中通過注解驅(qū)動(dòng)的方式針對(duì)不同緩存區(qū)域設(shè)置不同緩存策略。
在 Spring Boot 3 中,使用 RedisCacheManager
可以為不同的緩存區(qū)域(緩存名稱)設(shè)置自定義的過期策略。通過為每個(gè)緩存區(qū)域創(chuàng)建不同的 RedisCacheConfiguration
,你可以指定不同的過期時(shí)間(TTL)和其他緩存行為。以下是如何為不同的緩存區(qū)域設(shè)置自定義過期策略的詳細(xì)說明。
1. 引入 Redis 依賴
首先確保你的 pom.xml
或 build.gradle
文件中已經(jīng)引入了 Redis 相關(guān)的依賴。以 Maven 為例:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
2. 配置 RedisCacheManager 及自定義過期策略
通過創(chuàng)建自定義的 CacheManager
,你可以為不同的緩存名稱指定不同的 RedisCacheConfiguration
,每個(gè)配置可以有不同的過期時(shí)間或序列化規(guī)則。
2.1 示例代碼:自定義過期策略
package com.coderjia.boot310redis.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;
import java.util.HashMap;
import java.util.Map;/*** @author CoderJia* @create 2024/10/5 下午 12:36* @Description**/
@Configuration
public class CacheConfig {// @Bean// public RedisCacheConfiguration cacheConfiguration() {// return RedisCacheConfiguration.defaultCacheConfig()// .prefixCacheNameWith("coderjia:") // 設(shè)置緩存 Key 前綴// .entryTtl(Duration.ofMinutes(10)) // 設(shè)置緩存過期時(shí)間為 10 分鐘// .disableKeyPrefix()// .enableTimeToIdle()// .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 自定義 Key 序列化器// .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); // 自定義 Value 序列化器// }@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {// 創(chuàng)建默認(rèn)的 RedisCacheConfiguration,并設(shè)置全局緩存過期時(shí)間RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)) // 默認(rèn)全局緩存過期時(shí)間為5分鐘.disableCachingNullValues(); // 禁止緩存 null 值// 為特定緩存配置不同的過期策略Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();// 配置名為 "shortLivedCache" 的緩存,設(shè)置過期時(shí)間為1分鐘cacheConfigurations.put("shortLivedCache",RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)) // 設(shè)置緩存的TTL為1分鐘.disableCachingNullValues()); // 禁止緩存 null 值// 配置名為 "longLivedCache" 的緩存,設(shè)置過期時(shí)間為1小時(shí)cacheConfigurations.put("longLivedCache",RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)) // 設(shè)置緩存的TTL為1小時(shí).disableCachingNullValues()); // 禁止緩存 null 值// 配置名為 "jsonCache" 的緩存,使用 JSON 序列化器cacheConfigurations.put("jsonCache",RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)) // 30分鐘過期.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())).disableCachingNullValues()); // 禁止緩存 null 值// 創(chuàng)建 RedisCacheManager,加載自定義的緩存配置return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(defaultCacheConfig) // 設(shè)置默認(rèn)的緩存配置.withInitialCacheConfigurations(cacheConfigurations) // 加載不同緩存區(qū)域的配置.build();}
}
3. 配置說明
-
defaultCacheConfig
:這是默認(rèn)的緩存配置,用于所有未顯式定義的緩存區(qū)域。在上面的例子中,默認(rèn)的 TTL 是 5 分鐘。 -
cacheConfigurations.put("shortLivedCache", ...)
:為緩存名為"shortLivedCache"
的區(qū)域設(shè)置了特定的過期時(shí)間為 1 分鐘。這意味著,當(dāng)你使用@Cacheable
指定該緩存時(shí),它的 TTL 將為 1 分鐘。 -
cacheConfigurations.put("longLivedCache", ...)
:為緩存名為"longLivedCache"
的區(qū)域設(shè)置了 1 小時(shí)的 TTL。這非常適合需要長時(shí)間保留的數(shù)據(jù)。 -
cacheConfigurations.put("jsonCache", ...)
:這個(gè)緩存區(qū)域使用 JSON 序列化器。這樣可以確保鍵和值的序列化與反序列化是通過 JSON 格式完成的。
4. 使用自定義的緩存區(qū)域
在代碼中使用這些自定義的緩存區(qū)域時(shí),你可以通過 @Cacheable
注解指定不同的緩存名稱。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;@Service
public class UserService {// 當(dāng)方法第一次調(diào)用時(shí),結(jié)果將被緩存起來,之后相同參數(shù)的調(diào)用將直接從緩存中獲取數(shù)據(jù)@Cacheable(value = "user", key = "#p0")public User getUserById(Long id) {// 模擬數(shù)據(jù)庫查詢操作System.out.println("Fetching user with id: " + id);return new User(id, "User" + id);}// 使用短生命周期的緩存配置(1分鐘)@Cacheable(value = "shortLivedCache", key = "#p0")public User getShortLivedUserById(Long id) {return findUserInDatabase(id);}// 使用長生命周期的緩存配置(1小時(shí))@Cacheable(value = "longLivedCache", key = "#p0")public User getLongLivedUserById(Long id) {return findUserInDatabase(id);}// 使用 JSON 序列化的緩存(30分鐘)@Cacheable(value = "jsonCache", key = "#p0")public User getJsonSerializedUserById(Long id) {return findUserInDatabase(id);}private User findUserInDatabase(Long userId) {// 模擬數(shù)據(jù)庫查找return new User(userId, "John Doe");}
}
5. 驗(yàn)證
當(dāng)調(diào)用 getUserById
時(shí),緩存數(shù)據(jù)會(huì)存儲(chǔ)在默認(rèn)的緩存區(qū)域,數(shù)據(jù)會(huì)在 5 分鐘后過期。
調(diào)用 getShortLivedUserById
時(shí),數(shù)據(jù)會(huì)在 1 分鐘后自動(dòng)失效。
調(diào)用 getLongLivedUserById
時(shí),緩存數(shù)據(jù)會(huì)在 1 小時(shí)后失效。
getJsonSerializedUserById
方法將數(shù)據(jù)以 JSON 格式序列化,并在 30 分鐘后過期。
6. 總結(jié)
通過 RedisCacheManager
和 RedisCacheConfiguration
,你可以為不同的緩存區(qū)域設(shè)置不同的 TTL、序列化策略、以及緩存行為。這樣可以根據(jù)不同的業(yè)務(wù)場景調(diào)整緩存的生命周期,優(yōu)化應(yīng)用的性能。
為了更進(jìn)一步完整代碼,可以將緩存名稱和對(duì)應(yīng)有效期放入都配置文件中,更有利于線上環(huán)境根據(jù)實(shí)際情況調(diào)整緩存有效期,示例如下:
@Value("${cache.shortLiveCache.name}")
private String shortLiveCacheName;@Value("${cache.shortLiveCache.ttl}")
private long shortLiveCacheTtl;RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().cacheName(shortLiveCacheName).enableTimeToIdle(true).tti(Duration.ofSeconds(shortLiveCacheTtl));