空指针问题解决方案注意点:
1.打断点调试
2.sout控制台查看
3.查看实体类各注释
4.注意更新字段(自动填充)的判空问题
博客项目中问题:
UpdateViewCountJob类:
修改方法:
public void updateViewCount() {
//获取redis中浏览量数据
Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");
System.out.println(viewCountMap);
List<Article> articles = viewCountMap.entrySet()
.stream()
.map(entry ->
new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
.collect(Collectors.toList());
System.out.println("执行定时任务:更新文章浏览量");
for (Article article : articles) {
LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(Article::getId, article.getId());
updateWrapper.set(Article::getViewCount, article.getViewCount());
articleService.update(updateWrapper);
}
}
从Redis缓存中获取文章浏览量数据,并将其转换为Article对象(实体类)的列表。然后,通过循环遍历列表,使用LambdaUpdateWrapper更新数据库中对应文章的浏览量信息。
使用redisCache的getCacheMap方法获取名为"article:viewCount"的缓存数据(即radis中的键名),并将其存储在viewCountMap变量中。
通过stream流对viewCountMap中的每个键值对进行处理。使用map方法将键值对转换为Article对象,并将其存储在articles列表中。
输出执行定时任务的提示信息到控制台给开发者。
通过循环遍历articles列表,对每个Article对象执行更新操作。创建一个LambdaUpdateWrapper对象,设置更新条件为文章id与当前循环的Article对象的id相等,然后使用set方法设置更新字段为浏览量,并将其更新到数据库中。
从而将Redis中保存的浏览量数据更新到数据库中。