redis序列化问题springboot以及springboot的基本redis配置文件

可以看到value显示为二进制,这是由于redisTemplate默认使用jdk序列化导致的,这种方式生成的数据较大,性能较低,且只有Java应用能够反序列化。本文将用fastjson2作为序列化方式。

fastjson2作为序列化方式
pom文件中引入fastjson2:

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.45</version>
</dependency>


 增加RedisConfig配置类:

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
/**
 * redis配置
 *
 * @Author: gusy
 */
@Slf4j
@Configuration
public class RedisConfig {
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用Fastjson2序列化器
        GenericFastJsonRedisSerializer redisSerializer = new GenericFastJsonRedisSerializer();
        // 设置 value 的序列化规则和 key 的序列化规则
        template.setValueSerializer(redisSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        log.info("redis自定义配置启动成功!");
        return template;
    }
}

基本redis配置文件

spring:
  rabbitmq:
    host: 192.168.150.104 # 你的虚拟机IP
    port: 5672 # 端口
    virtual-host: /hmall # 虚拟主机
    username: zxr # 用户名
    password: 123456 # 密码
  redis:
    host: 192.168.150.104 # 你的虚拟机IP
    password:
    port: 6379  # 端口号
    timeout: 1800000  # 连接超时时间(毫秒)
    lettuce:
      pool:
        max-active: 20  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1  # 最大阻塞等待时间(负数表示没有限制)
        max-idle: 5  # 连接池中最大空闲连接
        min-idle: 0  # 连接池中最小空闲连接

 

posted @ 2024-07-11 20:37  冷风5997  阅读(200)  评论(0)    收藏  举报