前言
近期在进行阅读类业务的开发工作,核心需求之一是准确记录用户的页面浏览量(PV)和独立访客数(UV)。
当前项目处于前期业务尝试阶段,整体策略偏向轻量化。
主要特点如下:
追求快速实现,避免过度复杂的架构设计,旨在满足初期市场推广和运营的基本需求,从而迅速投入市场。
核心目标是收集用户的原始行为数据,关键要素包括:
明确识别出是谁、在什么时间阅读了哪篇文章。
在处理PV和UV指标时,需重点关注以下特性:
必须考虑系统性能,因为每位用户打开文章都需要进行记录;同时允许存在较小的数据误差,即接受少部分数据的丢失。
架构设计
整体系统架构图如下所示:

详细的业务流程时序图如下:

用于记录基础数据的MySQL表结构设计如下:
CREATE TABLE `zh_article_count` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`bu_no` varchar(32) DEFAULT NULL COMMENT '业务编码',
`customer_id` varchar(32) DEFAULT NULL COMMENT '用户编码',
`type` int(2) DEFAULT '0' COMMENT '统计类型:0APP内文章阅读',
`article_no` varchar(32) DEFAULT NULL COMMENT '文章编码',
`read_time` datetime DEFAULT NULL COMMENT '阅读时间',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
`param1` int(2) DEFAULT NULL COMMENT '预留字段1',
`param2` int(4) DEFAULT NULL COMMENT '预留字段2',
`param3` int(11) DEFAULT NULL COMMENT '预留字段3',
`param4` varchar(20) DEFAULT NULL COMMENT '预留字段4',
`param5` varchar(32) DEFAULT NULL COMMENT '预留字段5',
`param6` varchar(64) DEFAULT NULL COMMENT '预留字段6',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uk_zh_article_count_buno` (`bu_no`),
KEY `key_zh_article_count_csign` (`customer_id`),
KEY `key_zh_article_count_ano` (`article_no`),
KEY `key_zh_article_count_rtime` (`read_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章阅读统计表';
采用的技术实现方案主要包括:
后端框架选用SpringBoot。
引入Redis作为高速缓存层。
使用MySQL作为持久化存储数据库。
代码实现
完整源代码已托管于GitHub,欢迎Star、Fork和Watch。
https://github.com/dangnianchuntian/springboot
以下是主要代码片段的展示:
Controller层实现
/*
* Copyright (c) 2026. zhanghan_java@163.com All Rights Reserved.
* 项目名称:Spring Boot实战解决高并发数据入库: Redis 缓存+MySQL 批量入库
* 类名称:ArticleCountController.java
* 创建人:张晗
* 联系方式:zhanghan_java@163.com
* 开源地址: https://github.com/dangnianchuntian/springboot
* 博客地址: https://zhanghan.blog.csdn.net
*/
package com.zhanghan.zhredistodb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.zhanghan.zhredistodb.controller.request.PostArticleViewsRequest;
import com.zhanghan.zhredistodb.service.ArticleCountService;
@RestController
public class ArticleCountController {
@Autowired
private ArticleCountService articleCountService;
/**
* 记录用户访问记录
*/
@RequestMapping(value = "/post/article/views", method = RequestMethod.POST)
public Object postArticleViews(@RequestBody @Validated PostArticleViewsRequest postArticleViewsRequest) {
return articleCountService.postArticleViews(postArticleViewsRequest);
}
/**
* 批量将缓存中的数据同步到MySQL(模拟定时任务操作)
*/
@RequestMapping(value = "/post/batch", method = RequestMethod.POST)
public Object postBatch() {
return articleCountService.postBatchRedisToDb();
}
Service层逻辑实现
/*
* Copyright (c) 2026. zhanghan_java@163.com All Rights Reserved.
* 项目名称:Spring Boot实战解决高并发数据入库: Redis 缓存+MySQL 批量入库
* 类名称:ArticleCountServiceImpl.java
* 创建人:张晗
* 联系方式:zhanghan_java@163.com
* 开源地址: https://github.com/dangnianchuntian/springboot
* 博客地址: https://zhanghan.blog.csdn.net
*/
package com.zhanghan.zhredistodb.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.zhanghan.zhredistodb.controller.request.PostArticleViewsRequest;
import com.zhanghan.zhredistodb.dto.ArticleCountDto;
import com.zhanghan.zhredistodb.mybatis.mapper.XArticleCountMapper;
import com.zhanghan.zhredistodb.service.ArticleCountService;
import com.zhanghan.zhredistodb.util.wrapper.WrapMapper;
import cn.hutool.core.util.IdUtil;
@Service
public class ArticleCountServiceImpl implements ArticleCountService {
private static Logger logger = LoggerFactory.getLogger(ArticleCountServiceImpl.class);
@Autowired
private RedisTemplate strRedisTemplate;
private XArticleCountMapper xArticleCountMapper;
@Value("${zh.article.count.redis.key:zh}")
private String zhArticleCountRedisKey;
@Value("#{T(java.lang.Integer).parseInt('${zh..article.read.num:3}')}")
private Integer articleReadNum;
/**
* 记录用户访问记录
*/
@Override
public Object postArticleViews(PostArticleViewsRequest postArticleViewsRequest) {
ArticleCountDto articleCountDto = new ArticleCountDto();
articleCountDto.setBuNo(IdUtil.simpleUUID());
articleCountDto.setCustomerId(postArticleViewsRequest.getCustomerId());
articleCountDto.setArticleNo(postArticleViewsRequest.getArticleNo());
articleCountDto.setReadTime(new Date());
String strArticleCountDto = JSON.toJSONString(articleCountDto);
strRedisTemplate.opsForList().rightPush(zhArticleCountRedisKey, strArticleCountDto);
return WrapMapper.ok();
}
* 批量将缓存中的数据同步到MySQL
public Object postBatchRedisToDb() {
Date now = new Date();
while (true) {
List strArticleCountList =
strRedisTemplate.opsForList().range(zhArticleCountRedisKey, 0, articleReadNum);
if (CollectionUtils.isEmpty(strArticleCountList)) {
return WrapMapper.ok();
}
List articleCountDtoList = new ArrayList<>();
strArticleCountList.stream().forEach(x -> {
ArticleCountDto articleCountDto = JSON.parseObject(x, ArticleCountDto.class);
articleCountDtoList.add(articleCountDto);
});
//过滤出本次定时任务之前的缓存中数据,防止死循环
List beforeArticleCountDtoList = articleCountDtoList.stream().filter(x -> x.getReadTime()
.before(now)).collect(Collectors.toList());
if (CollectionUtils.isEmpty(beforeArticleCountDtoList)) {
xArticleCountMapper.batchAdd(beforeArticleCountDtoList);
Integer delSize = beforeArticleCountDtoList.size();
strRedisTemplate.opsForList().trim(zhArticleCountRedisKey, delSize, -1L);
}
}
测试
通过多次请求模拟用户访问后台的行为。

检查Redis缓存中是否成功存储了访问数据。

模拟定时任务执行,将缓存中的数据批量同步到数据库中。

此时再次查看,发现缓存中的数据已被清空。

检查MySQL数据库表结构及新增数据。

总结
- 关于项目中定时任务的几点说明:
- 演示中为方便起见使用HTTP请求代替定时任务调度;在实际生产项目中建议使用XXL-JOB等调度框架,可参考《定时任务的选型及改造》一文。
- 在定时任务执行过程中,应使用Redis锁防止并发冲突(如调度端多次触发),可参考《Redis实现计数器—接口防刷—升级版(Redis+Lua)》。
- 后期运营分析可从阅读记录表中拉取数据进行深度挖掘。
- 当访问量巨大时,建议将MySQL中的阅读记录表定期迁移至历史表或使用MongoDB等NoSQL数据库进行归档。
到此这篇关于Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库的文章就介绍到这了,更多相关Spring Boot高并发数据入库内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!