缓存:整合SpringCache


首先还是引入依赖:

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-cacheartifactId>
        dependency>

以及之前已经引入了的redis:

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

进行配置,自动配置了很多东西,这里配置使用redis作为缓存。

spring.cache.type=redis

 

 开启缓存功能:

@EnableCaching
@EnableFeignClients(basePackages = "com.atguigu.gulimall.product.feign")
@EnableDiscoveryClient
@MapperScan("com.atguigu.gulimall.product.dao")
@SpringBootApplication
public class GulimallProductApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallProductApplication.class, args);
    }

}

就是最上面的 @EnableCaching注解就是开启缓存功能

然后用注解操作缓存就行了。

  /**
     * @Cacheable: 代表当前方法的结果需要缓存 并指定缓存名字 【缓存名字最好分区加以区分】
     * 如果缓存中有,不用调用方法,如果没有,调用方法,把方法中的结果放入缓存。

     *
     */
    @Cacheable(value = {"category"})
    @Override
    public List getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper().eq("cat_level", 1));
        // 测试能否缓存null值
//        return null;
    }
如果缓存中有,不用调用方法,如果没有,调用方法,把方法中的结果放入缓存。