Spring 3.1 引入了激动人心的基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(例如 EHCache 或者 Redis),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。
Spring Cache 具备相当的好的灵活性,不仅能够使用 SpEL(Spring Expression Language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存临时存储方案,也支持和主流的专业缓存例如 EHCache、Redis、Guava 的集成。
- 基于 annotation 即可使得现有代码支持缓存
- 开箱即用 Out-Of-The-Box,不用安装和部署额外第三方组件即可使用缓存
- 支持 Spring Express Language,能使用对象的任何属性或者方法来定义缓存的 key 和 condition
- 支持 AspectJ,并通过其实现任何方法的缓存支持
- 支持自定义 key 和自定义缓存管理者,具有相当的灵活性和扩展性
Redis缓存的设计思路:
- 在执行查询时,先查询redis缓存,如果有数据则不在调用dao直接返回;如果查不到,才调用dao,并将数据保存到缓存
- 在执行增删改后,需要清空缓存,避免脏数据
1. pom.xml引入jar包
如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置文件
spring.cache.type
使用了Spring Cache后,能指定spring.cache.type就手动指定一下,虽然它会自动去适配已有Cache的依赖,但先后顺序会对Redis使用有影响(JCache -> EhCache -> Redis -> Guava)
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
redis:
database: 0
host: localhost
port: 6379
cache:
type: redis
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
global-config:
db-config:
id-type: auto
field-strategy: NOT_EMPTY
db-type: MYSQL
configuration:
map-underscore-to-camel-case: true
call-setters-on-nulls: true
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
level:
com.wd.dao: debug
3. 创建配置类 RedisConfig, 增加注解@EnableCaching,开启缓存功能
此处使用默认的CacheManager, 没有自行进行自定义配置, 如有需要可以谷歌
package com.wd.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author wangdi
* @date 21-7-6
*/
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
4. 注解介绍
@CacheConfig
有时候一个类中可能会有多个缓存操作,而这些缓存操作可能是重复的。这个时候可以使用@CacheConfig
@Mapper
@CacheConfig(cacheNames = "users")
public interface UserMapper {
@Select("select * from user where id =#{id}")
@Cacheable(key ="#p0")
User findById(@Param("id") String id);
@CachePut(key = "#p0")
@Update("update user set name=#{name} where id=#{id}")
void updataById(@Param("id")String id,@Param("name")String name);
//如果指定为 true,则方法调用后将立即清空所有缓存
@CacheEvict(key ="#p0",allEntries=true)
@Delete("delete from user where id=#{id}")
void deleteById(@Param("id")String id);
}
@CacheConfig是一个类级别的注解,允许共享缓存的名称、KeyGenerator、CacheManager 和CacheResolver。
该操作会被覆盖。即用了该注解, 下面的@Cacheable等注解可以不用指定value值
@Cacheable
根据方法的请求参数对其结果进行缓存
当重复使用相同参数调用方法的时候,方法本身不会被调用执行,即方法本身被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。
- key: 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合(如:@Cacheable(value=“user”,key="#userName"))
- value: 缓存的名称,必须指定至少一个(如:@Cacheable(value=“user”) 或者 @Cacheable(value={“user1”,“use2”}) )
- condition: 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存(如:@Cacheable(value = “user”, key = “#id”,condition = “#id < 10”))
@CachePut
这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中。指定key,将更新的结果同步到redis中
谨慎使用, 例: 当更新数据时, 只是对当前key进行了redis数据更新, 查询集合的那个key依然不受影响, 产生了脏数据
- key: 同上
- value: 同上
- condition: 同上
@CachEvict
根据条件对缓存进行清空
- key: 同上
- value: 同上
- condition: 同上
- allEntries: 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存(如: @CacheEvict(value = “user”, key = “#id”, allEntries = true) )
- beforeInvocation: 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存(如: @CacheEvict(value = “user”, key = “#id”, beforeInvocation = true) )
5. 在Spring缓存注解中的key属性中使用SpEL表达式
5. 案例使用
提前准备好一个简单的增删改查案例
/**
* (User)表数据库访问层
*
* @author wd
* @since 2021-07-06 09:48:24
*/
@Repository
@Mapper
@CacheConfig(cacheNames = "user")
public interface UserDao extends BaseMapper<User> {
/**
* 在执行增删改后,需要清空缓存,避免脏数据
*/
@Cacheable(key = "#a0")
@Override
User selectById(Serializable id);
@Cacheable(key = "#root.methodName")
@Override
List<User> selectList(Wrapper<User> queryWrapper);
// @CachePut(key = "#a0.id") [不推荐]
@CacheEvict(allEntries = true)
@Override
int insert(User entity);
// @CacheEvict(key = "#a0") [不推荐]
@CacheEvict(allEntries = true)
@Override
int deleteById(Serializable id);
// @CachePut(key = "#a0.id") [不推荐]
@CacheEvict(allEntries = true)
@Override
int updateById(User entity);
}
编写测试类, 测试redis是否缓存了数据等
该缓存也会将查询到为null的值存储到redis中, 解决了缓存穿透的问题