緩存我是寫在service里了,
有兩個方法诅诱,
一個是通過商品ID查詢方法,一個是通過商品ID和其他商品信息的更新方法送朱。
有三個注解徙歼,
@Cacheable:將返回對象加入緩存
@CachePur:更新redis中的緩存對象
@CacheEvict:刪除redis中的緩存對象
代碼如下
@Override
@Cacheable(cacheNames = "product", key = "#productId")
public ProductInfo selectByProductId(Integer productId) {
return productInfoMapper.selectByProductId(productId);
}
@Override
@CachePut(cacheNames = "product", key = "#productId", condition = "#productId > 0")
//@CacheEvict(cacheNames = "product", key = "123")
public ProductInfo updateByProductId(Integer productId) {
productInfoMapper.updateByProductId(productId, KeyUtil.genUniqueKey());
return productInfoMapper.selectByProductId(productId);
}
記得在啟動類上加上@EnableCaching注解
@SpringBootApplication
@MapperScan(basePackages = "com.tianci.supereal.mapper")
@EnableCaching
public class SuperealApplication {
public static void main(String[] args) {
SpringApplication.run(SuperealApplication.class, args);
}
}
還有pom.xml文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>RELEASE</version>
</dependency>