分布式缓存:SpringCache使用redis进行数据缓存(可直接使用)

SpringCache简介

Spring Cache 核心思想是 当我们调用一个缓存方法时,会把该方法参数和返回结果作为一个键值对存放在缓存中,等下次利用同样的参数来调用方法时,将不再执行该方法,而是直接从缓存中获取结果进行返回。

需要注意

  1. 内部类之间的调用,缓存注解将起不到任何的作用
  2. 方法必须声明为public,必须有返回值
  3. 注解只能放在方法体上,若是缓存的逻辑颗粒度更加的细小,则不能实现
  4. 缓存逻辑简单,不能做更加深入的逻辑判断

常用的注解及配置


@EnableCache:开启缓存功能;
@Cacheable(value = "accountCache", key = "#id"):定义缓存,用于触发缓存,标记在方法上,凡是调用这个方法后,方法的返回值就会存储在名为 accountCache 的缓存中,key 按照spel表达式
@CachePut:定义更新缓存,触发缓存更新;
@CacheEvict:定义清除缓存,触发缓存清除 allEntries = true方法调用后清空所有缓存;
@Caching:组合定义多种缓存功能;
@CacheConfig:定义公共设置,位于 类class 之上;@CacheConfig(value = "user")每个方法中都默认使用 cacheNames = “user”

spring:
  # spring cache整合
  cache:
    type: redis
    redis:
      #允许缓存空值,默认true(能防止缓存穿透,也叫暴力缓存。)
      cache-null-values: true
      # 过期时间(这里是30min)。缺省情况下,表项永远不会过期。单位毫秒
      time-to-live: 1800000
      # key前缀
      key-prefix: 'cache:'
      # 当写入Redis时是否使用key前缀,默认true
      use-key-prefix: true

项目集成

1.引入jar包

        <!-- spring cache缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- redis连接池 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

2.yml文件配置redis库

实际情况根据自己的业务配置

spring:
  # spring cache整合
  cache:
    type: redis
    redis:
      #允许缓存空值,默认true(能防止缓存穿透,也叫暴力缓存。)
      cache-null-values: true
      # 过期时间(这里是30min)。缺省情况下,表项永远不会过期。单位毫秒
      time-to-live: 1800000
      # key前缀
      key-prefix: 'cache:'
      # 当写入Redis时是否使用key前缀,默认true
      use-key-prefix: true

3.config配置

注意开启缓存注解功能 @EnableCaching,有一些redis序列化反序列化,如果只用缓存可以不用配置

@EnableCaching
@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RedisConfig {

    /**
     * 构造方法注入
     */
    private final CacheProperties cacheProperties;

    private final RedisConnectionFactory redisConnectionFactory;

    /**
     * redisTemplate 序列化为json
     * 不需要redisTemplate,这个可不写。与spring cache没任何影响
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // key 序列化
        template.setKeySerializer(new StringRedisSerializer());

        template.setValueSerializer(jackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }


    /**
     * 获取spring cache的redis配置
     *
     * @return spring cache的redis配置
     */
    @Bean
    public CacheProperties.Redis redisProperties() {
        return cacheProperties.getRedis();
    }

    /**
     * 配置RedisCacheConfiguration,序列化为json
     *
     * @return redis序列化为json
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                //序列化/反序列化 key,value
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()));

        //spring cache redis模式的配置,对应配置文件spring.cache.redis下
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }


    /**
     * 序列化
     */
    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        // value的序列化类型
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        // 解决jackson2无法反序列化LocalDateTime的问题
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());

        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}

4.使用

@Cacheable:先查询缓存是否存在,如果存在,则返回结果;如果不存在,则执行方法,并将结果保存在缓存中。主要用于查询操作

@CachePut:不检查缓存中是否存在,直接执行方法,并将结果保存在缓存中。主要用于数据新增和修改操作

@CacheEvict:从缓存中移除指定的key数据,如果allEntries属性为true,则清除全部;如果beforeInvocation属性为true,则在方法执行前删除。主要用于删除操作

注解demo详情,下面只是service层实现的代码,controller层正常写就可以,先会根据注解去缓存里面取,没有的话才会走查询逻辑。

    @Cacheable(value = "admin", key = "#id")//如果在缓存中找不到计算出的键值,则会调用目标方法,并将返回的值存储在关联的缓存中。
    public Admin getById(Long id) {
        Admin admin = Admin.builder()
                .id(id)
                .userName("随机用户" + new Random().nextInt(100))
                .lastLoginTime(LocalDateTime.now())
                .build();

        log.info("detail-->id={},admin={}", id, admin);
        return admin;
    }


    @CachePut(value = "admin", key = "#admin.id")//新增或修改一条记录
    public Admin update(Admin admin) {
        log.info("update-->id={},admin={}", admin.getId(), admin);
        return admin;
    }

    @CacheEvict(value = "admin", key = "#id") //清除一条缓存,key为要清空的数据
//    @CacheEvict(value = "admin", allEntries = true) //方法调用后清空所有缓存
//    @CacheEvict(value = "admin", beforeInvocation = true, allEntries = true) //方法调用前清空所有缓存
    public void deleteById(Long id) {
        log.info("deleteById-->id={}", id);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值