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<Object, Object> redisTemplate() { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(keyRedisSerializer()); redisTemplate.setValueSerializer(valueRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * key序列化器 * @return */ private RedisSerializer<Object> keyRedisSerializer() { RedisCacheKeySerializer keySerializer = new RedisCacheKeySerializer(Object.class, profile); keySerializer.setObjectMapper(objectMapper); return keySerializer; } /** * value序列化器 * @return */ private RedisSerializer<Object> valueRedisSerializer() { Jackson2JsonRedisSerializer<Object> valueSerializer = new Jackson2JsonRedisSerializer<Object>(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<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); protected String profile; protected JavaType javaType; protected ObjectMapper objectMapper = new ObjectMapper(); public RedisCacheKeySerializer(Class<T> 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"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zyong.framework.spring.redis</groupId> <artifactId>spring-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-redis</name> <description>spring-redis project for Spring Boot</description> <properties> <java.version>1.8</java.version> <commons-lang3.version>3.6</commons-lang3.version> <guava.version>27.0-jre</guava.version> <jackson.version>2.9.5</jackson.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <!--<!–Jackson required包–>--> <!--<dependency>--> <!--<groupId>com.fasterxml.jackson.core</groupId>--> <!--<artifactId>jackson-core</artifactId>--> <!--<version>${jackson.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>com.fasterxml.jackson.core</groupId>--> <!--<artifactId>jackson-databind</artifactId>--> <!--<version>${jackson.version}</version>--> <!--<exclusions>--> <!--<exclusion>--> <!--<groupId>com.fasterxml.jackson.core</groupId>--> <!--<artifactId>jackson-annotations</artifactId>--> <!--</exclusion>--> <!--<exclusion>--> <!--<groupId>com.fasterxml.jackson.core</groupId>--> <!--<artifactId>jackson-core</artifactId>--> <!--</exclusion>--> <!--</exclusions>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>com.fasterxml.jackson.core</groupId>--> <!--<artifactId>jackson-annotations</artifactId>--> <!--<version>${jackson.version}</version>--> <!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>