springboot整合redis(三)---修改redis的KeyValue中文乱码

未修改前效果
在这里插入图片描述
一、创建实例:Student,并构造有参和无参方法

public class Student implements Serializable {
    private int id;
    private String name;
    private int score;

    public Student(int id,String name,int score) {
        this.id = id;
        this.name = name;
        this.score = score;
    }

    public Student(){

    }

二、pom文件中引入fastjson

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

三、创建RedisConfig,修改RedisTemplate中序列化配置

@Slf4j
@Configurable
public class RedisConfig {
    
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        //value序列化
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.afterPropertiesSet();
        log.info("redisTemplate: "+redisTemplate);
        return redisTemplate;
    }
}

四、在Application主类中配置RedisConfig(@Import)

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@ComponentScan("com.example.demo")
@Import(RedisConfig.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

五、测试效果
ValueOperations:spring提供操作redis的类。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class RedisConfigTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test1(){
        Student student = new Student(2,"张三",28);
        ValueOperations<String, Student> operations=redisTemplate.opsForValue();
        operations.set("student2",student);
        log.info("成功---"+operations.get("student2").toString());
    }
}

运行结果:在这里插入图片描述
六、利用RedisDesktopManager查看效果,成功。
在这里插入图片描述
也可以在liunx中查看,这里中文乱码是因为我没有修改liunx配置。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值