SpringBoot中使用@Cacheable:
錯誤代碼:
@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(); // ----------- ①
}
運行程序,出錯:
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]
解決方案
只需要將編號①處的代碼修改為:
.collect(Collectors.toList());
原理
- collect(Collectors.toList())?返回的數據:
- ?toList()?返回的數據:
collect(Collectors.toList()) 和 toList() 的主要區別在于返回的列表類型和可變性:
- collect(Collectors.toList())?:返回的是一個普通的 ArrayList ,因此可以進行添加、刪除和修改操作?
- ?toList()?:返回的是通過對原始數組創建一個不可修改的列表。一旦創建,就不能對其進行添加、刪除或修改操作?
?使用場景?:
- ?toList()?:適用于不需要對列表進行修改的場景,如從數據庫查詢數據等,因為它返回的是不可變列表,可以防止數據被意外修改?
- ?collect(Collectors.toList())?:適用于需要對列表進行修改的場景,因為它返回的是普通的ArrayList,可以進行各種操作?