Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题


Posted in Redis onFebruary 12, 2022

前言

最近在做阅读类的业务,需要记录用户的PV,UV;

项目状况:前期尝试业务阶段;

特点:

快速实现(不需要做太重,满足初期推广运营即可)快速投入市场去运营

收集用户的原始数据,三要素:

谁在什么时间阅读哪篇文章

提到PV,UV脑海中首先浮现特点:

需要考虑性能(每个客户每打开一篇文章进行记录)允许数据有较小误差(少部分数据丢失)

架构设计

架构图:

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

时序图

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

记录基础数据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) 2020. 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) 2020. 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<String, String> 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<String> strArticleCountList =
                    strRedisTemplate.opsForList().range(zhArticleCountRedisKey, 0, articleReadNum);
            if (CollectionUtils.isEmpty(strArticleCountList)) {
                return WrapMapper.ok();
            }
            List<ArticleCountDto> articleCountDtoList = new ArrayList<>();
            strArticleCountList.stream().forEach(x -> {
                ArticleCountDto articleCountDto = JSON.parseObject(x, ArticleCountDto.class);
                articleCountDtoList.add(articleCountDto);
            });
            //过滤出本次定时任务之前的缓存中数据,防止死循环
            List<ArticleCountDto> 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);
        }
}

测试

模拟用户请求访问后台(多次请求)

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

查看缓存中访问数据

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

模拟定时任务将缓存中数据同步到DB中

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

这时查看缓存中的数据已经没了

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

查看数据库表结构

Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库问题

总结

  • 项目中定时任务
  • 问演示方便用http代替定时任务调度;实际项目中用XXL-job
  • 定时任务项目中用redis锁防止并发(定时任务调度端多次调度等)
  • 后期运营数据可以从阅读记录表中拉数据进行相关分析
  • 访问量大:可以将MySQL中的阅读记录表定时迁移走(MySQL建历史表,MongoDB等)

到此这篇关于Spring Boot实战解决高并发数据入库之 Redis 缓存+MySQL 批量入库的文章就介绍到这了,更多相关Spring Boot高并发数据入库内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Redis 相关文章推荐
浅谈redis五大数据结构和使用场景
Apr 12 Redis
Redis数据结构之链表与字典的使用
May 11 Redis
redis实现的四种常见限流策略
Jun 18 Redis
redis客户端实现高可用读写分离的方式详解
Jul 04 Redis
Redis做数据持久化的解决方案及底层原理
Jul 15 Redis
redis 存储对象的方法对比分析
Aug 02 Redis
Redis 持久化 RDB 与 AOF的执行过程
Nov 07 Redis
Springboot/Springcloud项目集成redis进行存取的过程解析
Dec 04 Redis
Redis基本数据类型哈希Hash常用操作命令
Jun 01 Redis
Redis sentinel哨兵集群的实现步骤
Jul 15 Redis
Redis配置外网可访问(redis远程连接不上)的方法
Dec 24 Redis
基于Redis zSet实现滑动窗口对短信进行防刷限流的问题
Feb 12 #Redis
聊聊redis-dump工具安装问题
Jan 18 #Redis
redis的list数据类型相关命令介绍及使用
Jan 18 #Redis
关于使用Redisson订阅数问题
Jan 18 #Redis
Redis中缓存穿透/击穿/雪崩问题和解决方法
linux下安装redis图文详细步骤
Springboot/Springcloud项目集成redis进行存取的过程解析
You might like
php基础知识:函数基础知识
2006/12/13 PHP
推荐个功能齐全的发送PHP邮件类
2007/01/03 PHP
php实现随机显示图片方法汇总
2015/05/21 PHP
ThinkPHP3.2.3框架Memcache缓存使用方法实例总结
2019/04/15 PHP
artdialog的图片/标题以及关闭按钮不显示的解决方法
2013/06/27 Javascript
javascript 获取浏览器版本
2015/01/21 Javascript
javascript创建动态表单的方法
2015/07/25 Javascript
微信小程序 Buffer缓冲区的详解
2017/07/06 Javascript
详谈JS中数组的迭代方法和归并方法
2017/08/11 Javascript
使用vue-cli创建项目的图文教程(新手入门篇)
2018/05/02 Javascript
vue+axios+mock.js环境搭建的方法步骤
2018/08/28 Javascript
关于JavaScript中高阶函数的魅力详解
2018/09/07 Javascript
支付宝小程序自定义弹窗dialog插件的实现代码
2018/11/30 Javascript
关于node-bindings无法在Electron中使用的解决办法
2018/12/18 Javascript
12 种使用Vue 的最佳做法
2020/03/30 Javascript
JS XMLHttpRequest原理与使用方法深入详解
2020/04/30 Javascript
解决vue项目中遇到 Cannot find module ‘chalk‘ 报错的问题
2020/11/05 Javascript
[05:22]DOTA2 2015国际邀请赛中国区预选赛首日TOP10
2015/05/26 DOTA
python之wxPython应用实例
2014/09/28 Python
Python创建文件和追加文件内容实例
2014/10/21 Python
python中list常用操作实例详解
2015/06/03 Python
基于python爬虫数据处理(详解)
2017/06/10 Python
Python实现类似比特币的加密货币区块链的创建与交易实例
2018/03/20 Python
python+selenium打印当前页面的titl和url方法
2018/06/22 Python
对pandas的层次索引与取值的新方法详解
2018/11/06 Python
tensorflow mnist 数据加载实现并画图效果
2020/02/05 Python
CSS3属性box-shadow使用详细教程
2012/01/21 HTML / CSS
美国百货齐全的精品网站,提供美式风格的产品:Overstock.com
2016/07/22 全球购物
美国眼镜网:GlassesUSA
2017/09/07 全球购物
物业保安主管岗位职责
2013/12/25 职场文书
水利学院求职自荐书
2014/02/01 职场文书
财产公证书样本
2014/04/04 职场文书
保护野生动物倡议书
2014/05/16 职场文书
人力资源管理系自荐信
2014/05/31 职场文书
群众路线教育实践活动对照检查材料
2014/09/22 职场文书
Python写情书? 10行代码展示如何把情书写在她的照片里
2022/04/21 Python