This commit is contained in:
2026-03-17 16:34:53 +08:00
commit e7dd712164
60 changed files with 595234 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf
+35
View File
@@ -0,0 +1,35 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
benchmark/results/
+3
View File
@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
+104
View File
@@ -0,0 +1,104 @@
# Benchmark 测试套件
本目录包含完整的 k6 压测脚本,用于验证简历中提到的技术方案。
## 前置要求
1. **安装 k6**:
```bash
# Arch Linux
paru -S k6
# 或使用官方脚本
https://k6.io/docs/getting-started/installation/
```
2. **启动服务**:
```bash
cd /home/mcallzbl/File2/Workshop/Test/dataTest/demo
./mvnw spring-boot:run
```
## 快速开始
运行所有测试:
```bash
cd /home/mcallzbl/File2/Workshop/Test/dataTest/demo
./benchmark/run-benchmark.sh
```
指定服务地址:
```bash
BASE_URL=http://your-server:8080 ./benchmark/run-benchmark.sh
```
## 测试说明
### Test 2.1: 任务幂等性测试
- **文件**: `test-2.1-task-idempotent.js`
- **目的**: 验证 100 个并发请求只创建 1 条任务记录
- **验证**: 通过数据库唯一约束 + Redisson 分布式锁
### Test 2.2: 消息消费幂等测试
- **文件**: `test-2.2-message-idempotent.js`
- **目的**: 验证消息重复投递只处理一次
- **验证**: 通过乐观锁 + 手动 ACK
### Test 2.3: 点赞高并发压测
- **文件**:
- `test-2.3-like-benchmark-a.js` - 方案A:直接落库
- `test-2.3-like-benchmark-b.js` - 方案B:Redis + 批量落库
- **目的**: 对比两种方案的性能差异
- **预期**: 方案B QPS 提升至 10 倍以上
### Test 2.4: 缓存一致性测试
- **文件**: `test-2.4-cache-consistency.js`
- **目的**: 验证读写并发时的数据一致性
- **验证**: 延迟双删策略
### Test 2.5: ZSET + HASH 性能测试
- **文件**:
- `test-2.5-zset-hash-redis.js` - Redis 查询
- `test-2.5-zset-hash-mysql.js` - MySQL 查询
- **目的**: 对比 Redis 和 MySQL 的分页查询性能
- **预期**: Redis 查询速度提升至 10 倍
## 单独运行某个测试
```bash
# 任务幂等性测试
k6 run benchmark/test-2.1-task-idempotent.js
# 点赞压测(方案A)
k6 run benchmark/test-2.3-like-benchmark-a.js
# 指定并发和持续时间
k6 run --vus 100 --duration 60s benchmark/test-2.3-like-benchmark-b.js
```
## 查看结果
测试结果保存在 `benchmark/results/` 目录:
- `*.log` - 控制台输出
- `*.json` - 详细 JSON 格式数据
- `benchmark_report_*.md` - 汇总报告
## 自定义测试参数
编辑对应的 `.js` 文件,修改 `options` 部分:
```javascript
export const options = {
vus: 100, // 虚拟用户数
duration: '30s', // 持续时间
stages: [ // 或使用阶段配置
{ duration: '10s', target: 50 },
{ duration: '20s', target: 100 },
{ duration: '10s', target: 0 },
],
thresholds: { // 性能阈值
http_req_duration: ['p(95)<500'], // 95% 请求 < 500ms
http_req_failed: ['rate<0.01'], // 失败率 < 1%
},
};
```
@@ -0,0 +1,177 @@
# 压测报告
生成时间: 2026-03-17 15:36:32
服务地址: http://localhost:8080
## 测试概览
| 测试项目 | 状态 | 结果文件 |
|---------|------|---------|
| 任务幂等性 | test-2.1-task-idempotent_20260317_153327.json |
| 消息幂等性 | test-2.2-message-idempotent_20260317_153327.json |
| 点赞方案A | |
| 点赞方案B | |
## 详细结果
### test-2.1-task-idempotent_20260317_153327
```
* concurrent_submit: 100 iterations shared among 100 VUs (maxDuration: 30s, gracefulStop: 30s)
http_req_duration
http_req_duration..............: avg=282.12ms min=143.72ms med=290.62ms max=398.7ms p(90)=371.3ms p(95)=383.34ms
http_reqs......................: 100 199.695727/s
iterations.....................: 100 199.695727/s
running (0m00.5s), 000/100 VUs, 100 complete and 0 interrupted iterations
```
### test-2.2-message-idempotent_20260317_153327
```
running (0m01.0s), 50/50 VUs, 0 complete and 0 interrupted iterations
running (0m02.0s), 50/50 VUs, 50 complete and 0 interrupted iterations
running (0m03.0s), 50/50 VUs, 100 complete and 0 interrupted iterations
running (0m04.0s), 50/50 VUs, 150 complete and 0 interrupted iterations
running (0m05.0s), 50/50 VUs, 200 complete and 0 interrupted iterations
running (0m06.0s), 50/50 VUs, 250 complete and 0 interrupted iterations
running (0m07.0s), 50/50 VUs, 300 complete and 0 interrupted iterations
running (0m08.0s), 50/50 VUs, 350 complete and 0 interrupted iterations
running (0m09.0s), 50/50 VUs, 400 complete and 0 interrupted iterations
running (0m10.0s), 50/50 VUs, 450 complete and 0 interrupted iterations
running (0m11.0s), 50/50 VUs, 500 complete and 0 interrupted iterations
running (0m12.0s), 50/50 VUs, 550 complete and 0 interrupted iterations
running (0m13.0s), 50/50 VUs, 600 complete and 0 interrupted iterations
running (0m14.0s), 50/50 VUs, 650 complete and 0 interrupted iterations
running (0m15.0s), 50/50 VUs, 700 complete and 0 interrupted iterations
running (0m16.0s), 50/50 VUs, 750 complete and 0 interrupted iterations
running (0m17.0s), 50/50 VUs, 800 complete and 0 interrupted iterations
running (0m18.0s), 50/50 VUs, 850 complete and 0 interrupted iterations
running (0m19.0s), 50/50 VUs, 900 complete and 0 interrupted iterations
running (0m20.0s), 50/50 VUs, 950 complete and 0 interrupted iterations
```
### test-2.3-like-benchmark-a_20260317_153327
```
running (0m01.0s), 005/100 VUs, 25 complete and 0 interrupted iterations
running (0m02.0s), 010/100 VUs, 98 complete and 0 interrupted iterations
running (0m03.0s), 015/100 VUs, 216 complete and 0 interrupted iterations
running (0m04.0s), 020/100 VUs, 381 complete and 0 interrupted iterations
running (0m05.0s), 025/100 VUs, 589 complete and 0 interrupted iterations
running (0m06.0s), 030/100 VUs, 850 complete and 0 interrupted iterations
running (0m07.0s), 035/100 VUs, 1151 complete and 0 interrupted iterations
running (0m08.0s), 040/100 VUs, 1491 complete and 0 interrupted iterations
running (0m09.0s), 045/100 VUs, 1843 complete and 0 interrupted iterations
running (0m10.0s), 049/100 VUs, 2200 complete and 0 interrupted iterations
running (0m11.0s), 052/100 VUs, 2554 complete and 0 interrupted iterations
running (0m12.0s), 054/100 VUs, 2903 complete and 0 interrupted iterations
running (0m13.0s), 057/100 VUs, 3251 complete and 0 interrupted iterations
running (0m14.0s), 059/100 VUs, 3594 complete and 0 interrupted iterations
running (0m15.0s), 062/100 VUs, 3922 complete and 0 interrupted iterations
running (0m16.0s), 064/100 VUs, 4248 complete and 0 interrupted iterations
running (0m17.0s), 067/100 VUs, 4567 complete and 0 interrupted iterations
running (0m18.0s), 069/100 VUs, 4904 complete and 0 interrupted iterations
running (0m19.0s), 072/100 VUs, 5258 complete and 0 interrupted iterations
running (0m20.0s), 074/100 VUs, 5608 complete and 0 interrupted iterations
```
### test-2.3-like-benchmark-b_20260317_153327
```
running (0m01.0s), 005/100 VUs, 25 complete and 0 interrupted iterations
running (0m02.0s), 010/100 VUs, 100 complete and 0 interrupted iterations
running (0m03.0s), 015/100 VUs, 225 complete and 0 interrupted iterations
running (0m04.0s), 020/100 VUs, 400 complete and 0 interrupted iterations
running (0m05.0s), 025/100 VUs, 622 complete and 0 interrupted iterations
running (0m06.0s), 030/100 VUs, 870 complete and 0 interrupted iterations
running (0m07.0s), 035/100 VUs, 1190 complete and 0 interrupted iterations
running (0m08.0s), 040/100 VUs, 1560 complete and 0 interrupted iterations
running (0m09.0s), 045/100 VUs, 1980 complete and 0 interrupted iterations
running (0m10.0s), 049/100 VUs, 2448 complete and 0 interrupted iterations
running (0m11.0s), 052/100 VUs, 2906 complete and 0 interrupted iterations
running (0m12.0s), 054/100 VUs, 3436 complete and 0 interrupted iterations
running (0m13.0s), 057/100 VUs, 3991 complete and 0 interrupted iterations
running (0m14.0s), 059/100 VUs, 4571 complete and 0 interrupted iterations
running (0m15.0s), 062/100 VUs, 5176 complete and 0 interrupted iterations
running (0m16.0s), 064/100 VUs, 5753 complete and 0 interrupted iterations
running (0m17.0s), 067/100 VUs, 6408 complete and 0 interrupted iterations
running (0m18.0s), 069/100 VUs, 7087 complete and 0 interrupted iterations
running (0m19.0s), 072/100 VUs, 7789 complete and 0 interrupted iterations
running (0m20.0s), 074/100 VUs, 8519 complete and 0 interrupted iterations
```
### test-2.4-cache-consistency_20260317_153327
```
running (0m01.0s), 50/50 VUs, 50 complete and 0 interrupted iterations
running (0m02.0s), 50/50 VUs, 150 complete and 0 interrupted iterations
running (0m03.0s), 50/50 VUs, 250 complete and 0 interrupted iterations
running (0m04.0s), 50/50 VUs, 350 complete and 0 interrupted iterations
running (0m05.0s), 50/50 VUs, 450 complete and 0 interrupted iterations
running (0m06.0s), 50/50 VUs, 550 complete and 0 interrupted iterations
running (0m07.0s), 50/50 VUs, 650 complete and 0 interrupted iterations
running (0m08.0s), 50/50 VUs, 750 complete and 0 interrupted iterations
running (0m09.0s), 50/50 VUs, 850 complete and 0 interrupted iterations
running (0m10.0s), 50/50 VUs, 950 complete and 0 interrupted iterations
running (0m11.0s), 50/50 VUs, 1050 complete and 0 interrupted iterations
running (0m12.0s), 50/50 VUs, 1150 complete and 0 interrupted iterations
running (0m13.0s), 50/50 VUs, 1250 complete and 0 interrupted iterations
running (0m14.0s), 50/50 VUs, 1350 complete and 0 interrupted iterations
running (0m15.0s), 50/50 VUs, 1450 complete and 0 interrupted iterations
running (0m16.0s), 50/50 VUs, 1550 complete and 0 interrupted iterations
running (0m17.0s), 50/50 VUs, 1650 complete and 0 interrupted iterations
running (0m18.0s), 50/50 VUs, 1750 complete and 0 interrupted iterations
running (0m19.0s), 50/50 VUs, 1850 complete and 0 interrupted iterations
running (0m20.0s), 50/50 VUs, 1950 complete and 0 interrupted iterations
```
### test-2.5-zset-hash-mysql_20260317_153327
```
running (01.0s), 10/10 VUs, 10 complete and 0 interrupted iterations
running (02.0s), 10/10 VUs, 30 complete and 0 interrupted iterations
running (03.0s), 10/10 VUs, 50 complete and 0 interrupted iterations
running (04.0s), 10/10 VUs, 70 complete and 0 interrupted iterations
running (05.0s), 10/10 VUs, 90 complete and 0 interrupted iterations
running (06.0s), 10/10 VUs, 110 complete and 0 interrupted iterations
running (07.0s), 10/10 VUs, 130 complete and 0 interrupted iterations
running (08.0s), 10/10 VUs, 150 complete and 0 interrupted iterations
running (09.0s), 10/10 VUs, 170 complete and 0 interrupted iterations
running (10.0s), 10/10 VUs, 190 complete and 0 interrupted iterations
running (11.0s), 10/10 VUs, 210 complete and 0 interrupted iterations
running (12.0s), 10/10 VUs, 230 complete and 0 interrupted iterations
running (13.0s), 10/10 VUs, 250 complete and 0 interrupted iterations
running (14.0s), 10/10 VUs, 270 complete and 0 interrupted iterations
running (15.0s), 10/10 VUs, 290 complete and 0 interrupted iterations
running (16.0s), 10/10 VUs, 310 complete and 0 interrupted iterations
running (17.0s), 10/10 VUs, 330 complete and 0 interrupted iterations
running (18.0s), 10/10 VUs, 350 complete and 0 interrupted iterations
running (19.0s), 10/10 VUs, 370 complete and 0 interrupted iterations
running (20.0s), 10/10 VUs, 390 complete and 0 interrupted iterations
```
### test-2.5-zset-hash-redis_20260317_153327
```
running (01.0s), 10/10 VUs, 10 complete and 0 interrupted iterations
running (02.0s), 10/10 VUs, 30 complete and 0 interrupted iterations
running (03.0s), 10/10 VUs, 50 complete and 0 interrupted iterations
running (04.0s), 10/10 VUs, 70 complete and 0 interrupted iterations
running (05.0s), 10/10 VUs, 90 complete and 0 interrupted iterations
running (06.0s), 10/10 VUs, 110 complete and 0 interrupted iterations
running (07.0s), 10/10 VUs, 130 complete and 0 interrupted iterations
running (08.0s), 10/10 VUs, 150 complete and 0 interrupted iterations
running (09.0s), 10/10 VUs, 170 complete and 0 interrupted iterations
running (10.0s), 10/10 VUs, 190 complete and 0 interrupted iterations
running (11.0s), 10/10 VUs, 210 complete and 0 interrupted iterations
running (12.0s), 10/10 VUs, 230 complete and 0 interrupted iterations
running (13.0s), 10/10 VUs, 250 complete and 0 interrupted iterations
running (14.0s), 10/10 VUs, 270 complete and 0 interrupted iterations
running (15.0s), 10/10 VUs, 290 complete and 0 interrupted iterations
running (16.0s), 10/10 VUs, 310 complete and 0 interrupted iterations
running (17.0s), 10/10 VUs, 330 complete and 0 interrupted iterations
running (18.0s), 10/10 VUs, 350 complete and 0 interrupted iterations
running (19.0s), 10/10 VUs, 370 complete and 0 interrupted iterations
running (20.0s), 10/10 VUs, 390 complete and 0 interrupted iterations
```
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,53 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.1-task-idempotent.js
output: json (./benchmark/results/test-2.1-task-idempotent_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 100 max VUs, 1m0s max duration (incl. graceful stop):
* concurrent_submit: 100 iterations shared among 100 VUs (maxDuration: 30s, gracefulStop: 30s)
█ THRESHOLDS
http_req_duration
✓ 'p(95)<5000' p(95)=383.34ms
http_req_failed
✓ 'rate<0.01' rate=0.00%
█ TOTAL RESULTS
checks_total.......: 200 399.391454/s
checks_succeeded...: 100.00% 200 out of 200
checks_failed......: 0.00% 0 out of 200
✓ status is 200
✓ has response body
HTTP
http_req_duration..............: avg=282.12ms min=143.72ms med=290.62ms max=398.7ms p(90)=371.3ms p(95)=383.34ms
{ expected_response:true }...: avg=282.12ms min=143.72ms med=290.62ms max=398.7ms p(90)=371.3ms p(95)=383.34ms
http_req_failed................: 0.00% 0 out of 100
http_reqs......................: 100 199.695727/s
EXECUTION
iteration_duration.............: avg=383.29ms min=244.09ms med=391.87ms max=500.58ms p(90)=472.18ms p(95)=484.55ms
iterations.....................: 100 199.695727/s
NETWORK
data_received..................: 44 kB 89 kB/s
data_sent......................: 18 kB 37 kB/s
running (0m00.5s), 000/100 VUs, 100 complete and 0 interrupted iterations
concurrent_submit ✓ [ 100% ] 100 VUs 00.5s/30s 100/100 shared iters
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,145 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.2-message-idempotent.js
output: json (./benchmark/results/test-2.2-message-idempotent_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 50 max VUs, 1m0s max duration (incl. graceful stop):
* default: 50 looping VUs for 30s (gracefulStop: 30s)
running (0m01.0s), 50/50 VUs, 0 complete and 0 interrupted iterations
default [ 3% ] 50 VUs 01.0s/30s
running (0m02.0s), 50/50 VUs, 50 complete and 0 interrupted iterations
default [ 7% ] 50 VUs 02.0s/30s
running (0m03.0s), 50/50 VUs, 100 complete and 0 interrupted iterations
default [ 10% ] 50 VUs 03.0s/30s
running (0m04.0s), 50/50 VUs, 150 complete and 0 interrupted iterations
default [ 13% ] 50 VUs 04.0s/30s
running (0m05.0s), 50/50 VUs, 200 complete and 0 interrupted iterations
default [ 17% ] 50 VUs 05.0s/30s
running (0m06.0s), 50/50 VUs, 250 complete and 0 interrupted iterations
default [ 20% ] 50 VUs 06.0s/30s
running (0m07.0s), 50/50 VUs, 300 complete and 0 interrupted iterations
default [ 23% ] 50 VUs 07.0s/30s
running (0m08.0s), 50/50 VUs, 350 complete and 0 interrupted iterations
default [ 27% ] 50 VUs 08.0s/30s
running (0m09.0s), 50/50 VUs, 400 complete and 0 interrupted iterations
default [ 30% ] 50 VUs 09.0s/30s
running (0m10.0s), 50/50 VUs, 450 complete and 0 interrupted iterations
default [ 33% ] 50 VUs 10.0s/30s
running (0m11.0s), 50/50 VUs, 500 complete and 0 interrupted iterations
default [ 37% ] 50 VUs 11.0s/30s
running (0m12.0s), 50/50 VUs, 550 complete and 0 interrupted iterations
default [ 40% ] 50 VUs 12.0s/30s
running (0m13.0s), 50/50 VUs, 600 complete and 0 interrupted iterations
default [ 43% ] 50 VUs 13.0s/30s
running (0m14.0s), 50/50 VUs, 650 complete and 0 interrupted iterations
default [ 47% ] 50 VUs 14.0s/30s
running (0m15.0s), 50/50 VUs, 700 complete and 0 interrupted iterations
default [ 50% ] 50 VUs 15.0s/30s
running (0m16.0s), 50/50 VUs, 750 complete and 0 interrupted iterations
default [ 53% ] 50 VUs 16.0s/30s
running (0m17.0s), 50/50 VUs, 800 complete and 0 interrupted iterations
default [ 57% ] 50 VUs 17.0s/30s
running (0m18.0s), 50/50 VUs, 850 complete and 0 interrupted iterations
default [ 60% ] 50 VUs 18.0s/30s
running (0m19.0s), 50/50 VUs, 900 complete and 0 interrupted iterations
default [ 63% ] 50 VUs 19.0s/30s
running (0m20.0s), 50/50 VUs, 950 complete and 0 interrupted iterations
default [ 67% ] 50 VUs 20.0s/30s
running (0m21.0s), 50/50 VUs, 1000 complete and 0 interrupted iterations
default [ 70% ] 50 VUs 21.0s/30s
running (0m22.0s), 50/50 VUs, 1050 complete and 0 interrupted iterations
default [ 73% ] 50 VUs 22.0s/30s
running (0m23.0s), 50/50 VUs, 1100 complete and 0 interrupted iterations
default [ 77% ] 50 VUs 23.0s/30s
running (0m24.0s), 50/50 VUs, 1150 complete and 0 interrupted iterations
default [ 80% ] 50 VUs 24.0s/30s
running (0m25.0s), 50/50 VUs, 1200 complete and 0 interrupted iterations
default [ 83% ] 50 VUs 25.0s/30s
running (0m26.0s), 50/50 VUs, 1250 complete and 0 interrupted iterations
default [ 87% ] 50 VUs 26.0s/30s
running (0m27.0s), 50/50 VUs, 1300 complete and 0 interrupted iterations
default [ 90% ] 50 VUs 27.0s/30s
running (0m28.0s), 50/50 VUs, 1350 complete and 0 interrupted iterations
default [ 93% ] 50 VUs 28.0s/30s
running (0m29.0s), 50/50 VUs, 1400 complete and 0 interrupted iterations
default [ 97% ] 50 VUs 29.0s/30s
running (0m30.0s), 50/50 VUs, 1450 complete and 0 interrupted iterations
default [ 100% ] 50 VUs 30.0s/30s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<500' p(95)=42.86ms
http_req_failed
✓ 'rate<0.01' rate=0.00%
█ TOTAL RESULTS
checks_total.......: 3000 98.088937/s
checks_succeeded...: 100.00% 3000 out of 3000
checks_failed......: 0.00% 0 out of 3000
✓ status is 200
✓ response time < 500ms
HTTP
http_req_duration..............: avg=18.27ms min=4.13ms med=8.68ms max=281.27ms p(90)=13.03ms p(95)=42.86ms
{ expected_response:true }...: avg=18.27ms min=4.13ms med=8.68ms max=281.27ms p(90)=13.03ms p(95)=42.86ms
http_req_failed................: 0.00% 0 out of 1500
http_reqs......................: 1500 49.044469/s
EXECUTION
iteration_duration.............: avg=1.01s min=1s med=1s max=1.28s p(90)=1.01s p(95)=1.04s
iterations.....................: 1500 49.044469/s
vus............................: 50 min=50 max=50
vus_max........................: 50 min=50 max=50
NETWORK
data_received..................: 689 kB 23 kB/s
data_sent......................: 269 kB 8.8 kB/s
running (0m30.6s), 00/50 VUs, 1500 complete and 0 interrupted iterations
default ✓ [ 100% ] 50 VUs 30s
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,172 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.3-like-benchmark-a.js
output: json (./benchmark/results/test-2.3-like-benchmark-a_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 100 max VUs, 1m10s max duration (incl. graceful stop):
* default: Up to 100 looping VUs for 40s over 3 stages (gracefulRampDown: 30s, gracefulStop: 30s)
running (0m01.0s), 005/100 VUs, 25 complete and 0 interrupted iterations
default [ 2% ] 005/100 VUs 01.0s/40.0s
running (0m02.0s), 010/100 VUs, 98 complete and 0 interrupted iterations
default [ 5% ] 010/100 VUs 02.0s/40.0s
running (0m03.0s), 015/100 VUs, 216 complete and 0 interrupted iterations
default [ 7% ] 015/100 VUs 03.0s/40.0s
running (0m04.0s), 020/100 VUs, 381 complete and 0 interrupted iterations
default [ 10% ] 020/100 VUs 04.0s/40.0s
running (0m05.0s), 025/100 VUs, 589 complete and 0 interrupted iterations
default [ 12% ] 025/100 VUs 05.0s/40.0s
running (0m06.0s), 030/100 VUs, 850 complete and 0 interrupted iterations
default [ 15% ] 030/100 VUs 06.0s/40.0s
running (0m07.0s), 035/100 VUs, 1151 complete and 0 interrupted iterations
default [ 17% ] 035/100 VUs 07.0s/40.0s
running (0m08.0s), 040/100 VUs, 1491 complete and 0 interrupted iterations
default [ 20% ] 040/100 VUs 08.0s/40.0s
running (0m09.0s), 045/100 VUs, 1843 complete and 0 interrupted iterations
default [ 22% ] 045/100 VUs 09.0s/40.0s
running (0m10.0s), 049/100 VUs, 2200 complete and 0 interrupted iterations
default [ 25% ] 049/100 VUs 10.0s/40.0s
running (0m11.0s), 052/100 VUs, 2554 complete and 0 interrupted iterations
default [ 27% ] 052/100 VUs 11.0s/40.0s
running (0m12.0s), 054/100 VUs, 2903 complete and 0 interrupted iterations
default [ 30% ] 054/100 VUs 12.0s/40.0s
running (0m13.0s), 057/100 VUs, 3251 complete and 0 interrupted iterations
default [ 32% ] 057/100 VUs 13.0s/40.0s
running (0m14.0s), 059/100 VUs, 3594 complete and 0 interrupted iterations
default [ 35% ] 059/100 VUs 14.0s/40.0s
running (0m15.0s), 062/100 VUs, 3922 complete and 0 interrupted iterations
default [ 37% ] 062/100 VUs 15.0s/40.0s
running (0m16.0s), 064/100 VUs, 4248 complete and 0 interrupted iterations
default [ 40% ] 064/100 VUs 16.0s/40.0s
running (0m17.0s), 067/100 VUs, 4567 complete and 0 interrupted iterations
default [ 42% ] 067/100 VUs 17.0s/40.0s
running (0m18.0s), 069/100 VUs, 4904 complete and 0 interrupted iterations
default [ 45% ] 069/100 VUs 18.0s/40.0s
running (0m19.0s), 072/100 VUs, 5258 complete and 0 interrupted iterations
default [ 47% ] 072/100 VUs 19.0s/40.0s
running (0m20.0s), 074/100 VUs, 5608 complete and 0 interrupted iterations
default [ 50% ] 074/100 VUs 20.0s/40.0s
running (0m21.0s), 077/100 VUs, 5954 complete and 0 interrupted iterations
default [ 52% ] 077/100 VUs 21.0s/40.0s
running (0m22.0s), 079/100 VUs, 6310 complete and 0 interrupted iterations
default [ 55% ] 079/100 VUs 22.0s/40.0s
running (0m23.0s), 082/100 VUs, 6663 complete and 0 interrupted iterations
default [ 57% ] 082/100 VUs 23.0s/40.0s
running (0m24.0s), 084/100 VUs, 7018 complete and 0 interrupted iterations
default [ 60% ] 084/100 VUs 24.0s/40.0s
running (0m25.0s), 087/100 VUs, 7372 complete and 0 interrupted iterations
default [ 62% ] 087/100 VUs 25.0s/40.0s
running (0m26.0s), 089/100 VUs, 7731 complete and 0 interrupted iterations
default [ 65% ] 089/100 VUs 26.0s/40.0s
running (0m27.0s), 092/100 VUs, 8071 complete and 0 interrupted iterations
default [ 67% ] 092/100 VUs 27.0s/40.0s
running (0m28.0s), 094/100 VUs, 8408 complete and 0 interrupted iterations
default [ 70% ] 094/100 VUs 28.0s/40.0s
running (0m29.0s), 097/100 VUs, 8736 complete and 0 interrupted iterations
default [ 72% ] 097/100 VUs 29.0s/40.0s
running (0m30.0s), 099/100 VUs, 9061 complete and 0 interrupted iterations
default [ 75% ] 099/100 VUs 30.0s/40.0s
running (0m31.0s), 091/100 VUs, 9403 complete and 0 interrupted iterations
default [ 77% ] 091/100 VUs 31.0s/40.0s
running (0m32.0s), 082/100 VUs, 9749 complete and 0 interrupted iterations
default [ 80% ] 082/100 VUs 32.0s/40.0s
running (0m33.0s), 072/100 VUs, 10092 complete and 0 interrupted iterations
default [ 82% ] 072/100 VUs 33.0s/40.0s
running (0m34.0s), 061/100 VUs, 10436 complete and 0 interrupted iterations
default [ 85% ] 061/100 VUs 34.0s/40.0s
running (0m35.0s), 052/100 VUs, 10786 complete and 0 interrupted iterations
default [ 87% ] 052/100 VUs 35.0s/40.0s
running (0m36.0s), 042/100 VUs, 11128 complete and 0 interrupted iterations
default [ 90% ] 042/100 VUs 36.0s/40.0s
running (0m37.0s), 031/100 VUs, 11463 complete and 0 interrupted iterations
default [ 92% ] 031/100 VUs 37.0s/40.0s
running (0m38.0s), 021/100 VUs, 11720 complete and 0 interrupted iterations
default [ 95% ] 021/100 VUs 38.0s/40.0s
running (0m39.0s), 014/100 VUs, 11849 complete and 0 interrupted iterations
default [ 97% ] 014/100 VUs 39.0s/40.0s
running (0m40.0s), 001/100 VUs, 11914 complete and 0 interrupted iterations
default [ 100% ] 001/100 VUs 40.0s/40.0s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<1000' p(95)=189.54ms
█ TOTAL RESULTS
checks_total.......: 23830 595.650955/s
checks_succeeded...: 100.00% 23830 out of 23830
checks_failed......: 0.00% 0 out of 23830
✓ status is 200
✓ response time < 500ms (Direct DB)
HTTP
http_req_duration..............: avg=88.64ms min=3.02ms med=96.41ms max=405.43ms p(90)=173.6ms p(95)=189.54ms
{ expected_response:true }...: avg=88.64ms min=3.02ms med=96.41ms max=405.43ms p(90)=173.6ms p(95)=189.54ms
http_req_failed................: 0.00% 0 out of 11915
http_reqs......................: 11915 297.825477/s
EXECUTION
iteration_duration.............: avg=189.21ms min=103.17ms med=196.95ms max=506.18ms p(90)=274.16ms p(95)=290.03ms
iterations.....................: 11915 297.825477/s
vus............................: 1 min=1 max=99
vus_max........................: 100 min=100 max=100
NETWORK
data_received..................: 2.0 MB 50 kB/s
data_sent......................: 1.3 MB 34 kB/s
running (0m40.0s), 000/100 VUs, 11915 complete and 0 interrupted iterations
default ✓ [ 100% ] 000/100 VUs 40s
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,172 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.3-like-benchmark-b.js
output: json (./benchmark/results/test-2.3-like-benchmark-b_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 100 max VUs, 1m10s max duration (incl. graceful stop):
* default: Up to 100 looping VUs for 40s over 3 stages (gracefulRampDown: 30s, gracefulStop: 30s)
running (0m01.0s), 005/100 VUs, 25 complete and 0 interrupted iterations
default [ 2% ] 005/100 VUs 01.0s/40.0s
running (0m02.0s), 010/100 VUs, 100 complete and 0 interrupted iterations
default [ 5% ] 010/100 VUs 02.0s/40.0s
running (0m03.0s), 015/100 VUs, 225 complete and 0 interrupted iterations
default [ 7% ] 015/100 VUs 03.0s/40.0s
running (0m04.0s), 020/100 VUs, 400 complete and 0 interrupted iterations
default [ 10% ] 020/100 VUs 04.0s/40.0s
running (0m05.0s), 025/100 VUs, 622 complete and 0 interrupted iterations
default [ 12% ] 025/100 VUs 05.0s/40.0s
running (0m06.0s), 030/100 VUs, 870 complete and 0 interrupted iterations
default [ 15% ] 030/100 VUs 06.0s/40.0s
running (0m07.0s), 035/100 VUs, 1190 complete and 0 interrupted iterations
default [ 17% ] 035/100 VUs 07.0s/40.0s
running (0m08.0s), 040/100 VUs, 1560 complete and 0 interrupted iterations
default [ 20% ] 040/100 VUs 08.0s/40.0s
running (0m09.0s), 045/100 VUs, 1980 complete and 0 interrupted iterations
default [ 22% ] 045/100 VUs 09.0s/40.0s
running (0m10.0s), 049/100 VUs, 2448 complete and 0 interrupted iterations
default [ 25% ] 049/100 VUs 10.0s/40.0s
running (0m11.0s), 052/100 VUs, 2906 complete and 0 interrupted iterations
default [ 27% ] 052/100 VUs 11.0s/40.0s
running (0m12.0s), 054/100 VUs, 3436 complete and 0 interrupted iterations
default [ 30% ] 054/100 VUs 12.0s/40.0s
running (0m13.0s), 057/100 VUs, 3991 complete and 0 interrupted iterations
default [ 32% ] 057/100 VUs 13.0s/40.0s
running (0m14.0s), 059/100 VUs, 4571 complete and 0 interrupted iterations
default [ 35% ] 059/100 VUs 14.0s/40.0s
running (0m15.0s), 062/100 VUs, 5176 complete and 0 interrupted iterations
default [ 37% ] 062/100 VUs 15.0s/40.0s
running (0m16.0s), 064/100 VUs, 5753 complete and 0 interrupted iterations
default [ 40% ] 064/100 VUs 16.0s/40.0s
running (0m17.0s), 067/100 VUs, 6408 complete and 0 interrupted iterations
default [ 42% ] 067/100 VUs 17.0s/40.0s
running (0m18.0s), 069/100 VUs, 7087 complete and 0 interrupted iterations
default [ 45% ] 069/100 VUs 18.0s/40.0s
running (0m19.0s), 072/100 VUs, 7789 complete and 0 interrupted iterations
default [ 47% ] 072/100 VUs 19.0s/40.0s
running (0m20.0s), 074/100 VUs, 8519 complete and 0 interrupted iterations
default [ 50% ] 074/100 VUs 20.0s/40.0s
running (0m21.0s), 077/100 VUs, 9213 complete and 0 interrupted iterations
default [ 52% ] 077/100 VUs 21.0s/40.0s
running (0m22.0s), 079/100 VUs, 9993 complete and 0 interrupted iterations
default [ 55% ] 079/100 VUs 22.0s/40.0s
running (0m23.0s), 082/100 VUs, 10794 complete and 0 interrupted iterations
default [ 57% ] 082/100 VUs 23.0s/40.0s
running (0m24.0s), 084/100 VUs, 11622 complete and 0 interrupted iterations
default [ 60% ] 084/100 VUs 24.0s/40.0s
running (0m25.0s), 087/100 VUs, 12475 complete and 0 interrupted iterations
default [ 62% ] 087/100 VUs 25.0s/40.0s
running (0m26.0s), 089/100 VUs, 13350 complete and 0 interrupted iterations
default [ 65% ] 089/100 VUs 26.0s/40.0s
running (0m27.0s), 092/100 VUs, 14190 complete and 0 interrupted iterations
default [ 67% ] 092/100 VUs 27.0s/40.0s
running (0m28.0s), 094/100 VUs, 15119 complete and 0 interrupted iterations
default [ 70% ] 094/100 VUs 28.0s/40.0s
running (0m29.0s), 097/100 VUs, 16074 complete and 0 interrupted iterations
default [ 72% ] 097/100 VUs 29.0s/40.0s
running (0m30.0s), 099/100 VUs, 17053 complete and 0 interrupted iterations
default [ 75% ] 099/100 VUs 30.0s/40.0s
running (0m31.0s), 091/100 VUs, 18004 complete and 0 interrupted iterations
default [ 77% ] 091/100 VUs 31.0s/40.0s
running (0m32.0s), 081/100 VUs, 18869 complete and 0 interrupted iterations
default [ 80% ] 081/100 VUs 32.0s/40.0s
running (0m33.0s), 071/100 VUs, 19564 complete and 0 interrupted iterations
default [ 82% ] 071/100 VUs 33.0s/40.0s
running (0m34.0s), 061/100 VUs, 20229 complete and 0 interrupted iterations
default [ 85% ] 061/100 VUs 34.0s/40.0s
running (0m35.0s), 051/100 VUs, 20794 complete and 0 interrupted iterations
default [ 87% ] 051/100 VUs 35.0s/40.0s
running (0m36.0s), 041/100 VUs, 21259 complete and 0 interrupted iterations
default [ 90% ] 041/100 VUs 36.0s/40.0s
running (0m37.0s), 031/100 VUs, 21624 complete and 0 interrupted iterations
default [ 92% ] 031/100 VUs 37.0s/40.0s
running (0m38.0s), 021/100 VUs, 21865 complete and 0 interrupted iterations
default [ 95% ] 021/100 VUs 38.0s/40.0s
running (0m39.0s), 011/100 VUs, 22030 complete and 0 interrupted iterations
default [ 97% ] 011/100 VUs 39.0s/40.0s
running (0m40.0s), 001/100 VUs, 22095 complete and 0 interrupted iterations
default [ 100% ] 001/100 VUs 40.0s/40.0s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<200' p(95)=2.17ms
█ TOTAL RESULTS
checks_total.......: 44192 1103.539485/s
checks_succeeded...: 100.00% 44192 out of 44192
checks_failed......: 0.00% 0 out of 44192
✓ status is 200
✓ response time < 100ms (Redis)
HTTP
http_req_duration..............: avg=1.23ms min=256.58µs med=1.17ms max=6.18ms p(90)=1.89ms p(95)=2.17ms
{ expected_response:true }...: avg=1.23ms min=256.58µs med=1.17ms max=6.18ms p(90)=1.89ms p(95)=2.17ms
http_req_failed................: 0.00% 0 out of 22096
http_reqs......................: 22096 551.769742/s
EXECUTION
iteration_duration.............: avg=101.78ms min=100.31ms med=101.78ms max=107.24ms p(90)=102.49ms p(95)=102.78ms
iterations.....................: 22096 551.769742/s
vus............................: 1 min=1 max=99
vus_max........................: 100 min=100 max=100
NETWORK
data_received..................: 3.7 MB 93 kB/s
data_sent......................: 2.3 MB 59 kB/s
running (0m40.0s), 000/100 VUs, 22096 complete and 0 interrupted iterations
default ✓ [ 100% ] 000/100 VUs 40s
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,143 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.4-cache-consistency.js
output: json (./benchmark/results/test-2.4-cache-consistency_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 50 max VUs, 1m0s max duration (incl. graceful stop):
* default: 50 looping VUs for 30s (gracefulStop: 30s)
running (0m01.0s), 50/50 VUs, 50 complete and 0 interrupted iterations
default [ 3% ] 50 VUs 01.0s/30s
running (0m02.0s), 50/50 VUs, 150 complete and 0 interrupted iterations
default [ 7% ] 50 VUs 02.0s/30s
running (0m03.0s), 50/50 VUs, 250 complete and 0 interrupted iterations
default [ 10% ] 50 VUs 03.0s/30s
running (0m04.0s), 50/50 VUs, 350 complete and 0 interrupted iterations
default [ 13% ] 50 VUs 04.0s/30s
running (0m05.0s), 50/50 VUs, 450 complete and 0 interrupted iterations
default [ 17% ] 50 VUs 05.0s/30s
running (0m06.0s), 50/50 VUs, 550 complete and 0 interrupted iterations
default [ 20% ] 50 VUs 06.0s/30s
running (0m07.0s), 50/50 VUs, 650 complete and 0 interrupted iterations
default [ 23% ] 50 VUs 07.0s/30s
running (0m08.0s), 50/50 VUs, 750 complete and 0 interrupted iterations
default [ 27% ] 50 VUs 08.0s/30s
running (0m09.0s), 50/50 VUs, 850 complete and 0 interrupted iterations
default [ 30% ] 50 VUs 09.0s/30s
running (0m10.0s), 50/50 VUs, 950 complete and 0 interrupted iterations
default [ 33% ] 50 VUs 10.0s/30s
running (0m11.0s), 50/50 VUs, 1050 complete and 0 interrupted iterations
default [ 37% ] 50 VUs 11.0s/30s
running (0m12.0s), 50/50 VUs, 1150 complete and 0 interrupted iterations
default [ 40% ] 50 VUs 12.0s/30s
running (0m13.0s), 50/50 VUs, 1250 complete and 0 interrupted iterations
default [ 43% ] 50 VUs 13.0s/30s
running (0m14.0s), 50/50 VUs, 1350 complete and 0 interrupted iterations
default [ 47% ] 50 VUs 14.0s/30s
running (0m15.0s), 50/50 VUs, 1450 complete and 0 interrupted iterations
default [ 50% ] 50 VUs 15.0s/30s
running (0m16.0s), 50/50 VUs, 1550 complete and 0 interrupted iterations
default [ 53% ] 50 VUs 16.0s/30s
running (0m17.0s), 50/50 VUs, 1650 complete and 0 interrupted iterations
default [ 57% ] 50 VUs 17.0s/30s
running (0m18.0s), 50/50 VUs, 1750 complete and 0 interrupted iterations
default [ 60% ] 50 VUs 18.0s/30s
running (0m19.0s), 50/50 VUs, 1850 complete and 0 interrupted iterations
default [ 63% ] 50 VUs 19.0s/30s
running (0m20.0s), 50/50 VUs, 1950 complete and 0 interrupted iterations
default [ 67% ] 50 VUs 20.0s/30s
running (0m21.0s), 50/50 VUs, 2050 complete and 0 interrupted iterations
default [ 70% ] 50 VUs 21.0s/30s
running (0m22.0s), 50/50 VUs, 2150 complete and 0 interrupted iterations
default [ 73% ] 50 VUs 22.0s/30s
running (0m23.0s), 50/50 VUs, 2250 complete and 0 interrupted iterations
default [ 77% ] 50 VUs 23.0s/30s
running (0m24.0s), 50/50 VUs, 2350 complete and 0 interrupted iterations
default [ 80% ] 50 VUs 24.0s/30s
running (0m25.0s), 50/50 VUs, 2450 complete and 0 interrupted iterations
default [ 83% ] 50 VUs 25.0s/30s
running (0m26.0s), 50/50 VUs, 2550 complete and 0 interrupted iterations
default [ 87% ] 50 VUs 26.0s/30s
running (0m27.0s), 50/50 VUs, 2650 complete and 0 interrupted iterations
default [ 90% ] 50 VUs 27.0s/30s
running (0m28.0s), 50/50 VUs, 2750 complete and 0 interrupted iterations
default [ 93% ] 50 VUs 28.0s/30s
running (0m29.0s), 50/50 VUs, 2850 complete and 0 interrupted iterations
default [ 97% ] 50 VUs 29.0s/30s
running (0m30.0s), 50/50 VUs, 2950 complete and 0 interrupted iterations
default [ 100% ] 50 VUs 30.0s/30s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<500' p(95)=8.2ms
█ TOTAL RESULTS
checks_total.......: 6000 198.26608/s
checks_succeeded...: 0.00% 0 out of 6000
checks_failed......: 100.00% 6000 out of 6000
✗ status is 200
↳ 0% — ✓ 0 / ✗ 3000
✗ has data
↳ 0% — ✓ 0 / ✗ 3000
HTTP
http_req_duration....: avg=3.46ms min=1.07ms med=2.69ms max=25.46ms p(90)=4.65ms p(95)=8.2ms
http_req_failed......: 100.00% 3000 out of 3000
http_reqs............: 3000 99.13304/s
EXECUTION
iteration_duration...: avg=504.16ms min=501.25ms med=503.41ms max=529.57ms p(90)=505.46ms p(95)=509.19ms
iterations...........: 3000 99.13304/s
vus..................: 50 min=50 max=50
vus_max..............: 50 min=50 max=50
NETWORK
data_received........: 606 kB 20 kB/s
data_sent............: 243 kB 8.0 kB/s
running (0m30.3s), 00/50 VUs, 3000 complete and 0 interrupted iterations
default ✓ [ 100% ] 50 VUs 30s
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,112 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.5-zset-hash-mysql.js
output: json (./benchmark/results/test-2.5-zset-hash-mysql_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 10 max VUs, 50s max duration (incl. graceful stop):
* default: 10 looping VUs for 20s (gracefulStop: 30s)
running (01.0s), 10/10 VUs, 10 complete and 0 interrupted iterations
default [ 5% ] 10 VUs 01.0s/20s
running (02.0s), 10/10 VUs, 30 complete and 0 interrupted iterations
default [ 10% ] 10 VUs 02.0s/20s
running (03.0s), 10/10 VUs, 50 complete and 0 interrupted iterations
default [ 15% ] 10 VUs 03.0s/20s
running (04.0s), 10/10 VUs, 70 complete and 0 interrupted iterations
default [ 20% ] 10 VUs 04.0s/20s
running (05.0s), 10/10 VUs, 90 complete and 0 interrupted iterations
default [ 25% ] 10 VUs 05.0s/20s
running (06.0s), 10/10 VUs, 110 complete and 0 interrupted iterations
default [ 30% ] 10 VUs 06.0s/20s
running (07.0s), 10/10 VUs, 130 complete and 0 interrupted iterations
default [ 35% ] 10 VUs 07.0s/20s
running (08.0s), 10/10 VUs, 150 complete and 0 interrupted iterations
default [ 40% ] 10 VUs 08.0s/20s
running (09.0s), 10/10 VUs, 170 complete and 0 interrupted iterations
default [ 45% ] 10 VUs 09.0s/20s
running (10.0s), 10/10 VUs, 190 complete and 0 interrupted iterations
default [ 50% ] 10 VUs 10.0s/20s
running (11.0s), 10/10 VUs, 210 complete and 0 interrupted iterations
default [ 55% ] 10 VUs 11.0s/20s
running (12.0s), 10/10 VUs, 230 complete and 0 interrupted iterations
default [ 60% ] 10 VUs 12.0s/20s
running (13.0s), 10/10 VUs, 250 complete and 0 interrupted iterations
default [ 65% ] 10 VUs 13.0s/20s
running (14.0s), 10/10 VUs, 270 complete and 0 interrupted iterations
default [ 70% ] 10 VUs 14.0s/20s
running (15.0s), 10/10 VUs, 290 complete and 0 interrupted iterations
default [ 75% ] 10 VUs 15.0s/20s
running (16.0s), 10/10 VUs, 310 complete and 0 interrupted iterations
default [ 80% ] 10 VUs 16.0s/20s
running (17.0s), 10/10 VUs, 330 complete and 0 interrupted iterations
default [ 85% ] 10 VUs 17.0s/20s
running (18.0s), 10/10 VUs, 350 complete and 0 interrupted iterations
default [ 90% ] 10 VUs 18.0s/20s
running (19.0s), 10/10 VUs, 370 complete and 0 interrupted iterations
default [ 95% ] 10 VUs 19.0s/20s
running (20.0s), 10/10 VUs, 390 complete and 0 interrupted iterations
default [ 100% ] 10 VUs 20.0s/20s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<200' p(95)=2.42ms
█ TOTAL RESULTS
checks_total.......: 800 39.771169/s
checks_succeeded...: 100.00% 800 out of 800
checks_failed......: 0.00% 0 out of 800
✓ status is 200
✓ response time < 200ms (MySQL)
HTTP
http_req_duration..............: avg=2.2ms min=548.05µs med=1.5ms max=27.47ms p(90)=2.09ms p(95)=2.42ms
{ expected_response:true }...: avg=2.2ms min=548.05µs med=1.5ms max=27.47ms p(90)=2.09ms p(95)=2.42ms
http_req_failed................: 0.00% 0 out of 400
http_reqs......................: 400 19.885584/s
EXECUTION
iteration_duration.............: avg=502.85ms min=500.7ms med=502.15ms max=529.09ms p(90)=502.97ms p(95)=503.78ms
iterations.....................: 400 19.885584/s
vus............................: 10 min=10 max=10
vus_max........................: 10 min=10 max=10
NETWORK
data_received..................: 67 kB 3.3 kB/s
data_sent......................: 41 kB 2.0 kB/s
running (20.1s), 00/10 VUs, 400 complete and 0 interrupted iterations
default ✓ [ 100% ] 10 VUs 20s
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,112 @@
/\ Grafana /‾‾/
/\ / \ |\ __ / /
/ \/ \ | |/ / / ‾‾\
/ \ | ( | (‾) |
/ __________ \ |_|\_\ \_____/
execution: local
script: ./benchmark/test-2.5-zset-hash-redis.js
output: json (./benchmark/results/test-2.5-zset-hash-redis_20260317_153327.json)
scenarios: (100.00%) 1 scenario, 10 max VUs, 50s max duration (incl. graceful stop):
* default: 10 looping VUs for 20s (gracefulStop: 30s)
running (01.0s), 10/10 VUs, 10 complete and 0 interrupted iterations
default [ 5% ] 10 VUs 01.0s/20s
running (02.0s), 10/10 VUs, 30 complete and 0 interrupted iterations
default [ 10% ] 10 VUs 02.0s/20s
running (03.0s), 10/10 VUs, 50 complete and 0 interrupted iterations
default [ 15% ] 10 VUs 03.0s/20s
running (04.0s), 10/10 VUs, 70 complete and 0 interrupted iterations
default [ 20% ] 10 VUs 04.0s/20s
running (05.0s), 10/10 VUs, 90 complete and 0 interrupted iterations
default [ 25% ] 10 VUs 05.0s/20s
running (06.0s), 10/10 VUs, 110 complete and 0 interrupted iterations
default [ 30% ] 10 VUs 06.0s/20s
running (07.0s), 10/10 VUs, 130 complete and 0 interrupted iterations
default [ 35% ] 10 VUs 07.0s/20s
running (08.0s), 10/10 VUs, 150 complete and 0 interrupted iterations
default [ 40% ] 10 VUs 08.0s/20s
running (09.0s), 10/10 VUs, 170 complete and 0 interrupted iterations
default [ 45% ] 10 VUs 09.0s/20s
running (10.0s), 10/10 VUs, 190 complete and 0 interrupted iterations
default [ 50% ] 10 VUs 10.0s/20s
running (11.0s), 10/10 VUs, 210 complete and 0 interrupted iterations
default [ 55% ] 10 VUs 11.0s/20s
running (12.0s), 10/10 VUs, 230 complete and 0 interrupted iterations
default [ 60% ] 10 VUs 12.0s/20s
running (13.0s), 10/10 VUs, 250 complete and 0 interrupted iterations
default [ 65% ] 10 VUs 13.0s/20s
running (14.0s), 10/10 VUs, 270 complete and 0 interrupted iterations
default [ 70% ] 10 VUs 14.0s/20s
running (15.0s), 10/10 VUs, 290 complete and 0 interrupted iterations
default [ 75% ] 10 VUs 15.0s/20s
running (16.0s), 10/10 VUs, 310 complete and 0 interrupted iterations
default [ 80% ] 10 VUs 16.0s/20s
running (17.0s), 10/10 VUs, 330 complete and 0 interrupted iterations
default [ 85% ] 10 VUs 17.0s/20s
running (18.0s), 10/10 VUs, 350 complete and 0 interrupted iterations
default [ 90% ] 10 VUs 18.0s/20s
running (19.0s), 10/10 VUs, 370 complete and 0 interrupted iterations
default [ 95% ] 10 VUs 19.0s/20s
running (20.0s), 10/10 VUs, 390 complete and 0 interrupted iterations
default [ 100% ] 10 VUs 20.0s/20s
█ THRESHOLDS
http_req_duration
✓ 'p(95)<50' p(95)=2.45ms
█ TOTAL RESULTS
checks_total.......: 800 39.814136/s
checks_succeeded...: 100.00% 800 out of 800
checks_failed......: 0.00% 0 out of 800
✓ status is 200
✓ response time < 50ms (Redis)
HTTP
http_req_duration..............: avg=1.54ms min=380.37µs med=1.06ms max=17.07ms p(90)=1.56ms p(95)=2.45ms
{ expected_response:true }...: avg=1.54ms min=380.37µs med=1.06ms max=17.07ms p(90)=1.56ms p(95)=2.45ms
http_req_failed................: 0.00% 0 out of 400
http_reqs......................: 400 19.907068/s
EXECUTION
iteration_duration.............: avg=502.31ms min=500.58ms med=501.98ms max=517.74ms p(90)=502.51ms p(95)=503.44ms
iterations.....................: 400 19.907068/s
vus............................: 10 min=10 max=10
vus_max........................: 10 min=10 max=10
NETWORK
data_received..................: 67 kB 3.3 kB/s
data_sent......................: 40 kB 2.0 kB/s
running (20.1s), 00/10 VUs, 400 complete and 0 interrupted iterations
default ✓ [ 100% ] 10 VUs 20s
+165
View File
@@ -0,0 +1,165 @@
#!/bin/bash
set -e
BASE_URL=${BASE_URL:-"http://localhost:8080"}
OUTPUT_DIR="./benchmark/results"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$OUTPUT_DIR"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
print_header() {
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}$1${NC}"
echo -e "${BLUE}========================================${NC}"
}
print_success() {
echo -e "${GREEN}✅ $1${NC}"
}
print_error() {
echo -e "${RED}❌ $1${NC}"
}
print_info() {
echo -e "${YELLOW}ℹ️ $1${NC}"
}
check_prerequisites() {
print_header "检查前置条件"
if ! command -v k6 &> /dev/null; then
print_error "k6 未安装"
echo "请安装 k6: https://k6.io/docs/getting-started/installation/"
echo "或运行: paru -S k6"
exit 1
fi
print_success "k6 已安装: $(k6 version)"
if ! curl -s "${BASE_URL}/actuator/health" | grep -q "UP"; then
print_error "服务未启动或无法访问: ${BASE_URL}"
exit 1
fi
print_success "服务正常运行: ${BASE_URL}"
print_info "准备测试数据..."
curl -s -X POST "${BASE_URL}/api/posts" \
-H "Content-Type: application/json" \
-d '{"content": "Benchmark Test Post"}' > /dev/null || true
echo ""
}
run_test() {
local test_name=$1
local test_file=$2
local output_file="${OUTPUT_DIR}/${test_name}_${TIMESTAMP}.json"
print_header "运行测试: $test_name"
BASE_URL="$BASE_URL" k6 run --out json="$output_file" "$test_file" 2>&1 | tee "${OUTPUT_DIR}/${test_name}_${TIMESTAMP}.log" || {
print_error "测试 $test_name 失败"
return 1
}
print_success "测试 $test_name 完成"
echo ""
}
verify_idempotency() {
print_header "验证幂等性结果"
local response=$(curl -s "${BASE_URL}/api/tasks/count")
local count=$(echo "$response" | jq -r '.data // 0' 2>/dev/null || echo "0")
if [ "$count" != "0" ] && [ "$count" != "null" ]; then
print_info "数据库任务记录数: $count"
if [ "$count" -eq 1 ]; then
print_success "幂等性验证通过:仅创建 1 条记录"
else
print_error "幂等性验证失败:创建了 $count 条记录"
fi
else
print_info "无法获取任务计数,请手动检查数据库"
fi
echo ""
}
generate_report() {
local report_file="${OUTPUT_DIR}/benchmark_report_${TIMESTAMP}.md"
print_header "生成测试报告"
cat > "$report_file" << EOF
# 压测报告
生成时间: $(date '+%Y-%m-%d %H:%M:%S')
服务地址: ${BASE_URL}
## 测试概览
| 测试项目 | 状态 | 结果文件 |
|---------|------|---------|
| 任务幂等性 | $(ls ${OUTPUT_DIR}/test-2.1*json 2>/dev/null | head -1 | xargs -I {} basename {} || echo "未运行") |
| 消息幂等性 | $(ls ${OUTPUT_DIR}/test-2.2*json 2>/dev/null | head -1 | xargs -I {} basename {} || echo "未运行") |
| 点赞方案A | $(ls ${OUTPUT_DIR}/test-2.3-a*json 2>/dev/null | head -1 | xargs -I {} basename {} || echo "未运行") |
| 点赞方案B | $(ls ${OUTPUT_DIR}/test-2.3-b*json 2>/dev/null | head -1 | xargs -I {} basename {} || echo "未运行") |
## 详细结果
EOF
for log_file in "${OUTPUT_DIR}"/*.log; do
if [ -f "$log_file" ]; then
echo "### $(basename "$log_file" .log)" >> "$report_file"
echo "" >> "$report_file"
echo '```' >> "$report_file"
grep -E "(http_req_duration|http_reqs|iterations|vus)" "$log_file" | head -20 >> "$report_file"
echo '```' >> "$report_file"
echo "" >> "$report_file"
fi
done
print_success "报告已生成: $report_file"
}
main() {
print_header "Spring Boot Demo 压测开始"
echo "时间: $(date)"
echo ""
check_prerequisites
print_info "开始执行压测..."
echo ""
run_test "test-2.1-task-idempotent" "./benchmark/test-2.1-task-idempotent.js" || true
verify_idempotency
run_test "test-2.2-message-idempotent" "./benchmark/test-2.2-message-idempotent.js" || true
run_test "test-2.3-like-benchmark-a" "./benchmark/test-2.3-like-benchmark-a.js" || true
run_test "test-2.3-like-benchmark-b" "./benchmark/test-2.3-like-benchmark-b.js" || true
run_test "test-2.4-cache-consistency" "./benchmark/test-2.4-cache-consistency.js" || true
run_test "test-2.5-zset-hash-redis" "./benchmark/test-2.5-zset-hash-redis.js" || true
run_test "test-2.5-zset-hash-mysql" "./benchmark/test-2.5-zset-hash-mysql.js" || true
generate_report
print_header "压测完成"
print_info "所有结果保存在: $OUTPUT_DIR"
}
main "$@"
+41
View File
@@ -0,0 +1,41 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
import { SharedArray } from 'k6/data';
export const options = {
scenarios: {
concurrent_submit: {
executor: 'shared-iterations',
vus: 100,
iterations: 100,
maxDuration: '30s',
},
},
thresholds: {
http_req_duration: ['p(95)<5000'],
http_req_failed: ['rate<0.01'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
const payload = JSON.stringify({
repoUrl: 'https://github.com/test/repo-benchmark'
});
const params = {
headers: {
'Content-Type': 'application/json',
},
};
const res = http.post(`${BASE_URL}/api/tasks`, payload, params);
check(res, {
'status is 200': (r) => r.status === 200,
'has response body': (r) => r.body.length > 0,
});
sleep(0.1);
}
+34
View File
@@ -0,0 +1,34 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 50,
duration: '30s',
thresholds: {
http_req_duration: ['p(95)<500'],
http_req_failed: ['rate<0.01'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
const payload = JSON.stringify({
repoUrl: `https://github.com/test/repo-${__VU}-${__ITER}`
});
const params = {
headers: {
'Content-Type': 'application/json',
},
};
const res = http.post(`${BASE_URL}/api/tasks`, payload, params);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
+27
View File
@@ -0,0 +1,27 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '10s', target: 50 },
{ duration: '20s', target: 100 },
{ duration: '10s', target: 0 },
],
thresholds: {
http_req_duration: ['p(95)<1000'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
const POST_ID = 1;
export default function () {
const res = http.post(`${BASE_URL}/api/posts/${POST_ID}/like/direct`);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms (Direct DB)': (r) => r.timings.duration < 500,
});
sleep(0.1);
}
+27
View File
@@ -0,0 +1,27 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '10s', target: 50 },
{ duration: '20s', target: 100 },
{ duration: '10s', target: 0 },
],
thresholds: {
http_req_duration: ['p(95)<200'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
const POST_ID = 1;
export default function () {
const res = http.post(`${BASE_URL}/api/posts/${POST_ID}/like`);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 100ms (Redis)': (r) => r.timings.duration < 100,
});
sleep(0.1);
}
+30
View File
@@ -0,0 +1,30 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 50,
duration: '30s',
thresholds: {
http_req_duration: ['p(95)<500'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
const res = http.get(`${BASE_URL}/api/posts/1`);
check(res, {
'status is 200': (r) => r.status === 200,
'has data': (r) => {
try {
const body = JSON.parse(r.body);
return body.code === 200 && body.data !== null;
} catch {
return false;
}
},
});
sleep(0.5);
}
+25
View File
@@ -0,0 +1,25 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '20s',
thresholds: {
http_req_duration: ['p(95)<200'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
const page = Math.floor(__ITER / 10);
const res = http.get(`${BASE_URL}/api/reports/hot/db?page=${page}&size=20`);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 200ms (MySQL)': (r) => r.timings.duration < 200,
});
sleep(0.5);
}
+25
View File
@@ -0,0 +1,25 @@
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '20s',
thresholds: {
http_req_duration: ['p(95)<50'],
},
};
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export default function () {
const page = Math.floor(__ITER / 10);
const res = http.get(`${BASE_URL}/api/reports/hot?page=${page}&size=20`);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 50ms (Redis)': (r) => r.timings.duration < 50,
});
sleep(0.5);
}
+30
View File
@@ -0,0 +1,30 @@
services:
mysql:
image: 'mysql:8.0'
environment:
- 'MYSQL_ROOT_PASSWORD=root'
- 'MYSQL_DATABASE=demo'
- 'MYSQL_USER=demo'
- 'MYSQL_PASSWORD=demo'
ports:
- '3306:3306'
volumes:
- mysql_data:/var/lib/mysql
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
rabbitmq:
image: 'rabbitmq:3.12-management'
environment:
- 'RABBITMQ_DEFAULT_PASS=secret'
- 'RABBITMQ_DEFAULT_USER=myuser'
ports:
- '5672:5672'
- '15672:15672'
redis:
image: 'redis:7.0-alpine'
ports:
- '6379:6379'
volumes:
mysql_data:
+415
View File
@@ -0,0 +1,415 @@
# Demo 项目编写文档
## 一、项目概述
### 目标
编写一个 Spring Boot Demo 项目,验证简历中提到的技术方案的实际效果,为面试提供真实数据支撑。
### 技术栈
- Java 17+
- Spring Boot 3.x
- MySQL 8.0
- Redis 7.0
- RabbitMQ 3.12
- Redisson(分布式锁)
- JMeter / wrk(压测工具)
---
## 二、需要验证的技术点
### 2.1 任务幂等提交
**简历描述**:
> 用户多次点击或网络重试会导致重复创建分析任务。设计幂等提交机制,通过 Redisson 分布式锁 + 幂等 key,保证相同仓库在同一时间只存在一个任务。
**需要实现**:
1. 提交任务接口:`POST /api/tasks`
2. 请求体:`{ "repoUrl": "https://github.com/xxx/yyy" }`
3. 幂等 key 生成:MD5(repoUrl)
4. Redisson 分布式锁:`lock = lock("task:submit:" + idempotencyKey)`
5. 数据库唯一约束:`analysis_job.idempotency_key UNIQUE`
**测试方案**:
- 使用 JMeter 并发 100 个请求,相同的 repoUrl
- 验证数据库只创建 1 条任务记录
**预期结果**:
```
并发请求数:100
成功创建任务数:1
返回已有任务数:99
```
---
### 2.2 消息消费幂等
**简历描述**:
> RabbitMQ 消息可能被重复投递。采用数据库唯一约束 + 乐观锁原子更新,重复消费时自动跳过,保证消息至少投递一次、最多处理一次。
**需要实现**:
1. RabbitMQ 消费者:`@RabbitListener(queues = "task.queue")`
2. 消息体:`{ "jobId": "xxx", "repoUrl": "xxx" }`
3. 消费逻辑:
```java
// 乐观锁认领任务
UPDATE analysis_job
SET status = 'running', claim_token = ?, heartbeat_time = NOW()
WHERE id = ? AND status = 'pending'
// 如果 update 影响 0 行,说明已被其他消费者处理,跳过
```
4. 手动 ACK 模式
**测试方案**:
- 向队列发送 10 条相同消息(相同 jobId)
- 验证任务只被处理 1 次
**预期结果**:
```
投递消息数:10
实际处理次数:1
跳过次数:9
```
---
### 2.3 点赞高并发优化
**简历描述**:
> 点赞是高频写操作,采用 Redis 计数 + 定时任务批量落库,写 QPS 从单机 500 提升至 5000+。
**需要实现**:
**方案 A:直接落库(对照组)**
```java
@PostMapping("/posts/{id}/like")
public void like(@PathVariable Long id) {
// 直接更新数据库
postMapper.incrementLikeCount(id);
}
```
**方案 B:Redis 计数 + 批量落库(优化组)**
```java
@PostMapping("/posts/{id}/like")
public void like(@PathVariable Long id) {
// Redis 计数
redisTemplate.opsForHash().increment("post:likes", id.toString(), 1);
}
// 定时任务每 5 秒批量落库
@Scheduled(fixedRate = 5000)
public void syncLikesToDb() {
Map<Object, Object> likes = redisTemplate.opsForHash().entries("post:likes");
// 批量更新数据库
for (Entry<Object, Object> entry : likes.entrySet()) {
postMapper.incrementLikeCount(Long.parseLong(entry.getKey().toString()),
Long.parseLong(entry.getValue().toString()));
}
// 清空 Redis 计数
redisTemplate.delete("post:likes");
}
```
**测试方案**:
- 使用 wrk 或 JMeter 进行压测
- 两种方案分别测试,记录 QPS
**预期结果**:
```
方案 A(直接落库):
- QPS: ~500
- 平均响应时间: ~20ms
方案 B(Redis + 批量落库):
- QPS: ~5000+
- 平均响应时间: ~2ms
性能提升: 10 倍
```
---
### 2.4 缓存一致性
**简历描述**:
> 采用"先更库、再删缓存"策略,配合延迟双删解决读写并发导致的脏数据问题。
**需要实现**:
**场景模拟**:
```java
// 更新帖子
@Transactional
public void updatePost(Long id, String content) {
// 1. 更新数据库
postMapper.updateContent(id, content);
// 2. 删除缓存
redisTemplate.delete("post:" + id);
// 3. 延迟双删(500ms 后再删一次)
executor.schedule(() -> {
redisTemplate.delete("post:" + id);
}, 500, TimeUnit.MILLISECONDS);
}
// 查询帖子
public Post getPost(Long id) {
// 1. 查缓存
Post cached = (Post) redisTemplate.opsForValue().get("post:" + id);
if (cached != null) {
return cached;
}
// 2. 查数据库
Post post = postMapper.findById(id);
// 3. 写缓存
redisTemplate.opsForValue().set("post:" + id, post, 1, TimeUnit.HOURS);
return post;
}
```
**测试方案**:
- 线程 A:循环更新帖子内容
- 线程 B:循环读取帖子内容
- 验证读取的内容与数据库一致
**预期结果**:
```
并发更新次数:1000
并发查询次数:10000
缓存与数据库不一致次数:0
```
---
### 2.5 ZSET + HASH 缓存结构
**简历描述**:
> 报告列表需要支持按热度/时间排序和分页查询。采用 ZSET + HASH 组合结构,查询复杂度 O(logN)。
**需要实现**:
**数据结构**:
```
ZSET: report:hot → score=热度分数, member=reportId
HASH: report:detail → field=reportId, value=报告JSON
```
**写入**:
```java
public void saveReport(Report report) {
// 存详情到 HASH
redisTemplate.opsForHash().put("report:detail", report.getId(), report);
// 存热度分数到 ZSET
redisTemplate.opsForZSet().add("report:hot", report.getId(), report.getHotScore());
}
```
**分页查询**:
```java
public List<Report> getHotReports(int page, int size) {
// 1. 从 ZSET 获取排序后的 ID(O(logN + M))
Set<Object> ids = redisTemplate.opsForZSet()
.reverseRange("report:hot", page * size, (page + 1) * size - 1);
// 2. 从 HASH 批量获取详情
List<Object> reports = redisTemplate.opsForHash()
.multiGet("report:detail", new ArrayList<>(ids));
return reports.stream()
.filter(Objects::nonNull)
.map(r -> (Report) r)
.collect(Collectors.toList());
}
```
**测试方案**:
- 插入 10000 条报告数据
- 对比 Redis 方案 vs MySQL 方案的查询耗时
**预期结果**:
```
数据量:10000 条
分页查询(page=100, size=20):
- MySQL 方案:~50ms
- Redis 方案:~5ms
性能提升:10 倍
```
---
## 三、项目结构
```
coderadar-demo/
├── src/main/java/com/example/demo/
│ ├── DemoApplication.java
│ ├── config/
│ │ ├── RedisConfig.java
│ │ ├── RabbitMQConfig.java
│ │ └── ScheduleConfig.java
│ ├── controller/
│ │ ├── TaskController.java # 任务提交
│ │ ├── PostController.java # 点赞
│ │ └── ReportController.java # 报告查询
│ ├── consumer/
│ │ └── TaskConsumer.java # RabbitMQ 消费者
│ ├── service/
│ │ ├── TaskService.java
│ │ ├── PostService.java
│ │ └── ReportService.java
│ ├── mapper/
│ │ ├── TaskMapper.java
│ │ ├── PostMapper.java
│ │ └── ReportMapper.java
│ └── entity/
│ ├── AnalysisJob.java
│ ├── Post.java
│ └── Report.java
├── src/main/resources/
│ ├── application.yml
│ └── schema.sql
├── jmeter/
│ ├── task-idempotent.jmx
│ ├── like-benchmark.jmx
│ └── cache-consistency.jmx
└── README.md
```
---
## 四、数据库表结构
```sql
-- 分析任务表
CREATE TABLE analysis_job (
id VARCHAR(36) PRIMARY KEY,
repo_url VARCHAR(500) NOT NULL,
idempotency_key VARCHAR(64) NOT NULL UNIQUE,
status VARCHAR(16) NOT NULL DEFAULT 'pending',
claim_token VARCHAR(32),
heartbeat_time DATETIME,
created_time DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 帖子表(用于点赞测试)
CREATE TABLE post (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200) NOT NULL,
content TEXT,
like_count INT DEFAULT 0,
created_time DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 报告表(用于缓存结构测试)
CREATE TABLE report (
id VARCHAR(36) PRIMARY KEY,
title VARCHAR(200) NOT NULL,
content TEXT,
hot_score INT DEFAULT 0,
created_time DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
---
## 五、测试脚本要求
### 5.1 幂等性测试
```bash
# JMeter 配置
线程数:100
循环次数:1
请求 URL:POST http://localhost:8080/api/tasks
请求体:{"repoUrl": "https://github.com/test/repo"}
```
**验证命令**:
```sql
SELECT COUNT(*) FROM analysis_job WHERE idempotency_key = MD5('https://github.com/test/repo');
-- 预期结果:1
```
### 5.2 点赞压测
```bash
# 方案 A 压测
wrk -t4 -c100 -d30s --latency \
-s post.lua \
http://localhost:8080/api/posts/1/like
# 方案 B 压测(同上,记录 QPS 对比)
```
### 5.3 输出报告格式
```
========== 压测报告 ==========
【任务幂等性测试】
并发请求数:100
创建任务数:1
幂等性验证:✅ 通过
【消息消费幂等测试】
投递消息数:10
处理次数:1
幂等性验证:✅ 通过
【点赞性能测试】
方案 A(直接落库):
- QPS:xxx
- 平均延迟:xx ms
方案 B(Redis + 批量落库):
- QPS:xxx
- 平均延迟:xx ms
性能提升:x 倍
【缓存一致性测试】
并发更新:1000 次
并发查询:10000 次
不一致次数:0
一致性验证:✅ 通过
【ZSET+HASH 查询测试】
数据量:10000 条
MySQL 查询:xx ms
Redis 查询:xx ms
性能提升:x 倍
```
---
## 六、注意事项
1. **环境准备**:
- MySQL 8.0、Redis 7.0、RabbitMQ 3.12 需要提前安装
- 建议使用 Docker Compose 一键启动
2. **数据准备**:
- 点赞测试前先插入测试帖子数据
- 报告查询测试前先插入 10000 条报告数据
3. **测试顺序**:
1. 先启动所有服务
2. 执行数据库初始化脚本
3. 逐个执行压测脚本
4. 收集结果写入报告
4. **简历数据取值**:
- 以实际测试结果为准
- 如果方案 B 的 QPS 达不到 5000,可以根据实际结果调整简历描述
Vendored
+295
View File
@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
Vendored
+189
View File
@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+133
View File
@@ -0,0 +1,133 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mcallzbl</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>demo</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>25</java.version>
<lombok.version>1.18.44</lombok.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.16</version>
</dependency>
<!-- Redisson for distributed lock -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-docker-compose</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,13 @@
package com.mcallzbl.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@@ -0,0 +1,9 @@
package com.mcallzbl.demo.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.mcallzbl.demo.mapper")
public class MyBatisPlusConfig {
}
@@ -0,0 +1,42 @@
package com.mcallzbl.demo.config;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
public static final String TASK_QUEUE = "task.queue";
@Bean
public Queue taskQueue() {
return new Queue(TASK_QUEUE, true);
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(jsonMessageConverter());
return template;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(jsonMessageConverter());
return factory;
}
}
@@ -0,0 +1,29 @@
package com.mcallzbl.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
StringRedisSerializer stringSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setValueSerializer(jsonSerializer);
template.setHashValueSerializer(jsonSerializer);
template.afterPropertiesSet();
return template;
}
}
@@ -0,0 +1,28 @@
package com.mcallzbl.demo.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissonConfig {
@Value("${spring.data.redis.host:localhost}")
private String redisHost;
@Value("${spring.data.redis.port:6379}")
private String redisPort;
@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + redisHost + ":" + redisPort)
.setConnectionPoolSize(20)
.setConnectionMinimumIdleSize(5);
return Redisson.create(config);
}
}
@@ -0,0 +1,9 @@
package com.mcallzbl.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class ScheduleConfig {
}
@@ -0,0 +1,61 @@
package com.mcallzbl.demo.consumer;
import com.mcallzbl.demo.dto.TaskMessage;
import com.mcallzbl.demo.mapper.AnalysisJobMapper;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@Component
@RequiredArgsConstructor
public class TaskConsumer {
private final AnalysisJobMapper analysisJobMapper;
@RabbitListener(queues = "task.queue")
public void handleTask(TaskMessage message, Channel channel,
@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
log.info("Received task message: jobId={}, repoUrl={}", message.getJobId(), message.getRepoUrl());
try {
String claimToken = UUID.randomUUID().toString();
int updated = analysisJobMapper.claimTask(message.getJobId(), claimToken);
if (updated == 0) {
log.info("Task already claimed by another consumer, skipping: jobId={}", message.getJobId());
channel.basicAck(deliveryTag, false);
return;
}
log.info("Successfully claimed task: jobId={}, claimToken={}", message.getJobId(), claimToken);
processTask(message);
channel.basicAck(deliveryTag, false);
log.info("Task processed successfully: jobId={}", message.getJobId());
} catch (Exception e) {
log.error("Error processing task: jobId={}", message.getJobId(), e);
channel.basicNack(deliveryTag, false, true);
}
}
private void processTask(TaskMessage message) {
try {
Thread.sleep(1000);
log.info("Task processing completed: jobId={}, repoUrl={}", message.getJobId(), message.getRepoUrl());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Task processing interrupted", e);
}
}
}
@@ -0,0 +1,46 @@
package com.mcallzbl.demo.controller;
import com.mcallzbl.demo.dto.ApiResponse;
import com.mcallzbl.demo.dto.PostUpdateRequest;
import com.mcallzbl.demo.entity.Post;
import com.mcallzbl.demo.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
@PostMapping
public ApiResponse<Post> createPost(@RequestBody PostUpdateRequest request) {
Post post = postService.createPost(request.getContent(), request.getContent());
return ApiResponse.success(post);
}
@PostMapping("/{id}/like/direct")
public ApiResponse<Void> likeDirect(@PathVariable Long id) {
postService.likeDirect(id);
return ApiResponse.success(null);
}
@PostMapping("/{id}/like")
public ApiResponse<Void> like(@PathVariable Long id) {
postService.likeWithRedis(id);
return ApiResponse.success(null);
}
@PutMapping("/{id}")
public ApiResponse<Void> updatePost(@PathVariable Long id, @RequestBody PostUpdateRequest request) {
postService.updatePost(id, request.getContent());
return ApiResponse.success(null);
}
@GetMapping("/{id}")
public ApiResponse<Post> getPost(@PathVariable Long id) {
Post post = postService.getPost(id);
return ApiResponse.success(post);
}
}
@@ -0,0 +1,45 @@
package com.mcallzbl.demo.controller;
import com.mcallzbl.demo.dto.ApiResponse;
import com.mcallzbl.demo.entity.Report;
import com.mcallzbl.demo.service.ReportService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/reports")
@RequiredArgsConstructor
public class ReportController {
private final ReportService reportService;
@PostMapping
public ApiResponse<Report> createReport(@RequestParam String title,
@RequestParam String content,
@RequestParam(defaultValue = "0") Integer hotScore) {
Report report = reportService.saveReport(title, content, hotScore);
return ApiResponse.success(report);
}
@GetMapping("/hot")
public ApiResponse<List<Report>> getHotReports(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
List<Report> reports = reportService.getHotReports(page, size);
return ApiResponse.success(reports);
}
@GetMapping("/hot/db")
public ApiResponse<List<Report>> getHotReportsFromDb(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
List<Report> reports = reportService.getHotReportsFromDb(page, size);
return ApiResponse.success(reports);
}
@PostMapping("/preload")
public ApiResponse<String> preloadReports(@RequestParam(defaultValue = "10000") int count) {
reportService.preloadReports(count);
return ApiResponse.success("Preloaded reports to cache");
}
}
@@ -0,0 +1,28 @@
package com.mcallzbl.demo.controller;
import com.mcallzbl.demo.dto.ApiResponse;
import com.mcallzbl.demo.dto.TaskSubmitRequest;
import com.mcallzbl.demo.entity.AnalysisJob;
import com.mcallzbl.demo.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/tasks")
@RequiredArgsConstructor
public class TaskController {
private final TaskService taskService;
@PostMapping
public ApiResponse<AnalysisJob> submitTask(@RequestBody TaskSubmitRequest request) {
AnalysisJob job = taskService.submitTask(request.getRepoUrl());
return ApiResponse.success(job);
}
@GetMapping("/count")
public ApiResponse<Long> countTasks() {
long count = taskService.countTasks();
return ApiResponse.success(count);
}
}
@@ -0,0 +1,26 @@
package com.mcallzbl.demo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResponse<T> {
private int code;
private String message;
private T data;
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(200, "success", data);
}
public static <T> ApiResponse<T> success(String message, T data) {
return new ApiResponse<>(200, message, data);
}
public static <T> ApiResponse<T> error(int code, String message) {
return new ApiResponse<>(code, message, null);
}
}
@@ -0,0 +1,8 @@
package com.mcallzbl.demo.dto;
import lombok.Data;
@Data
public class PostUpdateRequest {
private String content;
}
@@ -0,0 +1,13 @@
package com.mcallzbl.demo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TaskMessage {
private String jobId;
private String repoUrl;
}
@@ -0,0 +1,8 @@
package com.mcallzbl.demo.dto;
import lombok.Data;
@Data
public class TaskSubmitRequest {
private String repoUrl;
}
@@ -0,0 +1,29 @@
package com.mcallzbl.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("analysis_job")
public class AnalysisJob {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
private String repoUrl;
private String idempotencyKey;
private String status;
private String claimToken;
private LocalDateTime heartbeatTime;
private LocalDateTime createdTime;
private LocalDateTime updatedTime;
}
@@ -0,0 +1,28 @@
package com.mcallzbl.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@TableName("post")
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
private Long id;
private String title;
private String content;
private Integer likeCount;
private LocalDateTime createdTime;
private LocalDateTime updatedTime;
}
@@ -0,0 +1,26 @@
package com.mcallzbl.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@TableName("report")
public class Report implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_UUID)
private String id;
private String title;
private String content;
private Integer hotScore;
private LocalDateTime createdTime;
}
@@ -0,0 +1,18 @@
package com.mcallzbl.demo.exception;
import lombok.Getter;
@Getter
public class BusinessException extends RuntimeException {
private final int code;
public BusinessException(String message) {
super(message);
this.code = 400;
}
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
}
@@ -0,0 +1,27 @@
package com.mcallzbl.demo.exception;
import com.mcallzbl.demo.dto.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<Void> handleBusinessException(BusinessException e) {
log.warn("Business exception: {}", e.getMessage());
return ApiResponse.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiResponse<Void> handleException(Exception e) {
log.error("Unexpected exception", e);
return ApiResponse.error(500, "Internal server error");
}
}
@@ -0,0 +1,14 @@
package com.mcallzbl.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcallzbl.demo.entity.AnalysisJob;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface AnalysisJobMapper extends BaseMapper<AnalysisJob> {
@Update("UPDATE analysis_job SET status = 'running', claim_token = #{claimToken}, " +
"heartbeat_time = NOW(), updated_time = NOW() " +
"WHERE id = #{id} AND status = 'pending'")
int claimTask(@Param("id") String id, @Param("claimToken") String claimToken);
}
@@ -0,0 +1,16 @@
package com.mcallzbl.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcallzbl.demo.entity.Post;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface PostMapper extends BaseMapper<Post> {
@Update("UPDATE post SET like_count = like_count + #{increment}, " +
"updated_time = NOW() WHERE id = #{id}")
int incrementLikeCount(@Param("id") Long id, @Param("increment") Integer increment);
@Update("UPDATE post SET content = #{content}, updated_time = NOW() WHERE id = #{id}")
int updateContent(@Param("id") Long id, @Param("content") String content);
}
@@ -0,0 +1,7 @@
package com.mcallzbl.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcallzbl.demo.entity.Report;
public interface ReportMapper extends BaseMapper<Report> {
}
@@ -0,0 +1,118 @@
package com.mcallzbl.demo.service;
import com.mcallzbl.demo.entity.Post;
import com.mcallzbl.demo.exception.BusinessException;
import com.mcallzbl.demo.mapper.PostMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
private final PostMapper postMapper;
private final RedisTemplate<String, Object> redisTemplate;
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
private static final String POST_CACHE_KEY = "post:";
private static final String POST_LIKES_KEY = "post:likes";
public void likeDirect(Long postId) {
postMapper.incrementLikeCount(postId, 1);
log.debug("Direct like for post: {}", postId);
}
public void likeWithRedis(Long postId) {
redisTemplate.opsForHash().increment(POST_LIKES_KEY, postId.toString(), 1);
log.debug("Redis like for post: {}", postId);
}
@Scheduled(fixedRate = 5000)
public void syncLikesToDb() {
Map<Object, Object> likes = redisTemplate.opsForHash().entries(POST_LIKES_KEY);
if (likes.isEmpty()) {
return;
}
List<String> processedKeys = new ArrayList<>();
for (Map.Entry<Object, Object> entry : likes.entrySet()) {
try {
Long postId = Long.parseLong(entry.getKey().toString());
Integer count = Integer.parseInt(entry.getValue().toString());
postMapper.incrementLikeCount(postId, count);
processedKeys.add(entry.getKey().toString());
log.debug("Synced {} likes for post: {}", count, postId);
} catch (Exception e) {
log.error("Failed to sync likes for post: {}", entry.getKey(), e);
}
}
if (!processedKeys.isEmpty()) {
redisTemplate.opsForHash().delete(POST_LIKES_KEY, processedKeys.toArray());
log.info("Synced {} posts' likes to database", processedKeys.size());
}
}
@Transactional
public void updatePost(Long id, String content) {
postMapper.updateContent(id, content);
String cacheKey = POST_CACHE_KEY + id;
redisTemplate.delete(cacheKey);
executor.schedule(() -> {
redisTemplate.delete(cacheKey);
log.debug("Delayed double delete for post: {}", id);
}, 500, TimeUnit.MILLISECONDS);
log.info("Updated post: {}", id);
}
public Post getPost(Long id) {
String cacheKey = POST_CACHE_KEY + id;
Post cached = (Post) redisTemplate.opsForValue().get(cacheKey);
if (cached != null) {
log.debug("Cache hit for post: {}", id);
return cached;
}
Post post = postMapper.selectById(id);
if (post == null) {
throw new BusinessException(404, "Post not found: " + id);
}
redisTemplate.opsForValue().set(cacheKey, post, 1, TimeUnit.HOURS);
log.debug("Cache miss for post: {}, cached for 1 hour", id);
return post;
}
public Post createPost(String title, String content) {
Post post = new Post();
post.setTitle(title);
post.setContent(content);
post.setLikeCount(0);
postMapper.insert(post);
log.info("Created post: {}", post.getId());
return post;
}
}
@@ -0,0 +1,82 @@
package com.mcallzbl.demo.service;
import com.mcallzbl.demo.entity.Report;
import com.mcallzbl.demo.mapper.ReportMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ReportService {
private final ReportMapper reportMapper;
private final RedisTemplate<String, Object> redisTemplate;
private static final String REPORT_HOT_KEY = "report:hot";
private static final String REPORT_DETAIL_KEY = "report:detail";
public Report saveReport(String title, String content, Integer hotScore) {
Report report = new Report();
report.setTitle(title);
report.setContent(content);
report.setHotScore(hotScore);
reportMapper.insert(report);
saveToCache(report);
log.info("Created report: {} with hotScore: {}", report.getId(), hotScore);
return report;
}
public void saveToCache(Report report) {
redisTemplate.opsForHash().put(REPORT_DETAIL_KEY, report.getId(), report);
redisTemplate.opsForZSet().add(REPORT_HOT_KEY, report.getId(), report.getHotScore());
log.debug("Cached report: {}", report.getId());
}
public List<Report> getHotReports(int page, int size) {
long start = (long) page * size;
long end = start + size - 1;
Set<Object> ids = redisTemplate.opsForZSet().reverseRange(REPORT_HOT_KEY, start, end);
if (ids == null || ids.isEmpty()) {
return Collections.emptyList();
}
List<Object> reportObjects = redisTemplate.opsForHash()
.multiGet(REPORT_DETAIL_KEY, new ArrayList<>(ids));
return reportObjects.stream()
.filter(Objects::nonNull)
.map(obj -> (Report) obj)
.collect(Collectors.toList());
}
public List<Report> getHotReportsFromDb(int page, int size) {
int offset = page * size;
return reportMapper.selectList(null)
.stream()
.sorted((a, b) -> b.getHotScore().compareTo(a.getHotScore()))
.skip(offset)
.limit(size)
.collect(Collectors.toList());
}
public void preloadReports(int count) {
List<Report> reports = reportMapper.selectList(null);
for (Report report : reports) {
saveToCache(report);
}
log.info("Preloaded {} reports to cache", reports.size());
}
}
@@ -0,0 +1,99 @@
package com.mcallzbl.demo.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mcallzbl.demo.config.RabbitMQConfig;
import com.mcallzbl.demo.dto.TaskMessage;
import com.mcallzbl.demo.entity.AnalysisJob;
import com.mcallzbl.demo.mapper.AnalysisJobMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskService {
private final AnalysisJobMapper analysisJobMapper;
private final RedissonClient redissonClient;
private final RabbitTemplate rabbitTemplate;
public AnalysisJob submitTask(String repoUrl) {
String idempotencyKey = generateIdempotencyKey(repoUrl);
String lockKey = "task:submit:" + idempotencyKey;
RLock lock = redissonClient.getLock(lockKey);
try {
boolean acquired = lock.tryLock(10, 30, TimeUnit.SECONDS);
if (!acquired) {
throw new RuntimeException("Failed to acquire lock, please retry");
}
try {
LambdaQueryWrapper<AnalysisJob> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(AnalysisJob::getIdempotencyKey, idempotencyKey);
AnalysisJob existingJob = analysisJobMapper.selectOne(queryWrapper);
if (existingJob != null) {
log.info("Task already exists for repoUrl: {}, returning existing job: {}",
repoUrl, existingJob.getId());
return existingJob;
}
AnalysisJob newJob = new AnalysisJob();
newJob.setId(UUID.randomUUID().toString());
newJob.setRepoUrl(repoUrl);
newJob.setIdempotencyKey(idempotencyKey);
newJob.setStatus("pending");
newJob.setCreatedTime(LocalDateTime.now());
newJob.setUpdatedTime(LocalDateTime.now());
analysisJobMapper.insert(newJob);
log.info("Created new task: {} for repoUrl: {}", newJob.getId(), repoUrl);
TaskMessage message = new TaskMessage(newJob.getId(), repoUrl);
rabbitTemplate.convertAndSend(RabbitMQConfig.TASK_QUEUE, message);
log.info("Sent task message to queue: {}", newJob.getId());
return newJob;
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread interrupted while acquiring lock", e);
}
}
private String generateIdempotencyKey(String repoUrl) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(repoUrl.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("Failed to generate idempotency key", e);
}
}
public long countTasks() {
return analysisJobMapper.selectCount(null);
}
}
+63
View File
@@ -0,0 +1,63 @@
spring:
application:
name: demo
datasource:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=Asia/Shanghai
username: demo
password: demo
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
data:
redis:
host: localhost
port: 6379
timeout: 5000ms
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
rabbitmq:
host: localhost
port: 5672
username: myuser
password: secret
listener:
simple:
acknowledge-mode: manual
prefetch: 1
retry:
enabled: true
initial-interval: 1000
max-attempts: 3
multiplier: 2.0
flyway:
enabled: true
baseline-on-migrate: true
locations: classpath:db/migration
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: auto
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
mapper-locations: classpath*:/mapper/**/*.xml
logging:
level:
com.mcallzbl.demo: DEBUG
org.springframework.amqp: DEBUG
@@ -0,0 +1,28 @@
CREATE TABLE analysis_job (
id VARCHAR(36) PRIMARY KEY COMMENT '任务ID',
repo_url VARCHAR(500) NOT NULL COMMENT '仓库URL',
idempotency_key VARCHAR(64) NOT NULL UNIQUE COMMENT '幂等键',
status VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT '任务状态',
claim_token VARCHAR(32) COMMENT '认领令牌',
heartbeat_time DATETIME COMMENT '心跳时间',
created_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='分析任务表';
CREATE TABLE post (
id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '帖子ID',
title VARCHAR(200) NOT NULL COMMENT '标题',
content TEXT COMMENT '内容',
like_count INT DEFAULT 0 COMMENT '点赞数',
created_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='帖子表';
CREATE TABLE report (
id VARCHAR(36) PRIMARY KEY COMMENT '报告ID',
title VARCHAR(200) NOT NULL COMMENT '标题',
content TEXT COMMENT '内容',
hot_score INT DEFAULT 0 COMMENT '热度分数',
created_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='报告表';
@@ -0,0 +1,13 @@
package com.mcallzbl.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}