java订单抢购业务解决方案(抢购排队)
2022-06-09 本文已影响0人
姬拉
刚接手一个小站点,排队下单业务,由于普通时间业务量不大,在抢购活动(1000套)进行时,遇到数据库读取瓶颈。如下是一种轻便解决方案思路,有不足的大神指点一二。
说明:通过全局变量,限制下单数量和排队数量,在队列未消化前,让客户端等待下次发起
--全局变量,卡单,订单限制
/**
* Created by lala on 2022/6/8.
*/
public class Tools {
//全局变量,当前出单数量
public static int out_count = 0;
//最大的处理量
public volatile static int maxtodo=0;
}
--创建线程池,模拟多线程下单
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by lala on 2022/6/8.
*/
public class MultiThread {
//线程池
ExecutorService executorService = Executors.newCachedThreadPool();
public void testorder(){
ThreadService threadService = new ThreadService();
//线程池操作
executorService.submit(()->threadService.order());
executorService.submit(()->threadService.order());
executorService.submit(()->threadService.order());
executorService.submit(()->threadService.order());
}
}
--下单业务
/**
- Created by lala on 2022/6/8.
*/
public class ThreadService {
static ThreadService instance = new ThreadService();
public void order() {
//当前线程执行数量
int docount = 0;
//当最订单不满足接着循环
while (Tools.out_count<1000){
synchronized (instance) {
//再次校验
if (Tools.out_count >=1000) {
break;
}
//最大排队数量
if(Tools.maxtodo>=10){
//通知客户端等待,结束当前http请求
continue;
}
//开始执行新的订单,maxtodo+1
Tools.maxtodo++;
docount++;
try {
//执行的时间
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//执行完总数量+一单
Tools.out_count++;
//执行结束当前排队减1
Tools.maxtodo--;
}
}
System.out.println("线程:" + Thread.currentThread().getName() + "出单了:" + docount + ", 总出单=" + Tools.out_count);
}
}
--测试方法
public class test {
public static void main(String[] args) {
MultiThread multiThread = new MultiThread();
multiThread.testorder();
multiThread.executorService.shutdown();
}
}