likes
comments
collection
share

spring cache结合redis ,自定义过期时间,自定义key生成器,自定义是否生效

作者站长头像
站长
· 阅读数 11

spring boot 项目现在默认引用spring cache。 使用时只需要开启缓存即可使用。简单方便。这里将spring cache 整合redis,并且自定义的过程写出来。

说明

  1. spring-cache整合redis

  2. 自定义缓存key生成器

  3. 自定义规则,为每个缓存key设置过期时间

  4. 自定义resolver,根据请求头来限定是否使用缓存

这里就不具体说cache的基础用法了。

一 整合redis

添加redis依赖

implementation 'org.springframework.boot:spring-boot-starter-data-redis'

配置reids 序列化


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author yanghx
 */
@Configuration
public class RedisConfiguration {

    /**
     * redisTemplate 相关配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

开启并配置缓存

这里我把最终的cache配置放出来了。具体的内容放到后面说。


import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author yanghx
 */
@EnableCaching
@Configuration
@Slf4j
public class CacheConfiguration extends CachingConfigurerSupport {


    @Resource
    private KeyGenerator keyGenerator;
    @Resource
    private CacheErrorHandler cacheErrorHandler;


    @Bean
    public CacheResolver cacheResolver(CacheManager cacheManager) {
        return new SydCacheResolver(cacheManager);
    }


    /**
     * 配置cacheManage  使用 RedisTemplate 的配置信息
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> template) {
        if (null == template) {
            throw new RuntimeException("需要配置redis");
        }
        RedisConnectionFactory connectionFactory = template.getConnectionFactory();
        if (null == connectionFactory) {
            throw new RuntimeException("需要配置redis的 connectionFactory ");
        }
        // 基本配置
        RedisCacheConfiguration defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                // 设置key为String
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
                // 设置value 为自动转Json的Object
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
                // 不缓存null
                .disableCachingNullValues()
                // 前缀。用来区分不同的项目
                .prefixCacheNameWith(SpringUtil.getProperty("spring.application.name") + "-")
                // 缓存数据保存1小时 (默认)
                .entryTtl(Duration.ofHours(1));

        return new SydRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory), defaultCacheConfiguration);
    }


    /**
     * 自定义keyGenerator
     *
     * @return KeyGenerator
     */

    @Override
    public KeyGenerator keyGenerator() {
        return keyGenerator;
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return cacheErrorHandler;
    }


    @Override
    public CacheResolver cacheResolver() {
        return cacheResolver(cacheManager());
    }
}

整合reids说明

spring cache 定义了很多cacheManager,这里通过你bean的形式声明redis cache。 并且配置序列化相关数据。

本来这里return new RedisCacheManager(xxxx);。不过我做自定义缓存时间时,重写了redisCacheManager。所以返回了 SydRedisCacheManager


/**
 * 配置cacheManage  使用 RedisTemplate 的配置信息
 */
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> template) {
    if (null == template) {
        throw new RuntimeException("需要配置redis");
    }
    RedisConnectionFactory connectionFactory = template.getConnectionFactory();
    if (null == connectionFactory) {
        throw new RuntimeException("需要配置redis的 connectionFactory ");
    }
    // 基本配置
    RedisCacheConfiguration defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            // 设置key为String
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
            // 设置value 为自动转Json的Object
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
            // 不缓存null
            .disableCachingNullValues()
            // 前缀。用来区分不同的项目
            .prefixCacheNameWith(SpringUtil.getProperty("spring.application.name") + "-")
            // 缓存数据保存1小时 (默认)
            .entryTtl(Duration.ofHours(1));

    return new SydRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory), defaultCacheConfiguration);
}

CachingConfigurerSupport说明

这个类应该是spring 留给咱们的扩展点。看一下代码,里面全是空的。就是让咱们继承重写的。 上面的CacheConfiguration就是继承重写了这个类来完成自定义的。

public class CachingConfigurerSupport implements CachingConfigurer {

   @Override
   @Nullable
   public CacheManager cacheManager() {
      return null;
   }

   @Override
   @Nullable
   public CacheResolver cacheResolver() {
      return null;
   }

   @Override
   @Nullable
   public KeyGenerator keyGenerator() {
      return null;
   }

   @Override
   @Nullable
   public CacheErrorHandler errorHandler() {
      return null;
   }

}

三 为每个key自定义过期时间

用法示例

@Cacheable(cacheNames = "cache#500")
@PostMapping("/get")
public String get(@RequestBody CacheGetParams params) {
    String count = atomicInteger.incrementAndGet() + "";
    log.info("接收到请求 返回" + count);
    return count;


}

在cacheName上以#分隔,后面就是过期时间,单位是秒。

前面说了,重写redisCacheManager来做自定义过期时间。看一下SydRedisCacheManager的代码,就是在创建cache时,对cacheName进行解析和修改。


import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * @author yanghx
 */

public class SydRedisCacheManager extends RedisCacheManager {


    public SydRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }


    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] array = StringUtils.delimitedListToStringArray(name, "#");
        name = array[0];
        // 解析TTL
        if (array.length > 1) {
            long ttl = Long.parseLong(array[1]);
            // 注意单位我此处用的是秒,而非毫秒
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
        }
        return super.createRedisCache(name, cacheConfig);
    }
}

四 自定义key生成器

这个就比较简单了, 自己编写生成逻辑,然后在CacheConfiguration中配置一下就好。我是将类名,方法名,参数,返回值拼接到以前作为key的。其他参数和返回值是转成Base64的。


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author yanghx
 */
@Slf4j
@Component
public class SydKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        String key = null;
        try {
            String className = target.getClass().getName();
            String methodName = method.getName();
            String methodReturnName = method.getReturnType().getName();

            ObjectMapper om = new ObjectMapper();
            // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
            om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
            om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            String paramsStr = om.writeValueAsString(params);
            paramsStr = Base64Util.encode(paramsStr);
            methodReturnName = Base64Util.encode(methodReturnName);
            //类.方法(参数)返回值类型
            key = StrUtil.format("{}.{}({}){}", className, methodName, paramsStr, methodReturnName);
            log.info(StrUtil.format("generate cache key==> {}", key));
        } catch (Exception e) {
            log.error("生成 cache key 出现异常", e);
        }
        if (null == key) {
            throw new RuntimeException("cache key 生成出现异常");
        }
        return key;
    }
}

五 自定义缓存失效

我想到一种情况,由前端来决定是否使用缓存。实现这个要用到自定义CacheResolver。

首先是用法。当前端请求接口时,请求头上带有 no-cache:true的时候,就不加载缓存了,直接查真实数据。

但是这样还不够,还要将新查到的数据更新到缓存中、这样才能保证缓存中的数据有效。

不走缓存

自定义Resolver,检查请求头,在不使用缓存的情况下,将Cache对象替换。先看代码

package cn.yanghx.study.cache.config;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * 缓存处理器
 *
 * @author Administrator
 */
@Slf4j
@Component
@Qualifier("cacheResolver")
public class SydCacheResolver extends SimpleCacheResolver {

    @Resource
    private HttpServletRequest request;

    public SydCacheResolver(CacheManager cacheManager) {
        super(cacheManager);
    }

    @Override
    public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
        Collection<String> cacheNames = getCacheNames(context);
        if (cacheNames == null) {
            return Collections.emptyList();
        }
        Collection<Cache> result = new ArrayList<>(cacheNames.size());
        String cacheFlag = ServletUtil.getHeaderIgnoreCase(request, "no-cache");
        //是否不走缓存
        boolean isNoCache = Boolean.parseBoolean(cacheFlag);
        for (String cacheName : cacheNames) {
            Cache cache = getCacheManager().getCache(cacheName);
            if (cache == null) {
                throw new IllegalArgumentException("Cannot find cache named '" +
                        cacheName + "' for " + context.getOperation());
            }
            if (isNoCache && cache instanceof RedisCache) {
                cache = new SydRedisCache((RedisCache) cache);
            }
            result.add(cache);
        }
        return result;
    }
}

可以看到,在if (isNoCache && cache instanceof RedisCache)的条件下,我将cache对象替换为了SydRedisCache。其实就是把cache的get方法重写了,让它只能查到null,这样就自动走真实查询了,然后根据spring cacahe 的逻辑,它会把新的数据写入到缓存。如果你不想让它写了,可以返回NoOpCache。 看一下SydRedisCache代码。

package cn.yanghx.study.cache.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.Nullable;

/**
 * 重写一下get方法,返回null. 让他不走缓存
 * 在不使用缓存时
 *
 * @author Administrator
 */
@Slf4j
public class SydRedisCache extends RedisCache {
    /**
     * Create new {@link RedisCache}.
     *
     * @param name        must not be {@literal null}.
     * @param cacheWriter must not be {@literal null}.
     * @param cacheConfig must not be {@literal null}.
     */
    protected SydRedisCache(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
    }

    public SydRedisCache(RedisCache redisCache) {
        super(redisCache.getName(), redisCache.getNativeCache(), redisCache.getCacheConfiguration());
    }


    @Override
    @Nullable
    public ValueWrapper get(Object key) {
        log.info("syd cache return null ");
        return null;
    }

    @Override
    @Nullable
    public <T> T get(Object key, @Nullable Class<T> type) {
        log.info("syd cache return null ");
        return null;
    }

}

总结

spring 真的细,把各种扩展点给安排的明明白白的。有兴趣可以看下cache 包的源码。 哦,对了,spring cache 是基于aop做的。入口是一个拦截器。CacheInterceptor,我记得spring 事务也是通过aop做的,会有事务失效的问题,不知道spring cache 会不会有缓存失效的问题。

然后上面这些代码可以去我的git看,有项目示例 gitee.com/yanghx-gite…