package com.zyong.framework.spring.redis.config;
import java.time.Duration;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import org.springframework.data.redis.core.RedisTemplate;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Slf4j
@EnableCaching
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {
@Value(value = "${spring.application.name}")
String systemName;
@Value(value = "${spring.profiles.active}")
String profile;
@Value(value = "${spring.redis.timeout:3000}")
private Integer expiration;
@Value(value = "${spring.redis.cluster.nodes}")
private String[] nodes;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Autowired
ObjectMapper objectMapper;
@Primary
@Bean(name = "redisCacheManger")
public CacheManager cacheManager() {
// 缓存配置对象
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
// 设置缓存的默认超时时间:30分钟
// 如果是空值,不缓存
// 设置key序列化器
// 设置value序列化器
redisCacheConfiguration =
redisCacheConfiguration.entryTtl(Duration.ofMinutes( 30L))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(valueRedisSerializer()));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration)
.build();
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keyRedisSerializer());
redisTemplate.setValueSerializer(valueRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* key序列化器
* @return
*/
private RedisSerializer keyRedisSerializer() {
RedisCacheKeySerializer keySerializer = new RedisCacheKeySerializer(Object.class , profile);
keySerializer.setObjectMapper(objectMapper);
return keySerializer;
}
/**
* value序列化器
* @return
*/
private RedisSerializer valueRedisSerializer() {
Jackson2JsonRedisSerializer valueSerializer = new Jackson2JsonRedisSerializer(Object.class );
// 注意,这里的ObjectMapper不能使用容器默认的
// 缓存的序列化需要忽略JsonIgnore
ObjectMapper om = new ObjectMapper();
om.setDateFormat( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
valueSerializer.setObjectMapper(om);
return valueSerializer;
}
@Bean( "redisKeyGenerator")
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder(systemName + "|" + profile);
sb.append( ":" + o.getClass().getName());
sb.append( "." + method.getName());
if (objects != null ) {
sb.append( "$$" + StringUtils.join(objects, "@@"));
}
log.debug( "key:" + sb.toString());
return sb.toString();
}
};
}
}
package com.zyong.framework.spring.redis.config;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
@Slf4j
public class RedisCacheKeySerializer implements RedisSerializer {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
protected String profile;
protected JavaType javaType;
protected ObjectMapper objectMapper = new ObjectMapper();
public RedisCacheKeySerializer(Class type, String profile) {
Assert.notNull(type, "JavaType can not be null.");
Assert.notNull(profile, "Profile can not be null.");
this .javaType = getJavaType(type);
this .profile = "profile:" + profile + "|";
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this .objectMapper = objectMapper;
}
@Override
public byte [] serialize(Object t) throws SerializationException {
if (t == null ) {
return new byte [0];
}
try {
StringBuilder sb = new StringBuilder(profile);
sb.append( this .objectMapper.writeValueAsString(t));
log.debug( "serialize key: " + sb.toString());
return sb.toString().getBytes(DEFAULT_CHARSET);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
}
}
@Override
@SuppressWarnings( "unchecked")
public T deserialize(byte [] bytes) throws SerializationException {
if (isEmpty(bytes)) {
return null ;
}
try {
String value = StringUtils.removeFirst(new String(bytes, DEFAULT_CHARSET), profile);
log.debug( "deserialize key: " + value);
return (T) this .objectMapper.readValue(value, javaType);
} catch (Exception ex) {
throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex);
}
}
static boolean isEmpty(byte [] data) {
return (data == null || data.length == 0);
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
package com.zyong.framework.spring.redis.base;
import com.zyong.framework.spring.redis.SpringRedisApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author ZHANGYONG415
* @date 2019/5/21
*/
@Slf4j
@RunWith(SpringRunner. class )
@SpringBootTest(classes = SpringRedisApplication.class , webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseSpringBootTest {
@Before
public void init() {
log.info( "开始测试...");
}
@After
public void after() {
log.info( "测试结束...");
}
}
<?xml version="1.0" encoding="UTF-8"?>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.1.RELEASE
com.zyong.framework.spring.redis
spring-redis
0.0.1-SNAPSHOT
spring-redis
spring-redis project for Spring Boot
1.8
3.6
27.0-jre
2.9.5
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis
io.lettuce
lettuce-core
redis.clients
jedis
org.apache.commons
commons-lang3
${commons-lang3.version}
com.google.guava
guava
${guava.version}
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.junit.jupiter
junit-jupiter-api
junit
junit
4.12
org.springframework.boot
spring-boot-maven-plugin