使用 Spring Cache + Redis 作为缓存

it2026-02-02  2

准备工作

Redis windows 安装

如何配置

1. maven

完整依赖详见 ==> Gitee

<!-- 使用spring cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 为了解决 ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.0</version> </dependency>

2. application.properties

# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) #spring.redis.password=yourpwd # 连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间 spring.redis.lettuce.pool.max-wait=-1ms # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=5000ms #配置缓存相关 cache.default.expire-time=200 cache.user.expire-time=180 cache.user.name=test

3. @EnableCaching

标记注解 @EnableCaching,开启缓存,并配置Redis缓存管理器,需要初始化一个缓存空间。在缓存的时候,也需要标记使用哪一个缓存空间

@Configuration @EnableCaching public class RedisConfig { @Value("${cache.default.expire-time}") private int defaultExpireTime; @Value("${cache.user.expire-time}") private int userCacheExpireTime; @Value("${cache.user.name}") private String userCacheName; /** * 缓存管理器 * * @param lettuceConnectionFactory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存管理器管理的缓存的默认过期时间 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime)) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) // 不缓存空值 .disableCachingNullValues(); Set<String> cacheNames = new HashSet<>(); cacheNames.add(userCacheName); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime))); RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory) .cacheDefaults(defaultCacheConfig) .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } }

到此配置工作已经结束了


Spring Cache 使用

@Service @CacheConfig(cacheNames="user")// cacheName 是一定要指定的属性,可以通过 @CacheConfig 声明该类的通用配置 public class UserService { /** * 将结果缓存,当参数相同时,不会执行方法,从缓存中取 * * @param id * @return */ @Cacheable(key = "#id") public User findUserById(Integer id) { System.out.println("===> findUserById(id), id = " + id); return new User(id, "taven"); } /** * 将结果缓存,并且该方法不管缓存是否存在,每次都会执行 * * @param user * @return */ @CachePut(key = "#user.id") public User update(User user) { System.out.println("===> update(user), user = " + user); return user; } /** * 移除缓存,根据指定key * * @param user */ @CacheEvict(key = "#user.id") public void deleteById(User user) { System.out.println("===> deleteById(), user = " + user); } /** * 移除当前 cacheName下所有缓存 * */ @CacheEvict(allEntries = true) public void deleteAll() { System.out.println("===> deleteAll()"); } } 注解作用@Cacheable将方法的结果缓存起来,下一次方法执行参数相同时,将不执行方法,返回缓存中的结果@CacheEvict移除指定缓存@CachePut标记该注解的方法总会执行,根据注解的配置将结果缓存@Caching可以指定相同类型的多个缓存注解,例如根据不同的条件@CacheConfig类级别注解,可以设置一些共通的配置,@CacheConfig(cacheNames="user"), 代表该类下的方法均使用这个cacheNames

下面详细讲一下每个注解的作用和可选项。


Spring Cache 注解

1. @EnableCaching 做了什么

@EnableCaching 注释触发后置处理器, 检查每一个Spring bean 的 public 方法是否存在缓存注解。如果找到这样的一个注释, 自动创建一个代理拦截方法调用和处理相应的缓存行为。

2. 常用缓存注解简述

2.1 @Cacheable

将方法的结果缓存,必须要指定一个 cacheName(缓存空间)

@Cacheable("books") public Book findBook(ISBN isbn) {...}

默认 cache key

缓存的本质还是以 key-value 的形式存储的,默认情况下我们不指定key的时候 ,使用 SimpleKeyGenerator 作为key的生成策略

如果没有给出参数,则返回SimpleKey.EMPTY。如果只给出一个Param,则返回该实例。如果给出了更多的Param,则返回包含所有参数的SimpleKey。

注意:当使用默认策略时,我们的参数需要有 有效的hashCode()和equals()方法


自定义 cache key

@Cacheable(cacheNames="books", key="#isbn") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(cacheNames="books", key="#isbn.rawNumber") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(cacheNames="books", key="T(someType).hash(#isbn)") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

如上,配合Spring EL 使用,下文会详细介绍 Spring EL 对 Cache 的支持

指定对象指定对象中的属性某个类的某个静态方法

自定义 keyGenerator

@Cacheable(cacheNames="books", keyGenerator="myKeyGenerator") public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

实现 KeyGenerator接口可以自定义 cache key 的生成策略


自定义 cacheManager

@Cacheable(cacheNames="books", cacheManager="anotherCacheManager") public Book findBook(ISBN isbn) {...}

当我们的项目包含多个缓存管理器时,可以指定具体的缓存管理器,作为缓存解析


同步缓存

在多线程环境中,可能会出现相同的参数的请求并发调用方法的操作,默认情况下,spring cache 不会锁定任何东西,相同的值可能会被计算几次,这就违背了缓存的目的

对于这些特殊情况,可以使用sync属性。此时只有一个线程在处于计算,而其他线程则被阻塞,直到在缓存中更新条目为止。

@Cacheable(cacheNames="foos", sync=true) public Foo executeExpensiveOperation(String id) {...}

条件缓存

condition: 什么情况缓存,condition = true 时缓存,反之不缓存unless: 什么情况不缓存,unless = true 时不缓存,反之缓存 @Cacheable(cacheNames="book", condition="#name.length() < 32") public Book findBook(String name) @Cacheable(cacheNames="book", condition="#name.length() < 32", unless="#result?.hardback") public Optional<Book> findBook(String name)

Spring EL 对 Cache 的支持

NameLocationDescriptionExamplemethodNameRoot object被调用的方法的名称#root.methodNamemethodRoot object被调用的方法#root.method.nametargetRoot object当前调用方法的对象#root.targettargetClassRoot object当前调用方法的类#root.targetClassargsRoot object当前方法的参数#root.args[0]cachesRoot object当前方法的缓存集合#root.caches[0].nameArgument nameEvaluation context当前方法的参数名称#iban or #a0 (you can also use #p0 or #p<#arg> notation as an alias).resultEvaluation context方法返回的结果(要缓存的值)。只有在 unless 、@CachePut(用于计算键)或@CacheEvict(beforeInvocation=false)中才可用.对于支持的包装器(例如Optional),#result引用的是实际对象,而不是包装器#result

2.2 @CachePut

这个注解和 @Cacheable 有点类似,都会将结果缓存,但是标记 @CachePut 的方法每次都会执行,目的在于更新缓存,所以两个注解的使用场景完全不同。@Cacheable 支持的所有配置选项,同样适用于@CachePut

@CachePut(cacheNames="book", key="#isbn") public Book updateBook(ISBN isbn, BookDescriptor descriptor) 需要注意的是,不要在一个方法上同时使用@Cacheable 和 @CachePut

2.3 @CacheEvict

用于移除缓存

可以移除指定key声明 allEntries=true移除该CacheName下所有缓存声明beforeInvocation=true 在方法执行之前清除缓存,无论方法执行是否成功 @CacheEvict(cacheNames="book", key="#isbn") public Book updateBook(ISBN isbn, BookDescriptor descriptor) @CacheEvict(cacheNames="books", allEntries=true) public void loadBooks(InputStream batch)

2.4 @Caching

可以让你在一个方法上嵌套多个相同的Cache 注解(@Cacheable, @CachePut, @CacheEvict),分别指定不同的条件

@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") }) public Book importBooks(String deposit, Date date)

2.5 @CacheConfig

类级别注解,用于配置一些共同的选项(当方法注解声明的时候会被覆盖),例如 CacheName。

支持的选项如下:

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CacheConfig { String[] cacheNames() default {}; String keyGenerator() default ""; String cacheManager() default ""; String cacheResolver() default ""; }

参考:

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-annotations-cacheablehttps://spring.io/guides/gs/caching/

本文demo:

https://gitee.com/yintianwen7/taven-springboot-learning/tree/master/springboot-redis

最新回复(0)