1 秒杀系统模拟基础实现,使用DB实现

2024-04-06 12:58

本文主要是介绍1 秒杀系统模拟基础实现,使用DB实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文根据动脑学院的一节类似的课程,改编实现。分别使用DB和redis来完成。



隔离的解释

业务隔离:将秒杀业务独立出来,尽量不与其他业务关联,以减少对其他业务的依赖性。譬如秒杀业务只保留用户id,商品id,数量等重要属性,通过中间件发送给业务系统,完成后续的处理。

系统隔离:将秒杀业务单独部署,以减少对其他业务服务器的压力。

数据隔离:由于秒杀对DB的压力很大,将DB单独部署,不与其他业务DB放一起,避免对DB的压力。



本篇讲使用DB完成秒杀系统。下一篇使用redis完成持久层。

一 初始化项目

以Springboot,mysql,jpa为技术方案。

新建Springboot项目,pom如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.tianyalei</groupId><artifactId>common</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>common</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional><!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 --></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.18</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

javaBean

package com.tianyalei.model;import javax.persistence.*;/*** Created by wuwf on 17/7/5.*/
@Entity
public class GoodInfo {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Integer id;//数量private int amount;//商品编码@Column(unique = true)private String code;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public int getAmount() {return amount;}public void setAmount(int amount) {this.amount = amount;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}
}
dao层,注意一下sql语句,where条件中的amount - count >= 0是关键,该语句能严格保证不超卖。

package com.tianyalei.repository;import com.tianyalei.model.GoodInfo;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;/*** Created by admin on 17/7/5.*/
public interface GoodInfoRepository extends CrudRepository<GoodInfo, Integer> {@Query("update GoodInfo set amount = amount - ?2 where code = ?1 and amount - ?2 >= 0")@Modifyingint updateAmount(String code, int count);
}

service接口

package com.tianyalei.service;import com.tianyalei.model.GoodInfo;/*** Created by wuwf on 17/7/5.*/
public interface GoodInfoService {void add(GoodInfo goodInfo);void delete(GoodInfo goodInfo);int update(String code, int count);
}

Service实现类

package com.tianyalei.service;import com.tianyalei.model.GoodInfo;
import com.tianyalei.repository.GoodInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;/*** Created by wuwf on 17/7/5.*/
@Service("db")
public class GoodInfoDbService implements GoodInfoService {@Autowiredprivate GoodInfoRepository goodInfoRepository;@Transactionalpublic int update(String code, int count) {return goodInfoRepository.updateAmount(code, count);}public void add(GoodInfo goodInfo) {goodInfoRepository.save(goodInfo);}public void delete(GoodInfo goodInfo) {goodInfoRepository.deleteAll();}}
yml配置文件
spring:jpa:database: mysqlshow-sql: truehibernate:ddl-auto: updatedatasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/testusername: rootpassword:redis:host: localhostport: 6379password:pool:max-active: 8max-idle: 8min-idle: 0max-wait: 10000profiles:active: dev
server:port: 8080
以上即是基本配置。

二 模拟并发访问抢购

新建junit测试类
package com.tianyalei;import com.tianyalei.model.GoodInfo;
import com.tianyalei.service.GoodInfoService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;/*** Created by wuwf on 17/7/5.*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {@Resource(name = "db")private GoodInfoService service;private String goodCode = "iphone7";/*** 机器总数量*/private int goodAmount = 100;/*** 并发量*/private int threadNum = 200;//销售量private int goodSale = 0;//买成功的数量private int accountNum = 0;//买成功的人的ID集合private List<Integer> successUsers = new ArrayList<>();private GoodInfo goodInfo;/*当创建 CountDownLatch 对象时,对象使用构造函数的参数来初始化内部计数器。每次调用 countDown() 方法,CountDownLatch 对象内部计数器减一。当内部计数器达到0时, CountDownLatch 对象唤醒全部使用 await() 方法睡眠的线程们。*/private CountDownLatch countDownLatch = new CountDownLatch(threadNum);@Testpublic void contextLoads() {for (int i = 0; i < threadNum; i++) {new Thread(new UserRequest(goodCode, 7, i)).start();countDownLatch.countDown();}//让主线程等待200个线程执行完,休息2秒,不休息的话200条线程还没执行完,就打印了try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("-----------购买成功的用户数量----------为" + accountNum);System.out.println("-----------销售量--------------------为" + goodSale);System.out.println("-----------剩余数量------------------为" + (goodAmount - goodSale));System.out.println(successUsers);}private class UserRequest implements Runnable {private String code;private int buyCount;private int userId;public UserRequest(String code, int buyCount, int userId) {this.code = code;this.buyCount = buyCount;this.userId = userId;}@Overridepublic void run() {try {//让线程等待,等200个线程创建完一起执行countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}//如果更新数据库成功,也就代表购买成功了if (service.update(code, buyCount) > 0) {//对service加锁,因为很多线程在访问同一个service对象,不加锁将导致购买成功的人数少于预期,且数量不对,可自行测试synchronized (service) {//销售量goodSale += buyCount;accountNum++;//收录购买成功的人successUsers.add(userId);}}}}@Beforepublic void add() {goodInfo = new GoodInfo();goodInfo.setCode(goodCode);goodInfo.setAmount(goodAmount);service.add(goodInfo);}@Afterpublic void delete() {service.delete(goodInfo);}}

注意,由于是模拟并发,需要保证200个线程同时启动去访问数据库,所以使用了CountDownLatch类,在调用UserRequest线程的start方法后,会先进入await状态,等待200个线程创建完毕后,一起执行。

注意,由于是多线程操作service,必然导致数据不同步,所以需要对service加synchronize锁,来保证service的update方法能够正确执行。如果不加,可以自行测试,会导致少卖。
运行该测试类,看打印的结果。



可以多次运行,并修改每个人的购买数量、总商品数量、线程数,看看结果是否正确。

如修改为每人购买8个

mysql支持的并发访问量有限,倘若并发量较小,可以采用上面的update的sql就能控制住,倘若量大,可以考虑使用nosql。

下一篇讲一下redis模拟的方式。

这篇关于1 秒杀系统模拟基础实现,使用DB实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/879948

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没