Redis 序列化

springframework.data.redis.serializer.SerializationException: Could not read JSON: Illegal character ((CTRL-CHAR, code 0)): only regular white space (\r, \n, \t) is allowed between tokens

Redis 序列化

springboot版本2.5.3
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
 </parent>
redis版本
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis 序列化配置
package com.xin.example.config;

import org.springframework.cache.CacheManager;
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.*;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.Duration;

/**
 * @author mitnick
 * @version Created by xin on 2020/8/31 11:50 AM.
 */
@Configuration
public class RedisTemplateConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置值(value)的序列化采用FastJsonRedisSerializer。
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置键(key)的序列化采用StringRedisSerializer。
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /* 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置CacheManager的值序列化方式为json序列化
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(jsonSerializer);
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(pair);
        //设置默认超过期时间是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }
}

测试类
package com.xin.example;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.concurrent.TimeUnit;

@SpringBootTest
class XinJavaTestApplicationTests {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final ObjectMapper     OBJECT_MAPPER = new ObjectMapper();

    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("msg:order:mark:2324", "232323",TimeUnit.SECONDS.toSeconds(2));
        redisTemplate.opsForValue().get("msg:order:mark:2324");
    }
}

运行报错

可以正常的进行set操作,但是不能取出来,报错内容如下

springframework.data.redis.serializer.SerializationException: Could not read JSON: Illegal character ((CTRL-CHAR, code 0)): only regular white space (\r, \n, \t) is allowed between tokens

image-20210729140601308

分析
查看redis里面的存储

image-20210729140733420

value值是乱码。

各种百度、google查询结果,没找到,后来发现,redis的参数写错了,写过期时间写成了offset。

错误代码

image-20210729140847161

正确代码

image-20210729140929964

此问题 整整花费了5个多小时,找各种redis序列化的问题,一直以为是序列化配置的有问题。因此写代码一定要规范。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot提供了对Redis的自动配置,可以方便地进行序列化和反序列化操作。下面是关于Spring Boot Redis序列化的介绍和示例代码: 1. Redis介绍: Redis是一个开源的内存数据结构存储系统,可以用作数据库、缓存和消息中间件。它支持多种数据结构,如字符串、哈希、列表、集合和有序集合。 2. 添加pom.xml依赖: 在Spring Boot项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 3. 自动配置分析: Spring Boot会根据配置文件中的属性自动配置Redis连接工厂、Redis模板和Redis操作类等。 4. application.properties配置: 在application.properties文件中配置Redis相关属性,例如: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 5. 连接Redis测试: 可以使用RedisTemplate或者StringRedisTemplate来连接Redis并进行操作。以下是一个简单的示例代码: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 6. 使用Jedis客户端: 除了使用RedisTemplate,还可以使用Jedis客户端来连接Redis。以下是一个示例代码: ```java @Autowired private JedisConnectionFactory jedisConnectionFactory; public void set(String key, String value) { try (Jedis jedis = jedisConnectionFactory.getConnection().getNativeConnection()) { jedis.set(key, value); } } public String get(String key) { try (Jedis jedis = jedisConnectionFactory.getConnection().getNativeConnection()) { return jedis.get(key); } } ``` 7. 自定义默认的序列化器: Spring Boot默认使用JdkSerializationRedisSerializer作为序列化器,可以通过自定义配置来修改默认的序列化器。以下是一个示例代码: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 8. 序列化问题: 在使用Redis进行序列化时,需要注意对象的序列化和反序列化。可以使用Fastjson等第三方库来进行自定义的序列化和反序列化操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值