Spingboot集成Redis之踩坑(二)序列化问题

本文介绍了一种在Spring Boot应用中遇到的Redis序列化错误,并提供了详细的解决方案。通过调整RedisTemplate的序列化方式,可以避免类型转换异常,确保数据正确存取。

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

报错如下:

java.lang.ClassCastException: com.test.demo.test.Role cannot be cast to java.lang.String

	at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:36)
	at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:126)
	at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:235)
	at com.test.demo.test.TestRedis.redis(TestRedis.java:25)
	at com.test.demo.test.Test.get(Test.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

配置类如下(使用注解的方式实现配置类): 

/**
 * Created on 2019/3/31.
 * Title: Simple
 * Description:配置類
 * Copyright: Copyright(c) 2019
 * Company:
 *
 * @author wy
 */
@Configuration
@Slf4j
public class RedisConfig {
    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.password}")
    private String password;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.pool.max-total}")
    private int maxTotal;

    @PostConstruct
    public void init()
    {
        log.info("ids redis host {}, port {}", this.host, this.port);
    }

    @Primary
    @Bean(name="redisConnectionFactory")
    public JedisConnectionFactory idsRedisConnectionFactory() {

        if (StringUtil.isBlank(this.host)) {
            log.info("No need to initialize ids redis.");
            return null;
        }

        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(this.host);
        factory.setPort(this.port);
        factory.setDatabase(this.index);
        factory.setTimeout(this.timeout);
        factory.setUsePool(false);
        if (StringUtil.isNotBlank(this.password)) {
            factory.setPassword(this.password);
            log.info("idsRedisConnectionFactory setPassword {}", this.password);
        }
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
       jedisPoolConfig.setMaxTotal(this.maxTotal);
        factory.setPoolConfig(jedisPoolConfig);

        return factory;

    }

    @Primary
    @Bean(name="idsRedisTemplate")
    public RedisTemplate<String, String> idsRedisTemplate(@Qualifier("redisConnectionFactory")
                                                                  RedisConnectionFactory cacheRedisConnectionFactory) {

        if (null == cacheRedisConnectionFactory) {
            return null;
        }

        StringRedisTemplate template = new StringRedisTemplate(cacheRedisConnectionFactory);
        template.afterPropertiesSet();
        log.warn("set ids redis {}:{}", this.host, this.port);

        return template;

    }
}

 

配置文件:

#redis
redis:
  ids:
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 2000
    pool:
      max-active: 8
      max-idle: 8
      max-wait: -1
      min-idle: 0
      max-total: 10

测试代码:

/**
 * Created on 2019/3/31.
 * Title: Simple
 * Description:測試類
 * Copyright: Copyright(c) 2018
 * Company: 
 *
 * @author wy
 */
@Service
public class TestRedis {
    @Autowired
    private RedisTemplate redisTemplate;

    public void redis() {
        Role role = new Role();
        role.setId(10);
        role.setRoleName("CEO");
        redisTemplate.opsForValue().set("1", role);
        redisTemplate.opsForValue().set("role-1", role);
        Role role1 = (Role) redisTemplate.opsForValue().get("role-1");
        System.out.println(role1.getId() + "======" + role1.getRoleName());
    }

}

解决方案:

出现这个的问题,主要是序列化失败,不指定序列化方式,默认应该是使用的JDK的二进制序列化方式,导致的强制转换失败,所以解决方案,是在配置类中进行指定序列化方式来进行序列化;

如下(指定序列化方式):

        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

亲测,可以解决,如有遇到以上问题,可以定位下是否是因为Redis的序列化方式问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值