抢票 提前9分钟
All checks were successful
continuous-integration/drone Build is passing

This commit is contained in:
liukang 2025-02-21 15:51:44 +08:00
parent eab0cdfa16
commit 97ccfaa912
10 changed files with 229 additions and 61 deletions

2
run.sh
View File

@ -14,7 +14,7 @@ echo '----rm image----'
# 打包编译docker镜像
docker build -t ${group_name}/${app_name}:${app_version} .
echo '----build image----'
docker run -it -p 7072:8080 --name ${app_name} \
docker run -it -p 7072:8080 --name ${app_name} --restart=always \
--env=SPRING_CONFIG_LOCATION=/config/application.yml \
-v /etc/localtime:/etc/localtime \
-v /home/d1/project/weverse-api/logs:/home/weverse/logs \

View File

@ -0,0 +1,30 @@
package com.ruoyi.web.task;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
public class MyReq {
private HttpClient client;
private HttpRequest request;
public HttpClient getClient() {
return client;
}
public void setClient(HttpClient client) {
this.client = client;
}
public HttpRequest getRequest() {
return request;
}
public void setRequest(HttpRequest request) {
this.request = request;
}
public MyReq(HttpClient client, HttpRequest request) {
this.client = client;
this.request = request;
}
}

View File

@ -1,12 +1,14 @@
package com.ruoyi.web.task;
import com.ruoyi.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.domain.Apply;
import com.ruoyi.system.domain.Perform;
import com.ruoyi.system.mapper.ApplyMapper;
import com.ruoyi.system.mapper.PerformMapper;
import com.ruoyi.system.service.IPerformService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -14,6 +16,7 @@ import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
@ -26,45 +29,109 @@ public class RyTask {
@Autowired
private ISysJobService jobService;
@Autowired
private IPerformService performService;
@Autowired
private PerformMapper performMapper;
@Autowired
private ApplyMapper applyMapper;
private static final Logger log = LoggerFactory.getLogger(RyTask.class);
/**
* 抢票
*
* @param pid
*/
public void rob(Long pid, Long jobId) throws SchedulerException {
Perform perform = performService.selectPerformById(pid);
System.out.println(pid + "," + jobId);
for (int i = 0; i < 100; i++) {
System.out.println("开始");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.GET()
.build();
// 发起异步请求但不等待结果
CompletableFuture<HttpResponse<String>> future2 = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
future2.thenAccept(response -> {
// 处理响应例如记录日志
System.out.println("Response received: " + response.statusCode());
}).exceptionally(ex -> {
// 处理异常
ex.printStackTrace();
return null;
});
System.out.println("异步任务完成");
}
public void rob(Long pid, Long jobId) throws Exception {
//status
Perform pStatus1 = new Perform();
pStatus1.setStatus("2");
pStatus1.setId(pid);
performMapper.updatePerform(pStatus1);
//执行完成停止任务
SysJob job = new SysJob();
job.setJobId(jobId);
job.setStatus("1");
jobService.changeStatus(job);
//演出
Perform perform = performMapper.selectPerformById(pid);
if (perform == null) {
throw new Exception("未找到演出");
}
//URL
String url = String.format("https://faneventapi.weverse.io/api/v1/events/%s/register", perform.getNum());
//人员
Apply apply = new Apply();
apply.setPerformId(pid);
List<Apply> applies = applyMapper.selectApplyListAllow(apply);
if (applies == null || applies.isEmpty()) {
throw new Exception("没有参与人员");
}
if (perform.getAgree() == null || "".equals(perform.getAgree())) {
throw new Exception("协议为空");
}
//协议
String[] agree = perform.getAgree().split(",");
int[] agrees = Arrays.stream(agree).mapToInt(Integer::parseInt).toArray();
List<MyReq> req = new ArrayList<>();
for (Apply a : applies) {
// 准备JSON负载
Map<String, Object> eventData = new HashMap<>();
eventData.put("eventId", Integer.parseInt(perform.getNum()));
eventData.put("language", "zh-cn");
Map<String, Object> data = new HashMap<>();
data.put("birthDate", a.getBirthday());
data.put("phoneNumber", a.getCountryCode() + " " + a.getPhoneNum());
data.put("agreedTermIds", agrees);
eventData.put("data", data);
ObjectMapper mapper = new ObjectMapper();
String jsonPayload = mapper.writeValueAsString(eventData);
System.out.println(jsonPayload);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + a.getToken())
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
req.add(new MyReq(client, request));
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(perform.getStartTime());
calendar.add(Calendar.HOUR_OF_DAY, -1);
long start = calendar.getTimeInMillis();
long now = System.currentTimeMillis();
Thread.sleep(start - now);
log.info("抢票开始了");
for (MyReq r : req) {
// 发起异步请求但不等待结果
CompletableFuture<HttpResponse<String>> future2 = r.getClient().sendAsync(r.getRequest(), HttpResponse.BodyHandlers.ofString());
future2.thenAccept(response -> {
// 处理响应例如记录日志
System.out.println("Response received: " + response.statusCode());
System.out.println(response.body());
}).exceptionally(ex -> {
// 处理异常
ex.printStackTrace();
return null;
});
}
//status
Perform pStatus2 = new Perform();
pStatus2.setStatus("3");
pStatus2.setId(pid);
performMapper.updatePerform(pStatus2);
}
}

View File

@ -72,7 +72,7 @@ spring:
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
database: 1
# 密码
password: Yy5203344.
# 连接超时时间

View File

@ -1,10 +1,13 @@
package com.ruoyi.system.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.util.Date;
/**
* 申请对象 apply
*
@ -59,19 +62,13 @@ public class Apply extends BaseEntity
@Excel(name = "状态")
private String status;
/**
* 演出
*/
private Perform perform;
/** 名称 */
private String name;
/** 开始时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
public Perform getPerform() {
return perform;
}
public void setPerform(Perform perform) {
this.perform = perform;
}
public Long getUserId() {
return userId;
@ -172,6 +169,23 @@ public class Apply extends BaseEntity
return status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)

View File

@ -27,6 +27,10 @@ public interface ApplyMapper
*/
public List<Apply> selectApplyList(Apply apply);
public List<Apply> selectApplyListAllow(Apply apply);
public Apply selectApplyPerform(Apply apply);
/**
* 新增申请

View File

@ -34,6 +34,14 @@ public interface PerformMapper
*/
public List<Perform> selectPerformList(Perform perform);
/**
* 查询演出列表
*
* @param perform 演出
* @return 演出集合
*/
public List<Perform> selectPerformVerify(Perform perform);
/**
* 查询演出列表
*

View File

@ -80,6 +80,12 @@ public class PerformServiceImpl implements IPerformService {
if (perform.getStartTime().compareTo(new Date()) <= 0) {
throw new Exception("开始时间必须大于当前时间");
}
Perform query = new Perform();
query.setNum(perform.getNum());
List<Perform> performs = performMapper.selectPerformVerify(query);
if (!performs.isEmpty()) {
throw new Exception("演出Num已存在");
}
perform.setCreateTime(DateUtils.getNowDate());
//未开始
perform.setStatus("1");
@ -96,7 +102,7 @@ public class PerformServiceImpl implements IPerformService {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, -1);
calendar.add(Calendar.MINUTE, 9);
calendar.add(Calendar.MINUTE, -9);
// 获取年
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始所以加1
@ -114,6 +120,7 @@ public class PerformServiceImpl implements IPerformService {
SysJob job = new SysJob();
job.setJobName(name + " " + formattedDate);
job.setConcurrent("0");
job.setCronExpression(cron);
job.setInvokeTarget("ryTask.rob(" + pid + "L)");
job.setJobGroup("DEFAULT");
@ -137,6 +144,13 @@ public class PerformServiceImpl implements IPerformService {
if (perform.getStartTime().compareTo(new Date()) <= 0) {
throw new Exception("开始时间必须大于当前时间");
}
Perform query = new Perform();
query.setNum(perform.getNum());
query.setId(perform.getId());
List<Perform> performs = performMapper.selectPerformVerify(query);
if (!performs.isEmpty()) {
throw new Exception("演出Num已存在");
}
perform.setUpdateTime(DateUtils.getNowDate());
return performMapper.updatePerform(perform);
}

View File

@ -20,11 +20,8 @@
<result property="updateBy" column="update_by"/>
<result property="updateTime" column="update_time"/>
<result property="remark" column="remark"/>
<association property="perform" javaType="Perform">
<result property="name" column="name"/>
<result property="startTime" column="start_time"/>
</association>
<result property="name" column="name"/>
<result property="startTime" column="start_time"/>
</resultMap>
<sql id="selectApplyVo">
@ -66,19 +63,43 @@
p.start_time
from apply a left join perform p on p.id = a.perform_id
<where>
<if test="userId != null ">and user_id = #{userId}</if>
<if test="performId != null ">and perform_id = #{performId}</if>
<if test="weverseEmail != null and weverseEmail != ''">and weverse_email = #{weverseEmail}</if>
<if test="weversePassword != null and weversePassword != ''">and weverse_password = #{weversePassword}</if>
<if test="birthday != null and birthday != ''">and birthday = #{birthday}</if>
<if test="countryCode != null and countryCode != ''">and country_code = #{countryCode}</if>
<if test="phoneNum != null and phoneNum != ''">and phone_num = #{phoneNum}</if>
<if test="wechatNum != null and wechatNum != ''">and wechat_num = #{wechatNum}</if>
<if test="token != null and token != ''">and token = #{token}</if>
<if test="status != null and status != ''">and status = #{status}</if>
<if test="userId != null ">and a.user_id = #{userId}</if>
<if test="performId != null ">and a.perform_id = #{performId}</if>
<if test="weverseEmail != null and weverseEmail != ''">and a.weverse_email = #{weverseEmail}</if>
<if test="weversePassword != null and weversePassword != ''">and a.weverse_password = #{weversePassword}</if>
<if test="birthday != null and birthday != ''">and a.birthday = #{birthday}</if>
<if test="countryCode != null and countryCode != ''">and a.country_code = #{countryCode}</if>
<if test="phoneNum != null and phoneNum != ''">and a.phone_num = #{phoneNum}</if>
<if test="wechatNum != null and wechatNum != ''">and a.wechat_num = #{wechatNum}</if>
<if test="token != null and token != ''">and a.token = #{token}</if>
<if test="status != null and status != ''">and a.status = #{status}</if>
</where>
</select>
<select id="selectApplyListAllow" parameterType="Apply" resultMap="ApplyResult">
select a.id,
a.perform_id,
a.weverse_email,
a.weverse_password,
a.birthday,
a.country_code,
a.phone_num,
a.wechat_num,
a.token,
a.status,
a.create_by,
a.create_time,
a.update_by,
a.update_time,
a.remark,
p.name,
p.start_time
from apply a left join perform p on p.id = a.perform_id
where a.perform_id = #{performId}
and a.status = '2'
and a.token is not null
</select>
<select id="selectApplyPerform" parameterType="Apply" resultMap="ApplyResult">
<include refid="selectApplyVo"/>
where user_id = #{userId} and perform_id = #{performId}

View File

@ -31,6 +31,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</where>
</select>
<select id="selectPerformVerify" parameterType="Perform" resultMap="PerformResult">
<include refid="selectPerformVo"/>
<where>
<if test="num != null and num != ''">and num = #{num}</if>
<if test="id != null ">and id != #{id}</if>
</where>
</select>
<select id="selectAll" resultMap="PerformResult">
<include refid="selectPerformVo"/>
where status = '1'
@ -54,6 +62,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
insert into perform
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="num != null">num,</if>
<if test="agree != null and agree != ''">agree,</if>
<if test="name != null and name != ''">name,</if>
<if test="startTime != null">start_time,</if>
<if test="status != null and status != ''">status,</if>
@ -62,9 +71,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="updateBy != null">update_by,</if>
<if test="updateTime != null">update_time,</if>
<if test="remark != null">remark,</if>
</trim>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="num != null">#{num},</if>
<if test="agree != null and agree != ''">#{agree},</if>
<if test="name != null and name != ''">#{name},</if>
<if test="startTime != null">#{startTime},</if>
<if test="status != null and status != ''">#{status},</if>
@ -73,7 +83,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="updateBy != null">#{updateBy},</if>
<if test="updateTime != null">#{updateTime},</if>
<if test="remark != null">#{remark},</if>
</trim>
</trim>
</insert>
<update id="updatePerform" parameterType="Perform">