文章浏览次数
# 更新浏览次数
应用启动时将浏览量存储到 redis中;
每隔10分钟把 redis中浏览量更新到数据库中;
# CommandLineRunner
SpringBoot应用启动时进行一些初始化操作可以选择使用CommandLineRunner来进行处理;
@Component
public class ViewCountRunner implements CommandLineRunner {
@Autowired
private ArticleMapper articleMapper;
@Autowired
private RedisCache redisCache;
@Override
public void run(String... args) throws Exception {
List<Article> articles = articleMapper.selectList(null);
Map<String, Integer> viewCountMap = articles.stream()
.collect(Collectors.toMap(article -> article.getId().toString(), article -> {
return article.getViewCount().intValue();
}));
redisCache.setCacheMap("article:viewCount",viewCountMap);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 更新浏览次数接口
@PutMapping("/updateViewCount/{id}")
@ApiOperation(value = "文章浏览数")
public ResponseResult updateViewCount(@PathVariable("id") Long id){
return articleService.updateViewCount(id);
}
1
2
3
4
5
2
3
4
5
@Override
public ResponseResult updateViewCount(Long id) {
redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
return ResponseResult.okResult();
}
1
2
3
4
5
2
3
4
5
# 定时任务
启动类上加上@EnableScheduling注解开启定时任务功能
cron表达式:https://www.bejson.com/othertools/cron/
Article添加构造函数:
public Article(Long id, Long viewCount) { this.id = id; this.viewCount = viewCount; }
1
2
3
4任务执行器:
@Component public class UpdateViewCountJob { @Autowired private RedisCache redisCache; @Autowired private ArticleService articleService; @Scheduled(cron = "0/5 * * * * ?") public void updateViewCount(){ Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount"); List<Article> articles = viewCountMap.entrySet() .stream() .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue())) .collect(Collectors.toList()); /*更新到数据库*/ articleService.updateBatchById(articles); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22接口修改:
@Override public ResponseResult getArticleDetail(Long id) { Article article = getById(id); // 阅读量查询 Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString()); article.setViewCount(viewCount.longValue()); ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class); //添加 categroyName Long categoryId = articleDetailVo.getCategoryId(); Category category = categoryService.getById(categoryId); if(category!=null){ articleDetailVo.setCategoryName(category.getName()); } return ResponseResult.okResult(articleDetailVo); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15