mirror of
https://gitee.com/novel_dev_team/novel
synced 2026-07-20 17:52:45 +08:00
fix(book):修复推荐书籍无限循环bug
- 添加空列表检查以避免空指针异常 - 排除当前书籍ID以确保推荐的相关性 - 使用Set代替List提高索引查找效率 - 修复书籍不足时无限循环问题
This commit is contained in:
@@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user