本文主要是介绍Redis LocalDateTime 序列化与反序列化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Redis LocalDateTime 序列化与反序列化
spring yml配置:
spring:profiles:active: devredis:host: 127.0.0.1database: 0port: 6379password: passwordjedis:pool:max-active: 8max-wait: -1max-idle: 8min-idle: 0timeout: 10000
JedisConfig配置:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisCacheManager;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;import java.time.Duration;@Slf4j
//@EnableCaching
@Configuration
public class JedisConfig extends CachingConfigurerSupport {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.timeout}")private int timeout;@Value("${spring.redis.jedis.pool.max-active}")private int maxActive;@Value("${spring.redis.jedis.pool.max-idle}")private int maxIdle;@Value("${spring.redis.jedis.pool.min-idle}")private int minIdle;@Value("${spring.redis.jedis.pool.max-wait}")private long maxWaitMillis;@Beanpublic JedisPool redisPoolFactory() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxIdle(maxIdle);jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);jedisPoolConfig.setMaxTotal(maxActive);jedisPoolConfig.setMinIdle(minIdle);JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);log.info("JedisPool注入成功!");log.info("redis地址:" + host + ":" + port);return jedisPool;}@Beanpublic CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {//缓存配置对象RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();//设置缓存的默认超时时间:30分钟redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L))//如果是空值,不缓存.disableCachingNullValues()//设置key序列化器.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))//设置value序列化器.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer())));return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();}private RedisSerializer<String> keySerializer() {return new StringRedisSerializer();}private RedisSerializer<Object> valueSerializer() {Jackson2JsonRedisSerializer<Object> j2jrs = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);// 解决jackson无法反序列化LocalDateTime的问题om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);om.registerModule(new JavaTimeModule());om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);j2jrs.setObjectMapper(om);return j2jrs;
// return new GenericJackson2JsonRedisSerializer();}@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(keySerializer());redisTemplate.setHashKeySerializer(keySerializer());redisTemplate.setValueSerializer(valueSerializer());redisTemplate.setHashValueSerializer(valueSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}
}
maven相关配置:
<dependency><groupId>com.github.jedis-lock</groupId><artifactId>jedis-lock</artifactId><version>1.0.0</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
需使用缓存功能,即启用 @EnableCaching 注释;
可在 service.impl 中使用缓存功能,将会直接缓存到配置的Redis服务器中:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.codia.admin.biz.entity.Project;
import org.codia.admin.biz.mapper.ProjectMapper;
import org.codia.admin.biz.service.IProjectService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.List;@Service
@CacheConfig(cacheNames = "project")
@Transactional
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {@Resourceprivate ProjectMapper projectMapper;@Cacheable@Overridepublic List<Project> listAll() {return projectMapper.listAll();}
}
Redis中效果如下:
备注:
这里手动定义了Jedis连接池,使用了jackson作为序列化工具。希望对小伙伴们有帮助。
这篇关于Redis LocalDateTime 序列化与反序列化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!