1.简介
Spring 从 3.1 开始定义了 org.springframework.cache.Cache,和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术;并支持使用 JCache(JSR-107)注解简化我们开发;详情请参考官网添加链接描述
- Cache 接口为缓存的组件规范定义,包含缓存的各种操作集合;Cache 接 口 下 Spring 提 供 了 各 种 xxxCache 的 实 现 ; 如 RedisCache , EhCacheCache , ConcurrentMapCache 等;
- 每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。
- 使用 Spring 缓存抽象时我们需要关注以下两点;
- 1、确定方法需要被缓存以及他们的缓存策略
- 2、从缓存中读取之前缓存存储的数据
2.基础概念
3.整合Spring Cache
3.1.添加依赖
<!-- 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
3.2.配置信息
创建application.properties
spring.cache.type=redis
#spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000
#如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#spring.cache.redis.key-prefix=CACHE_
#spring.cache.redis.use-key-prefix=true
#是否缓存空值,防止缓存穿透
#spring.cache.redis.cache-null-values=true
#配置线程池
#gulimall.thread.coreSize=20
#gulimall.thread.maxSize=200
#gulimall.thread.keepAliveTime=10
#开启debug日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
3.3.启动类上加@EnableCaching
package com.atguigu.gulimall.product;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableCaching
@EnableFeignClients(basePackages = "com.atguigu.gulimall.product.feign")
@EnableDiscoveryClient
@SpringBootApplication
@MapperScan("com.atguigu.gulimall.product.dao")
public class GulimallProductApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallProductApplication.class, args);
}
}
3.4.使用缓存注解
CategoryServiceImpl的getTopCategorys方法上加@Cacheable
/**
* 查询所有1级分类
* @Cacheable代表当前方法的结果需要缓存,若缓存中有则方法不会调用,若缓存中没有会调用方法并将结果放入缓存
* @return
*/
@Cacheable({"category"})
@Override
public List<CategoryEntity> getTopCategorys() {
long startTime = System.currentTimeMillis();
List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(
new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
System.out.println("消耗时间:" + (System.currentTimeMillis() - startTime));
return categoryEntityList;
}
再次刷新首页方法不会被调用