SpringBoot中缓存@Cacheable出错

SpringBoot中使用@Cacheable:

错误代码:

java 复制代码
@Cacheable(value = "FrontAdvertiseVOList", keyGenerator = "cacheKey")
@Override
public List<FrontAdvertiseVO> getFrontAdvertiseVOList(Integer count) {
    return this.list(Wrappers.<Advertise>lambdaQuery()
                    .select(Advertise::getPic, Advertise::getUrl)
                    .eq(Advertise::getState, 1)
                    .orderByDesc(Advertise::getPriority)
                    .last("limit " + count))
            .stream()
            .map(advertise -> new FrontAdvertiseVO(advertise.getPic(), advertise.getUrl()))
            .toList();   // ----------- ①
}

运行程序,出错:

java 复制代码
org.springframework.data.redis.serializer.SerializationException: Could not read JSON:Unexpected token (START_OBJECT), expected VALUE_STRING: need String, Number of Boolean value that contains type id (for subtype of java.lang.Object)
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 1, column: 2] 

解决方案

只需要将编号①处的代码修改为:

java 复制代码
.collect(Collectors.toList());

原理

  • collect(Collectors.toList())‌返回的数据:
  • ‌toList()‌返回的数据:

collect(Collectors.toList()) 和 toList() 的主要区别在于返回的列表类型和可变性:

  • collect(Collectors.toList())‌:返回的是一个普通的 ArrayList ,因此可以进行添加、删除和修改操作‌
  • ‌toList()‌:返回的是通过对原始数组创建一个不可修改的列表。一旦创建,就不能对其进行添加、删除或修改操作‌

‌使用场景‌:

  • ‌toList()‌:适用于不需要对列表进行修改的场景,如从数据库查询数据等,因为它返回的是不可变列表,可以防止数据被意外修改‌
  • ‌collect(Collectors.toList())‌:适用于需要对列表进行修改的场景,因为它返回的是普通的ArrayList,可以进行各种操作‌
相关推荐
Java的搬运工26 分钟前
Spring boot 事件监听
java·spring boot·spring·编程语言
谢亮_vipxieliang30 分钟前
ValidX vs Apache Commons Validator:功能与性能对比
java·服务器·spring boot·后端·spring cloud·apache·hibernate
凤山老林42 分钟前
Spring Boot 3 + Spring Authorization Server 构建企业级 SSO:多端互通、会话共享与
spring boot·后端·spring·单点登录·sso·多端互通
咖啡八杯1 小时前
PageHelper 分页封装:TableDataInfo 与 startPage() 的工作原理
java·spring boot·分页·若依·开源框架·pagehelper
.Hypocritical.1 小时前
【SpringBoot】配置文件加载位置与优先级详解
java·spring boot·后端
十年Java程序媛19 小时前
深度实战:JDK21 虚拟线程 + HikariCP 生产正确配比、坑点、监控全套
java·spring boot
vipxieliang1 天前
ValidX vs Apache Commons Validator:功能与性能对比
java·spring boot
吃饱了得干活1 天前
一篇讲清楚Spring Boot:自动装配、启动器、过滤器、拦截器、设计模式
java·spring boot·后端
草莓熊Lotso1 天前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
jay神1 天前
【计算机毕业设计】基于SpringBoot的程序教学辅助系统
java·前端·vue.js·spring boot·后端·毕业设计·课程设计