spring boot 項(xiàng)目現(xiàn)在默認(rèn)引用spring cache。 使用時(shí)只需要開(kāi)啟緩存即可使用。簡(jiǎn)單方便。這里將spring cache 整合redis,并且自定義的過(guò)程寫(xiě)出來(lái)。
說(shuō)明
spring-cache整合redis
自定義緩存key生成器
自定義規(guī)則,為每個(gè)緩存key設(shè)置過(guò)期時(shí)間
自定義resolver,根據(jù)請(qǐng)求頭來(lái)限定是否使用緩存
這里就不具體說(shuō)cache的基礎(chǔ)用法了。
一 整合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 相關(guān)配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置連接工廠
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer來(lái)序列化和反序列化redis的value值(默認(rèn)使用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);
// 指定序列化輸入的類(lèi)型,類(lèi)必須是非final修飾的,final修飾的類(lèi),比如String,Integer等會(huì)跑出異常
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來(lái)序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 設(shè)置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* 對(duì)hash類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 對(duì)redis字符串類(lèi)型數(shù)據(jù)操作
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 對(duì)鏈表類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 對(duì)無(wú)序集合類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 對(duì)有序集合類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
開(kāi)啟并配置緩存
這里我把最終的cache配置放出來(lái)了。具體的內(nèi)容放到后面說(shuō)。
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()
// 設(shè)置key為String
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
// 設(shè)置value 為自動(dòng)轉(zhuǎn)Json的Object
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
// 不緩存null
.disableCachingNullValues()
// 前綴。用來(lái)區(qū)分不同的項(xiàng)目
.prefixCacheNameWith(SpringUtil.getProperty("spring.application.name") + "-")
// 緩存數(shù)據(jù)保存1小時(shí) (默認(rèn))
.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說(shuō)明
spring cache 定義了很多cacheManager,這里通過(guò)你bean的形式聲明redis cache。 并且配置序列化相關(guān)數(shù)據(jù)。
本來(lái)這里return new RedisCacheManager(xxxx);。不過(guò)我做自定義緩存時(shí)間時(shí),重寫(xiě)了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()
// 設(shè)置key為String
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
// 設(shè)置value 為自動(dòng)轉(zhuǎn)Json的Object
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
// 不緩存null
.disableCachingNullValues()
// 前綴。用來(lái)區(qū)分不同的項(xiàng)目
.prefixCacheNameWith(SpringUtil.getProperty("spring.application.name") + "-")
// 緩存數(shù)據(jù)保存1小時(shí) (默認(rèn))
.entryTtl(Duration.ofHours(1));
return new SydRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory), defaultCacheConfiguration);
}
二 CachingConfigurerSupport說(shuō)明
這個(gè)類(lèi)應(yīng)該是spring 留給咱們的擴(kuò)展點(diǎn)??匆幌麓a,里面全是空的。就是讓咱們繼承重寫(xiě)的。 上面的CacheConfiguration就是繼承重寫(xiě)了這個(gè)類(lèi)來(lái)完成自定義的。
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;
}
}
三 為每個(gè)key自定義過(guò)期時(shí)間
用法示例
@Cacheable(cacheNames = "cache#500")
@PostMapping("/get")
public String get(@RequestBody CacheGetParams params) {
String count = atomicInteger.incrementAndGet() + "";
log.info("接收到請(qǐng)求 返回" + count);
return count;
}
在cacheName上以#分隔,后面就是過(guò)期時(shí)間,單位是秒。
前面說(shuō)了,重寫(xiě)redisCacheManager來(lái)做自定義過(guò)期時(shí)間??匆幌?code>SydRedisCacheManager的代碼,就是在創(chuàng)建cache時(shí),對(duì)cacheName進(jìn)行解析和修改。
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生成器
這個(gè)就比較簡(jiǎn)單了, 自己編寫(xiě)生成邏輯,然后在CacheConfiguration中配置一下就好。我是將類(lèi)名,方法名,參數(shù),返回值拼接到以前作為key的。其他參數(shù)和返回值是轉(zhuǎn)成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);
// 指定序列化輸入的類(lèi)型,類(lèi)必須是非final修飾的,final修飾的類(lèi),比如String,Integer等會(huì)跑出異常
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);
//類(lèi).方法(參數(shù))返回值類(lèi)型
key = StrUtil.format("{}.{}({}){}", className, methodName, paramsStr, methodReturnName);
log.info(StrUtil.format("generate cache key==> {}", key));
} catch (Exception e) {
log.error("生成 cache key 出現(xiàn)異常", e);
}
if (null == key) {
throw new RuntimeException("cache key 生成出現(xiàn)異常");
}
return key;
}
}
五 自定義緩存失效
我想到一種情況,由前端來(lái)決定是否使用緩存。實(shí)現(xiàn)這個(gè)要用到自定義CacheResolver。
首先是用法。當(dāng)前端請(qǐng)求接口時(shí),請(qǐng)求頭上帶有 no-cache:true的時(shí)候,就不加載緩存了,直接查真實(shí)數(shù)據(jù)。
但是這樣還不夠,還要將新查到的數(shù)據(jù)更新到緩存中、這樣才能保證緩存中的數(shù)據(jù)有效。
不走緩存
自定義Resolver,檢查請(qǐng)求頭,在不使用緩存的情況下,將Cache對(duì)象替換。先看代碼
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對(duì)象替換為了SydRedisCache。其實(shí)就是把cache的get方法重寫(xiě)了,讓它只能查到null,這樣就自動(dòng)走真實(shí)查詢了,然后根據(jù)spring cacahe 的邏輯,它會(huì)把新的數(shù)據(jù)寫(xiě)入到緩存。如果你不想讓它寫(xiě)了,可以返回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;
/**
* 重寫(xiě)一下get方法,返回null. 讓他不走緩存
* 在不使用緩存時(shí)
*
* @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;
}
}
總結(jié)
spring 真的細(xì),把各種擴(kuò)展點(diǎn)給安排的明明白白的。有興趣可以看下cache 包的源碼。
哦,對(duì)了,spring cache 是基于aop做的。入口是一個(gè)攔截器。CacheInterceptor,我記得spring 事務(wù)也是通過(guò)aop做的,會(huì)有事務(wù)失效的問(wèn)題,不知道spring cache 會(huì)不會(huì)有緩存失效的問(wèn)題。
然后上面這些代碼可以去我的git看,有項(xiàng)目示例
https://gitee.com/yanghx-gitee/syd-projects/tree/master/syd-spring-cache