Redis注解使用

原文链接:https://www.cnblogs.com/zhangdongfang/p/12346883.html

1.引入依赖

<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.启用类上加上注解

@EnableCaching

3.方法上加注解(查询方法)

@Cacheable(cacheNames ="product",key = "#productId",condition="true",unless = "#productId.length() < 10")
public ProductInfo findOne(String productId) {
return repository.findOne(productId);
}

注解:@Cacheable 表示方法的返回值将被缓存;若加载类上,则所有方法返回值将被缓存
cacheNames 缓存名称,
key 缓存的字典key 支持SpEL表达式
condition 条件表达式 支持SpEL表达式 true 则缓存,默认空缓存
unless 具有一票否决权。若值为true 则不缓存,false则缓存,支持SpEL表达式; 用的多,可以筛选出错误信息不用cache

4.方法上加注解(保存方法)

@CachePut(cacheNames ="product" , key = "#productInfo.productId")
@Override
public ProductInfo save(ProductInfo productInfo) {
return repository.save(productInfo);
}
注解:@CachePut 更新缓存

5.注意事项:

a.查询的缓存对象和编辑都必须返回同一个对象

b.并且对象都必须实现Serialiable接口

c.两个方法缓存key必须是同一个

posted @ 2022-11-21 22:26  每日一小步  阅读(64)  评论(0编辑  收藏  举报