【Spring-boot】使用spring cache缓存,集成redis

一、spring cache是spring缓存。

spring-boot默认使用ConcurrentMapCacheManager作为缓存管理器,当没有指定缓存配置时使用。

二、加入依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

三、配置

  1. 开启缓存
@Configuration
@EnableCaching
public class CacheConfig{}

2.自定义缓存时间

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    public KeyGenerator simpleKeyGenerator() {
        return (o, method, objects) -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getSimpleName());
            stringBuilder.append(".");
            stringBuilder.append(method.getName());
            stringBuilder.append("[");
            for (Object obj : objects) {
                stringBuilder.append(obj.toString());
            }
            stringBuilder.append("]");

            return stringBuilder.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                // 默认策略,未配置的 key 会使用这个
                this.getRedisCacheConfigurationWithTtl(30 * 60),
                // 指定 key 策略
                this.getRedisCacheConfigurationMap()
        );
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        //用于Cacheable的value值 指定超时时间
        redisCacheConfigurationMap.put("UserInfoList", this.getRedisCacheConfigurationWithTtl(3000));
        redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000));

        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }
}

四、使用 直接在所要缓存的方法上使用注释

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

五 注意

  • spring cache是基于AOP的,所以类内部直接的方法调用不起作用
  • CachEvict 清除缓存是在方法执行成功后执行的,也可以通过配置在方法执行之前清空。

参考:注释驱动的 Spring cache 缓存介绍

### spring-boot-starter-data-redisspring-boot-starter-cache 的区别及应用场景 #### 区别 `spring-boot-starter-data-Redis` 主要用于与 Redis 数据库交互,提供了一套完整的操作 Redis 的 API 支持[^1]。它不仅限于缓存场景,还可以作为消息队列、发布/订阅模式等多种用途的数据存储解决方案。 而 `spring-boot-starter-cache` 则专注于实现应用级别的缓存抽象层,旨在简化开发者在项目中加入缓存机制的过程[^2]。此模块并不直接关联任何特定类型的持久化技术;相反,它是通过 SPI (Service Provider Interface) 来支持多种不同的缓存提供商,比如 EhCache, Caffeine 或者 Redis 等。 因此,在引入 `spring-boot-starter-cache` 后还需要额外指定具体的缓存实现方式——如果选择了 Redis,则通常会配合使用 `spring-boot-starter-data-redis` 提供的支持来完成实际的操作逻辑[^4]。 #### 应用场景 对于希望利用 Redis 进行复杂数据结构管理和分布式环境下的高性能读写需求的应用来说,应该优先考虑采用 `spring-boot-starter-data-redis` 。这使得开发人员能够充分利用 Redis 所提供的诸如列表(lists),集合(sets), 排序集(sorted sets)等功能特性[^3]。 另一方面,当只需要简单地提升热点查询效率或是减少数据库负载压力时,可以选择仅使用 `spring-boot-starter-cache` 并搭配合适的本地或远程缓存方案即可满足业务要求。这种方式下,即使不涉及复杂的键值对操作也能有效改善系统的响应时间和吞吐量表现。 ```java // 使用 spring-boot-starter-data-redis 实现简单的字符串设置和获取 @Autowired private StringRedisTemplate stringRedisTemplate; public void setKeyValue(String key, String value){ stringRedisTemplate.opsForValue().set(key,value); } public String getValueByKey(String key){ return stringRedisTemplate.opsForValue().get(key); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值