【异常】springboot集成@Cacheable缓存乱码的问题解决方案

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 【异常】springboot集成@Cacheable缓存乱码的问题解决方案

一、问题及现象

会把被标注的方法的返回值缓存到 Redis 中,相同的操作不会查数据库而是从缓存中获取数据。

Springboot 集成 Redis,使用 @Cacheable 注解之后,把数据缓存到 Redis 中,数据是保存在Redis 中了,但是,通过 Redis 的可视化管理工具查看缓存的数据时,却发现 redis 中的 key 正常,但是 value 是乱码。如下图所示的乱码:

修改过后,可以正常显示,如下图:

二、原因分析

其实出现上述乱码,一般情况都是没有配置 redis 序列化值导致的,而源码里的配置又没有默认,需要自己去实现。

在网上有很多种写法,我搜索了很多都不适合自己,只有下面这一种可以正常。

三、解决方案

添加一个 Redis 的配置类即可。如下代码是我在项目中的代码,加上重启项目 Redis 缓存中的 value 即可正常显示。

package com.iot.back.message.process.config;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
/**
 * <p>RedisConfig 此类用于:Redis相关配置,用于解决存入Redis中值乱码问题 </p>
 * <p>@author:hujm</p>
 * <p>@date:2022年08月18日 18:04</p>
 * <p>@remark:</p>
 */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 序列化值
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

使用 @Cacheable 注解的类

package com.iot.back.message.process.rpc;
import com.iot.back.message.process.convert.DeviceBasicInfoConvert;
import com.iot.back.message.process.dto.DeviceBasicInfoDTO;
import com.iot.basic.iotsmarthome.api.client.device.DeviceCloudClient;
import com.iot.basic.iotsmarthome.api.response.device.DeviceBasicInfoResponse;
import com.iot.framework.core.response.CommResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
 * <p>DeviceBasicInfoRpc 此类用于:设备基本信息远程调用 </p>
 * <p>@author:hujm</p>
 * <p>@date:2022年05月23日 15:07</p>
 * <p>@remark:</p>
 */
@Slf4j
@Component
public class DeviceBasicInfoRpc {
    @Resource
    private DeviceCloudClient deviceCloudClient;
    @Cacheable(cacheNames = "back-process-service:cache", key = "#sn+':'+#deviceId", sync = true)
    public DeviceBasicInfoDTO getDeviceBasicInfo(String sn, Integer deviceId) {
        CommResponse<DeviceBasicInfoResponse> deviceBasicInfoCommResponse = deviceCloudClient.getDeviceBasicInfo(sn, deviceId);
        if (deviceBasicInfoCommResponse == null || deviceBasicInfoCommResponse.isFail()) {
            log.error("P0|DeviceBasicInfoRpc|getDeviceBasicInfo|调用设备云服务时,根据sn和deviceId获取设备基础信息失败!");
            return null;
        }
        DeviceBasicInfoResponse deviceBasicInfoResponse = deviceBasicInfoCommResponse.getData();
        return DeviceBasicInfoConvert.INSTANCE.convert2DeviceBasicInfoDTO(deviceBasicInfoResponse);
    }
}

完结!


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
5天前
|
缓存 NoSQL Java
SpringBoot实现缓存预热的几种常用方案
SpringBoot实现缓存预热的几种常用方案
|
22天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
28天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
354 0
|
2月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
293 1
|
4天前
|
Java Spring
Spring Boot脚手架集成校验框架
Spring Boot脚手架集成校验框架
11 0
|
5天前
|
缓存 NoSQL Java
Springboot 大事务问题的常用优化方案
Springboot 大事务问题的常用优化方案
|
5天前
|
缓存 NoSQL Java
Springboot 多级缓存设计与实现
Springboot 多级缓存设计与实现
|
5天前
|
Java Docker 容器
SpringBoot项目集成XXL-job
SpringBoot项目集成XXL-job
|
7天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
12天前
|
前端开发 安全 Java
springboot集成springdoc-openapi(模拟前端请求)
springboot集成springdoc-openapi(模拟前端请求)