Spring Cache 入门教程

一:Spring缓存抽象

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、从缓存中读取之前缓存存储的数据

二:几个重要概念&缓存注解

名称解释
Cache缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等
CacheManager缓存管理器,管理各种缓存(cache)组件
@Cacheable主要针对方法配置,能够根据方法的请求参数对其进行缓存
@CacheEvict清空缓存
@CachePut保证方法被调用,又希望结果被缓存。 与@Cacheable区别在于是否每次都调用方法,常用于更新
@EnableCaching开启基于注解的缓存
keyGenerator缓存数据时key生成策略
serialize缓存数据时value序列化策略
@CacheConfig统一配置本类的缓存注解的属性

@Cacheable/@CachePut/@CacheEvict 主要的参数

名称解释
value缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写, 如果不指定,则缺省按照方法的所有参数进行组合 例如: @Cacheable(value=”testcache”,key=”#id”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false, 只有为 true 才进行缓存/清除缓存 例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
unless否定缓存。当条件结果为TRUE时,就不会缓存。 @Cacheable(value=”testcache”,unless=”#userName.length()>2”)
allEntries (@CacheEvict )是否清空所有缓存内容,缺省为 false,如果指定为 true, 则方法调用后将立即清空所有缓存 例如: @CachEvict(value=”testcache”,allEntries=true)
beforeInvocation (@CacheEvict)是否在方法执行前就清空,缺省为 false,如果指定为 true, 则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法 执行抛出异常,则不会清空缓存 例如: @CachEvict(value=”testcache”,beforeInvocation=true)

三:SpEL上下文数据

Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:

名称位置描述示例
methodNameroot对象当前被调用的方法名#root.methodname
methodroot对象当前被调用的方法#root.method.name
targetroot对象当前被调用的目标对象实例#root.target
targetClassroot对象当前被调用的目标对象的类#root.targetClass
argsroot对象当前被调用的方法的参数列表#root.args[0]
cachesroot对象当前方法调用使用的缓存列表#root.caches[0].name
Argument Name执行上下文当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数#artsian.id
result执行上下文方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false,conditon内无效)#result

注意:

1.当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。 如

@Cacheable(key = "targetClass + methodName +#p0")

2.使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。 如:

@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")

SpEL提供了多种运算符

类型运算符
关系<,>,<=,>=,==,!=,lt,gt,le,ge,eq,ne
算术+,- ,* ,/,%,^
逻辑&&,||,!,and,or,not,between,instanceof
条件?: (ternary),?: (elvis)
正则表达式matches
其他类型?.,?[…],![…],1,$[…]

以上的知识点适合你遗忘的时候来查阅,下面正式进入学习!

四:KeyGenerator

如果我们的缓存key比较复杂,则可以自定义KeyGenerator来灵活的生成缓存key

KeyGenerator 和key不能同时存在,存在的话会删除

  1. 自定义KeyGenerator
@Component
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        String key = JsonUtil.toJsonStr(params[0]);
        return key;
    }
}
  1. 使用
@Cacheable(keyGenerator = "myKeyGenerator",unless = "#result == null")
public Employee getByEmpId(Long id) {
    log.info("----------getByEmpId");
    return getById(id);
}

五:CacheManager

注解只是配置缓存的方式,真正进行缓存操作的类是CacheManager

我们可以利用其他框架提供的CacheManager,也可以自定义CacheManager。

  1. 创建CacheManager
//redisCacheManager
@Bean
@Primary
public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    //设置缓存过期时间
    RedisCacheConfiguration redisCacheCfg = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(STRING_SERIALIZER))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(JACKSON__SERIALIZER));
    return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
            .cacheDefaults(redisCacheCfg)
            .build();
}
  1. 使用
@CacheConfig(cacheNames = "emp",cacheManager = "redisCacheManager")@Cacheable(key = "#root.targetClass+''+#id",cacheManager = "redisCacheManager",unless = "#result == null")
  1. 我们也能通过CacheManager来手动的设置或删除缓存
@RestController
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    private EmployeeService employeeService;
    
    @GetMapping("/flushCche")
    public boolean flushCche(){
        //通过CacheManager获取cache(emp表示@@Cacheable或@CacheConfig 里面的 cacheNames)
        Cache emp = redisCacheManager.getCache("emp");
        System.out.println(emp);
        //删除cache
        emp.clear();
        return true;
    }
}

六、使用案例

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.gjw.mvc.bean.Employee;
import org.gjw.mvc.mapper.EmployeeMapper;
import org.gjw.mvc.service.EmployeeService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
//类内全局配置
@CacheConfig(cacheNames = "emp",cacheManager = "redisCacheManager")
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    @Transactional
    @Cacheable(key = "#root.targetClass+'getList'")
    public List<Employee> getList() {
        log.info("----------getList");
        baseMapper.selectList(null);
        return baseMapper.selectList(null);
    }

    @Override
    @Cacheable(key = "#root.targetClass+''+#id",unless = "#result == null")
    public Employee getByEmpId(Long id) {
        log.info("----------getByEmpId");
        return getById(id);
    }

    @Override
    @CacheEvict(allEntries = true)
    public boolean saveEmp(Employee employee) {
        log.info("----------saveEmp");
        return save(employee);
    }

    @Override
    @Caching(
            evict = {@CacheEvict(key = "#root.targetClass+'getList'"),@CacheEvict(key = "#root.targetClass+''+#id")}
    )
    public boolean deleteEmp(Long id) {
        log.info("----------deleteEmp");
        return removeById(id);
    }
}

  1. ↩︎

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值