SpringCache使用

Spring Cache使用方法与Spring对事务管理的配置相似。Spring Cache的核心就是对某 个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的 方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指 定的结果进行返回

相比于redis,springcache没有设置缓存过期时间的功能

使用步骤:

1、在springboot启动类上加注解:@EnableCaching

2、使用@Cacheable注解,使被注解的查询方法加入缓存:

@Cacheable(value = "gathering",key = "#id")
    public Gathering findById(String id) {
        return gatheringDao.findById(id).get();
    }

其中value是大key,key是小key,相当于redis的hash类型。#是关键字,表示从方法形参(id)中取值

3、使用@CacheEvict注解,令缓存失效:

@CacheEvict(value = "gathering",key = "#id")
    public void deleteById(String id) {
        gatheringDao.deleteById(id);
    }
@CacheEvict(value = "gathering",key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }
原文地址:https://www.cnblogs.com/naixin007/p/10525847.html