Spring Boot 2关于Redis的使用(1)

Spring Boot 2关于Redis的使用1

引入相关包

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.4.RELEASE'

配置redis

  • application.yml主要对应org.springframework.boot.autoconfigure.data.redis.RedisProperties
spring.redis.host=XXXX
spring.redis.port=6379
  • 入口类启用缓存
    @EnableCaching

使用缓存

  • @Cacheable注解

优先查询缓存数据,没有再执行方法

  1. value(cacheNames)
    缓存的方法名称,例如:cacheNames = “TEST_”
  2. key
    可以不制定,直接使用value值,支持SpEL 表达式,例如:key = “#id + ‘’”
  3. unless
    不缓存条件,当满足条件的时候不缓存数据,支持SpEL 表达式,例如:unless = “#result == null”
  4. condition
    缓存条件,与unless相反,当满足条件的时候缓存数据,支持SpEL 表达式,例如:unless = “#id != null”
  5. keyGenerator
    自定义缓存key生成器,与key属性互斥,如果不指定就使用默认key生成器。需要实现接口
    org.springframework.cache.interceptor.KeyGenerator
  6. cacheManager
    与cacheResolver互斥,自定义缓存管理器。实现接口org.springframework.cache.CacheManager
  7. cacheResolver
    需要实现org.springframework.cache.interceptor.CacheResolver

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html

  • @CachePut注解

每次都会执行方法,并将结果存入指定的缓存中

  • @CacheEvict注解
  1. allEntries
    表示是否需要清除缓存中的所有元素。默认为false
  2. beforeInvocation
    是否在方法内容执行之前清除缓存,默认false。从来控制先清缓存还是后清缓存。

用来清除缓存

@Cacheable(cacheNames = "TEST_", key = "#id + ''", unless = "#result == null")
@Override
public RspDTO getCacheableUserInfo(Long id) {
    logger.info("*****TestServiceImpl.getCacheableUserInfo参数id={}", id);
    return new RspDTO(id);
}

@CachePut(cacheNames = "TEST_", key = "#id + ''", unless = "#result == null")
@Override
public RspDTO getCachePutUserInfo(Long id) {
    logger.info("*****TestServiceImpl.getCachePutUserInfo参数id={}", id);
    return new RspDTO(id);
}

@CacheEvict(cacheNames = "TEST_", key = "#id + ''")
@Override
public boolean delete(Long id) {
    logger.info("*****TestServiceImpl.delete参数id={}", id);
    return true;
}
  • @CacheConfig注解

是一个类级别的注解,允许共享缓存的名称、KeyGenerator、CacheManager 和CacheResolver。 同时如果方法制定了自己的属性,可以 覆盖该注解中的属性。

  • @Caching注解

可以做一些复杂的操作,当@CacheEvict或者@CachePut单一注解无法实现的时候

@Caching(
          cacheable = {@Cacheable(key = "#id + ''", unless = "#result == null")},
          put = {@CachePut(key = "#id + ''", unless = "#result == null")},
          evict = {@CacheEvict(key = "#id + ''")}
)

源码位置
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch02

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值