本文最后更新于 2026年3月15日 晚上
博客文章预览量接口
博客文章预览量接口需求
根据用户预览文章次数增加预览量
在程序启动前先将数据库中的文章浏览量写入redis
然后更新浏览量时同步去更新redis的数据
再每隔10分钟将redis的数据更新到数据库中
这样就可以做到用户读取浏览量时始终从redis中读取
避免在高并发场景下对数据库的负载过大造成的性能问题
代码实现
先创建程序启动初始化类,来实现应用启动时先将数据库里的数据存入redis中,方便后续从redis中拿数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| @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(), new Function<Article, Integer>() { @Override public Integer apply(Article article) { return article.getViewCount().intValue(); } }));
redisCache.setCacheMap(SystemConstants.ARTICLE_VIEW_COUNT, viewCountMap); System.out.println("! ======程序初始化完成====== !"); } }
|
再创建执行定时任务的类,来实现 每隔10分钟将redis的数据更新到数据库中 的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Component public class UpdateViewCountJob { @Autowired private RedisCache redisCache;
@Autowired private ArticleService articleService;
@Scheduled(cron = "* 0/10 * * * ?") public void updateViewCount() { Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.ARTICLE_VIEW_COUNT);
List<Article> articles = viewCountMap.entrySet() .stream() .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue())) .collect(Collectors.toList()); articleService.updateBatchById(articles); } }
|
然后在redis工具类中添加用于在redis中增值的方法
再在Article中添加构造方法
剩下的就是常规操作了,在ArticleController中添加相关接口方法,实现方法,实现服务类等,下面只展示关键的服务类方法代码
由于上面已经将前置类写好了,这里调用就行,很方便
1 2 3 4 5 6 7 8
| @Override public ResponseResult viewCount(Long id) { redisCache.incrementCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT, id.toString(), 1); return ResponseResult.okResult(); }
|
现在已经实现将redis中的数据定时存入数据库,然而还没有实现将redis中的数据实时传递到前端
由于redis的数据是每隔10分钟更新至数据库
这就导致前端得到的数据一直是数据库中redis10分钟前更新的旧数据,无法做到实时更新数据
下面要做的就是将redis中的数据实时传递给前端
在文章相关的接口实现服务方法中添加下面代码实现这个功能
1 2 3 4 5
| list.forEach(article -> { Integer viewCount = redisCache.getCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT, article.getId().toString()); article.setViewCount(viewCount.longValue()); });
|
在houArticleList中添加
在articleList中添加
在getArticleDetail中添加
在articleListByCategoryId中添加
值得注意的是,目前开发阶段只涉及到 根据分类id查询文章列表 的功能
而后续开发还打算添加一个 根据标签id查询文章列表 的功能
后续的开发中也要注意要添加从redis中获取viewCount的方法实现
此博客系统的前台所包含的前端和后端基本开发完整(差一个文章所属标签和标签页未完善),因为先前已经写了一个分类是与标签功能相似的了,
而且后台系统中写文章相关也是要选择标签和分类的,
所以选择留到后续开发后台系统时再进行完善
PS:该系列只做为作者学习开发项目做的笔记用
不一定符合读者来学习,仅供参考
预告
后续会记录博客的开发过程
每次学习会做一份笔记来进行发表
“一花一世界,一叶一菩提”
版权所有 © 2025 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/