Spring Boot 2关于Redis的使用(2)

本文介绍在SpringBoot2中如何自定义Redis序列化方式,解决包名变动等问题,通过实现RedisSerializer接口并使用Jackson2JsonRedisSerializer进行泛型反序列化。同时,解析了Redis配置文件的使用方法,包括在application.yml或properties文件中的配置,并展示了如何构造JedisPoolConfig和JedisPool以优化Redis连接池。最后,提供了构造缓存工具类的方法,以便于更高效地操作Redis。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里主要采用自定义方式来操作Redis

自定义序列化

  1. 默认采用JDK的序列化方式,可能不满足我们的要求,比如说包名变动等导致反序列化报错
  2. 实现接口org.springframework.data.redis.serializer.RedisSerializer
  3. 系统自带org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
  4. 自定义JSON序列化,主要包名的问题,泛型反序列化问题
<T> T deserialize(byte[] source, Class<T> type);
<T> T deserialize(byte[] source, JavaType javaType);
<T> T deserialize(byte[] source, ParameterizedType parameterizedType);
<T> T deserialize(byte[] source, TypeReference<T> typeReference);

解析配置文件

可以在application.yml中配置,也可以在properties文件中配置

@Component
@ConfigurationProperties(prefix = "redis-config")
public class RedisProperties implements Serializable {
    private static final long serialVersionUID = 1071156375336358075L;

    private String host = Protocol.DEFAULT_HOST;
    private int port = Protocol.DEFAULT_PORT;
    private int timeout = Protocol.DEFAULT_TIMEOUT;
    private Long expireTime = 604800L;
    private int maxIdle = 8;
    private int maxTotal = 8;
    private long maxWaitMillis = 1000L;
    private Boolean testOnBorrow = true;
}	

构造JedisPoolConfig等信息

@Bean
public JedisPoolConfig getJedisPoolConfig() {
     JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
     jedisPoolConfig.setMaxIdle(this.redisProperties.getMaxIdle());
     jedisPoolConfig.setMaxTotal(this.redisProperties.getMaxTotal());
     jedisPoolConfig.setMaxWaitMillis(this.redisProperties.getMaxWaitMillis());
     jedisPoolConfig.setTestOnBorrow(this.redisProperties.getTestOnBorrow());
     return jedisPoolConfig;
 }

 @Bean
 public Pool<Jedis> getJedisPool(JedisPoolConfig jedisPoolConfig) {
     return new JedisPool(jedisPoolConfig, this.redisProperties.getHost(), this.redisProperties.getPort(), this.redisProperties.getTimeout());
 }

构造缓存工具类

@Component
public class RedisCacheUtil {
    private Logger logger = LoggerFactory.getLogger(RedisCacheUtil.class);
    private RedisJackson2JsonRedisSerializer redisSerializer = new RedisJackson2JsonRedisSerializer();

    @Autowired
    private Pool<Jedis> jedisPool;

    @Autowired
    private RedisProperties redisProperties;
}

通过Jedis提供的方法可以操作Redis的所有功能

源码位置
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch02

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值