SpringBoot集成Redis实现缓存
1.在pom.xml
中添加jar依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在application.yml
中进行Redis相关配置
spring:
redis:
host: 127.0.0.1
port: 6379
password:
jedis:
pool:
max-active: 25
max-idle: 20
min-idle: 10
3.在实体类
中修改MyBatisPlus框架的相关配置@TableId(value = "id", type = IdType.AUTO)
,以实现主键的自动回填
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "t_notice")
public class Notice implements Serializable {
/**
* 公告ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公告标题
*/
@TableField(value = "title")
private String title;
/**
* 公告内容
*/
@TableField(value = "content")
private String content;
/**
* 创建人
*/
@TableField(value = "created_user")
private String createdUser;
/**
* 创建时间
*/
@TableField(value = "created_time")
private Date createdTime;
/**
* 修改人
*/
@TableField(value = "modified_user")
private String modifiedUser;
/**
* 修改时间
*/
@TableField(value = "modified_time")
private Date modifiedTime;
private static final long serialVersionUID = 1L;
}
4.在启动类中添加注解@EnableCaching
@SpringBootApplication
@MapperScan("cn.xie.store.mapper")
@EnableCaching //开启缓存注解
public class StoreApplication {
public static void main(String[] args) {
SpringApplication.run(StoreApplication.class, args);
}
}
5.在config
包下新建RedisConfig
配置类
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
// 自定义key生成策略,按类名+方法名+参数名命名
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder key = new StringBuilder();
key.append(target.getClass().getName());
key.append(method.getName());
for (Object param : params) {
key.append(param.toString());
}
return key.toString();
}
};
}
// 缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 因为每步会生成新的对象,所以必须链式调用
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
// 设置序列化方式,否则客户端会呈现为二进制字符,value使用JSON序列化,key用String序列化
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
// RedisCacheManager构造器需要两个参数:
// RedisCacheWriter, 负责操作redis,不依赖redisTemplate
// RedisCacheConfiguration, 设置redis缓存配置
// 创建无锁的RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory);
return RedisCacheManager.builder(redisCacheWriter).cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
6.在service
层重写的CRUD
方法上添加相关注解
@Service
@CacheConfig(cacheNames = "notice")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
@Resource
private NoticeMapper noticeMapper;
@CachePut(key = "#result.id")
public Notice saveNotice(Notice entity) {
//mp插入之后会自动回填
super.save(entity);
return entity;
}
@Override
@CacheEvict(key = "#id")
public boolean removeById(Serializable id) {
return super.removeById(id);
}
@Override
@CachePut(key = "#result.id")
public Notice updateNoticeById(Notice entity) {
super.updateById(entity);
return noticeMapper.selectById(entity.getId());
}
@Override
@Cacheable(key = "#id")
public Notice getById(Serializable id) {
return super.getById(id);
}
}
注意:Redis缓存的是返回值
- cacheNames:缓存前缀
- key:缓存的Key
- CachePut:jedis.set方法
- #result:当前方法执行完成之后的返回值对象
附:Redis相关注解的简易说明
@Cacheable
@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
- value、cacheNames:两个等同的参数(cacheNames为Spring 4新增,作为value的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig,因此在Spring 3中原本必须有的value属性,也成为非必需项了
- key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key = “#p0”):使用函数第一个参数作为缓存的key值,更多关于SpEL表达式的详细内容可参考官方文档
- condition:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key = “#p0”, condition = “#p0.length() < 3”),表示只有当第一个参数的长度小于3的时候才会被缓存,若做此配置上面的AAA用户就不会被缓存,读者可自行实验尝试。
- unless:另外一个缓存条件参数,非必需,需使用SpEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断。
- keyGenerator:用于指定key生成器,非必需。若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.interceptor.KeyGenerator接口,并使用该参数来指定。需要注意的是:该参数与key是互斥的
- cacheManager:用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用
- cacheResolver:用于指定使用那个缓存解析器,非必需。需通过org.springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器,并用该参数指定。
@CachePut
@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
参数 | 解释 |
---|---|
value | 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 |
key | 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 |
condition | 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 |
@CacheEvict
参数 | 解释 |
---|---|
value | 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 |
key | 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 |
condition | 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存 |
allEntries | 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 |
beforeInvocation | 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 |
@CacheConfig
所有的@Cacheable()里面都有一个value=“xxx”的属性,这显然如果方法多了,写起来也是挺累的,如果可以一次性声明完 那就省事了, 所以,有了@CacheConfig这个配置,@CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法写别的名字,那么依然以方法的名字为准。
@CacheConfig是一个类级别的注解。