SpringCache使用配置

项目中引入SpringCache

  1. pom文件引入依赖

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-cacheartifactId>
    dependency>
    
  2. 配置文件指定缓存类型

    spring:
      cache:
        type: redis
    
  3. 启动类开启缓存注解@EnableCaching

springEl表达式

  • methodName:当前被调用的方法名

    • #root.methodName
  • args:当前被调用的方法的参数列表

    • #root.args[0]
  • result:方法执行后的返回值

    • #result

注解使用

  • Cacheable注解

    • 标记在一个方法上,也可以标记在一个类上
    • 缓存标注对象的返回结果,标注在方法上缓存该方法的返回值,标注在类上缓存该类所有的方法返回值
    • value:缓存名称,可以有多个
    • key:缓存的key规则,可以用springEL表达式,默认是方法的参数组合
    • condition:缓存条件,使用springEL编写,返回true才缓存
    @Cacheable(value = "user:page",key = "#pageNum+'_'+#pageSize")
    public Map<String, Object> page(Integer pageNum, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
    
        Page<User> page = new Page<>(pageNum,pageSize);
        Page<User> listPage = this.userMapper.selectPage(page, null);
    
        map.put("totalRecord",listPage.getTotal());
        map.put("totalPage",listPage.getPages());
        map.put("list",listPage.getRecords());
        return map;
    }
    
  • CachePut注解:更新缓存

    @CachePut(value = "user", key = "#user.id")
    public User update(User user) {
        this.userMapper.updateById(user);
        return this.userMapper.selectById(user.getId());
    }
    
  • CacheEvict注解:删除缓存

    • beforeInvocation = true:缓存清除是否在方法之前执行,默认false
    @CacheEvict(value = "user", key = "#id", beforeInvocation = true)
    public boolean delete(Integer id) {
        int i = 1 / 0;
        return this.userMapper.deleteById(id) > 0;
    }
    
  • Caching

    • 组合多个Cache注解使用
    • 允许在同一方法上使用多个嵌套的@Cacheable、@CachePut、@CacheEvict注解
    @Caching(cacheable = {@Cacheable(value = "user1", key = "#user.id")},
             put = {@CachePut(value = "user2", key = "#user.id")})
    public User update(User user) {
        this.userMapper.updateById(user);
        return this.userMapper.selectById(user.getId());
    }
    

SpringCache框架自定义cacheManager配置过期时间

  • 配置类

    /**
     * 过期时间1h
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager1Hour(RedisConnectionFactory redisConnectionFactory) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        // 只缓存非空值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 将类型序列化到属性json字符串中
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
    
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(configuration)
                .transactionAware().build();
    }
    
  • Service类使用

    @Cacheable(value = "user:page",key = "#pageNum+'_'+#pageSize", cacheManager = "redisCacheManager1Hour")
    public Map<String, Object> page(Integer pageNum, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
    
        Page<User> page = new Page<>(pageNum,pageSize);
        Page<User> listPage = this.userMapper.selectPage(page, null);
    
        map.put("totalRecord",listPage.getTotal());
        map.put("totalPage",listPage.getPages());
        map.put("list",listPage.getRecords());
        return map;
    }
    

SpringCache框架自定义keyGenerator

  • key规则定义配置类

    /**
     * 自定义缓存key规则
     *
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return (obj, method, args) -> obj.getClass().getSimpleName() + "_" + method.getName() + "_" + StringUtils.arrayToDelimitedString(args, "_");
    }
    
  • Service类使用,key和keyGenerator只能二选一

    @Cacheable(value = "user:page", keyGenerator = "keyGenerator")
    public Map<String, Object> page(Integer pageNum, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
    
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> listPage = this.userMapper.selectPage(page, null);
    
        map.put("totalRecord", listPage.getTotal());
        map.put("totalPage", listPage.getPages());
        map.put("list", listPage.getRecords());
        return map;
    }
    

你可能感兴趣的:(Redis,spring,boot,spring,java)