fix(book):修复推荐书籍无限循环bug

- 添加空列表检查以避免空指针异常
- 排除当前书籍ID以确保推荐的相关性
- 使用Set代替List提高索引查找效率
- 修复书籍不足时无限循环问题
This commit is contained in:
Atri
2025-11-01 12:02:43 +08:00
parent fb280bd85a
commit cf510dce38

View File

@@ -126,20 +126,39 @@ public class BookServiceImpl implements BookService {
throws NoSuchAlgorithmException { throws NoSuchAlgorithmException {
Long categoryId = bookInfoCacheManager.getBookInfo(bookId).getCategoryId(); Long categoryId = bookInfoCacheManager.getBookInfo(bookId).getCategoryId();
List<Long> lastUpdateIdList = bookInfoCacheManager.getLastUpdateIdList(categoryId); List<Long> lastUpdateIdList = bookInfoCacheManager.getLastUpdateIdList(categoryId);
// 检查列表是否为空或不足
if (CollectionUtils.isEmpty(lastUpdateIdList)) {
return RestResp.ok(Collections.emptyList());
}
// 排除当前书籍,同时确保有足够的推荐书籍用于展示
List<Long> candidateIdList = lastUpdateIdList.stream()
.filter(id -> !Objects.equals(id, bookId))
.toList();
if (candidateIdList.isEmpty()) {
return RestResp.ok(Collections.emptyList());
}
// 确定实际推荐的书籍数量
int actualRecCount = Math.min(REC_BOOK_COUNT, candidateIdList.size());
List<BookInfoRespDto> respDtoList = new ArrayList<>(); List<BookInfoRespDto> respDtoList = new ArrayList<>();
List<Integer> recIdIndexList = new ArrayList<>(); Set<Integer> recIdIndexSet = new HashSet<>();
int count = 0;
Random rand = SecureRandom.getInstanceStrong(); Random rand = SecureRandom.getInstanceStrong();
while (count < REC_BOOK_COUNT) {
int recIdIndex = rand.nextInt(lastUpdateIdList.size()); // 使用 Set 提高查找效率同时修复bug防止无限循环
if (!recIdIndexList.contains(recIdIndex)) { while (respDtoList.size() < actualRecCount && recIdIndexSet.size() < candidateIdList.size()) {
recIdIndexList.add(recIdIndex); int recIdIndex = rand.nextInt(candidateIdList.size());
bookId = lastUpdateIdList.get(recIdIndex); if (!recIdIndexSet.contains(recIdIndex)) {
BookInfoRespDto bookInfo = bookInfoCacheManager.getBookInfo(bookId); recIdIndexSet.add(recIdIndex);
Long recBookId = candidateIdList.get(recIdIndex);
BookInfoRespDto bookInfo = bookInfoCacheManager.getBookInfo(recBookId);
respDtoList.add(bookInfo); respDtoList.add(bookInfo);
count++;
} }
} }
return RestResp.ok(respDtoList); return RestResp.ok(respDtoList);
} }