Skip to content

feat: 第二轮并发优化与测试 - #118

Merged
Uchkun07 merged 1 commit into
mainfrom
concurrence
Jul 31, 2026
Merged

Uchkun07 merged 1 commit into
mainfrom
concurrence

Conversation

@Uchkun07

@Uchkun07 Uchkun07 commented Apr 15, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added performance monitoring for slow database queries with configurable thresholds and reporting.
    • Added hot-key monitoring to track frequently accessed data with alerts and Top-N reporting.
    • Added automatic precomputation of recommendations based on user activity patterns.
  • Documentation

    • Added load testing report documenting system performance benchmarks and analysis.

@github-actions

github-actions Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

Image description CodeRabbit


Uplevel your code reviews with CodeRabbit Pro

CodeRabbit Pro

If you like this project, please support us by purchasing the Pro version. The Pro version has advanced context, superior noise reduction and several proprietary improvements compared to the open source version. Moreover, CodeRabbit Pro is free for open source projects.

@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request adds a comprehensive performance monitoring framework with three independent monitoring modules: slow SQL tracking via MyBatis interceptor, hot key detection at the cache layer, and recommendation precomputation for active users. All monitoring features are controlled by configuration-driven toggles in PerformanceProperties.

Changes

Cohort / File(s) Summary
Configuration Foundation
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java
Added nested Monitor class with configurable fields for recommendation precomputation (enabled, intervals, delays, windows, limits, pagination, guest inclusion), hot-key monitoring (enabled, sampling rate, threshold, alert step, TopN, report interval), and slow-SQL monitoring (enabled, threshold, sampling rate, TopN, aggregation interval, max SQL length).
Slow SQL Monitoring
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java, backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java
Added MyBatis interceptor to capture execution time for update/query operations and delegate to analysis service; SlowSqlAnalysisService normalizes SQL, applies probabilistic sampling, maintains per-statement statistics (count, latency, errors, p95 percentile), and logs periodically.
Hot Key Monitoring
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java, backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java
Added HotKeyMonitorService with per-minute counters, sampling, and scheduled Top-N reporting; integrated into CacheClient to record cache key accesses at three points before Redis operations.
Recommendation Precomputation
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java, backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java
Added RecommendationPrecomputeTask scheduled job that fetches active user IDs (with optional guest user), precomputes recommendations via IRecommendationService, and caches results; added selectActiveUserIds mapper method.
Documentation
docs/后端全接口JMeter压测报告-2026-04-15.md
Added comprehensive JMeter load testing report documenting test scope (120 test cases covering backend APIs excluding AI/route endpoints), execution methodology (two-phase: login setup then high-concurrency phase), results with response codes and timing analysis, and recommendations for authentication hardening and scenario-specific testing.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Cache as CacheClient
    participant HK as HotKeyMonitorService
    participant MyBatis as MyBatis Executor
    participant Interceptor as SlowSqlInterceptor
    participant SQLS as SlowSqlAnalysisService
    participant DB as Database
    participant Sched as Spring Scheduler

    rect rgba(100, 150, 255, 0.5)
    note over Cache,HK: Hot Key Monitoring Flow
    App->>Cache: queryWithPassThrough(key)
    Cache->>HK: recordAccess(key)
    HK->>HK: sample & increment per-minute counter
    Cache->>Cache: read from Redis
    end

    rect rgba(100, 255, 150, 0.5)
    note over MyBatis,SQLS: Slow SQL Monitoring Flow
    App->>MyBatis: execute query
    MyBatis->>Interceptor: intercept(invocation)
    Interceptor->>Interceptor: measure execution time
    Interceptor->>DB: proceed with query
    Interceptor->>SQLS: recordSlowSql (if slow & sampled)
    SQLS->>SQLS: normalize SQL, aggregate statistics
    DB-->>Interceptor: return results
    end

    rect rgba(255, 150, 100, 0.5)
    note over Sched,SQLS: Periodic Reporting
    Sched->>HK: reportTopHotKeys()
    HK->>HK: aggregate previous minute, compute Top-N
    Sched->>SQLS: report()
    SQLS->>SQLS: compute p95, sort by avg latency, log top entries
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Whisker-twitching, I monitor the hops,
Slow queries caught before they top,
Hot keys counted with careful paws,
Precomputed paths follow spring's applause, 🌱
Performance now has watchful eyes!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: adding performance monitoring infrastructure (hot-key monitoring, slow-SQL analysis, recommendation precomputation) and a load-testing report, all centered on concurrency optimization and testing.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch concurrence

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Image description CodeRabbit

Commits Files that changed from the base of the PR and between e08c292 and 13c0570 commits.
Files selected (8)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java (2)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java (1)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java (1)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java (1)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java (1)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java (1)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java (5)
  • docs/后端全接口JMeter压测报告-2026-04-15.md (1)
Files not summarized due to errors (8)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java (nothing obtained from openai)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java (nothing obtained from openai)
  • docs/后端全接口JMeter压测报告-2026-04-15.md (nothing obtained from openai)
Files not reviewed due to errors (8)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java (no response)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java (no response)
  • docs/后端全接口JMeter压测报告-2026-04-15.md (no response)
Review comments generated (0)
  • Review: 0
  • LGTM: 0

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (4)
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java (1)

32-35: 建议为预计算定时任务增加跨实例互斥。

当前 @Scheduled 在多副本部署时会每个实例都执行一次,可能导致重复回源与重复写缓存。建议增加分布式互斥(如基于 Redis 的任务锁)确保同一时刻仅一个实例执行。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`
around lines 32 - 35, The scheduled precompute method
(RecommendationPrecomputeTask.precompute) runs on every replica; add a
distributed mutex (e.g., Redis-backed lock via Redisson or Spring Integration's
LockRegistry) around the body so only one instance executes at a time: acquire a
lock with a unique key (e.g., "recommend:precompute:lock") and a sensible TTL
before running, if acquisition fails log and skip, run the existing logic only
while the lock is held, and always release the lock in a finally block; ensure
the lock acquisition is configurable and timed to avoid deadlocks and to honor
the existing `@Scheduled` timing.
docs/后端全接口JMeter压测报告-2026-04-15.md (1)

123-123: 建议优化标题措辞可读性。

Line 123 的“建议的下一步”可改为“下一步建议”或“建议如下”,读起来更自然。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/后端全接口JMeter压测报告-2026-04-15.md` at line 123, Replace the heading text
"建议的下一步(可继续由我落地)" with a more natural phrasing such as "下一步建议" or "建议如下" to
improve readability; locate the exact header string in the document and update
it, and also update any matching table-of-contents entries or internal links
that reference the original header text to keep references consistent.
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java (1)

40-46: 建议确认活跃用户查询的复合索引以避免高并发下扫描放大。

WHERE browse_time ... + GROUP BY user_id + ORDER BY MAX(browse_time) 在数据量大时容易退化。建议确认 user_browse_record 上是否有与该模式匹配的索引(如 (browse_time, user_id) 或 (user_id, browse_time),按实际执行计划选型)。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java`
around lines 40 - 46, The query in UserBrowseRecordMapper (the `@Select` that
selects ubr.user_id with WHERE browse_time, GROUP BY user_id and ORDER BY
MAX(ubr.browse_time)) can cause scan amplification under high concurrency;
ensure the user_browse_record table has an appropriate composite index (for
example (browse_time, user_id) or (user_id, browse_time) depending on the
optimizer) to support the WHERE + GROUP BY + ORDER BY pattern, add the chosen
index via your DB migration (or DDL) and validate with an EXPLAIN plan to pick
the best ordering (consider a covering index including browse_time to avoid full
scans).
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java (1)

68-129: 建议为 Monitor 参数增加统一边界校验,减少误配置风险。

当前多个字段依赖调用方零散 Math.max 兜底。建议在配置层统一约束(如采样率限定到 [0,1],间隔/TopN/limit 保证 >0),避免线上配置异常时行为不可预期。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java`
around lines 68 - 129, Add centralized validation inside the
PerformanceProperties.Monitor class (e.g., a public void validate() called from
a `@PostConstruct` in the enclosing config) that enforces safe bounds instead of
relying on callers to use Math.max: clamp hotKeySampleRate and slowSqlSampleRate
to [0,1]; ensure all interval/threshold/topN/limit/count fields
(recommendPrecomputeIntervalMs, recommendPrecomputeInitialDelayMs,
precomputeActiveWindowHours, precomputeUserLimit, precomputePageNum,
precomputePageSize, hotKeyThresholdPerMinute, hotKeyAlertStep, hotKeyTopN,
hotKeyReportIntervalMs, slowSqlThresholdMs, slowSqlReportTopN,
slowSqlReportIntervalMs, slowSqlSampleSqlMaxLen) are set to sensible minima (>0)
using Math.max/defaults; keep boolean flags unchanged; call this validate method
during bean initialization so misconfigured properties are corrected early and
predictably.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java`:
- Around line 55-83: The reportTopHotKeys() currently only reports reportMinute
= current - 1 and then removes all minuteCounters <= reportMinute, which loses
intermediate minutes when the scheduler interval > 60s; change
reportTopHotKeys() to collect all distinct minutes present in minuteCounters
that are < current (e.g.,
minuteCounters.values().stream().map(MinuteCounter::minute).filter(m -> m <
current).distinct().sorted()), then for each such minute produce the top N
HotKeySnapshot list and log them (reuse HotKeySnapshot and the existing logging
format), and finally remove entries with minute() <= maxReportedMinute (the
largest minute you reported) instead of just reportMinute. This preserves and
reports all missed minute windows when hotKeyReportIntervalMs > 60s.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`:
- Around line 130-142: The maxMs update and sampleSql assignment are ordered so
the comparison elapsedMs > maxMs.get() will almost never be true; change the
logic to detect when elapsedMs becomes the new max by capturing the previous or
new max from the atomic update (e.g., use maxMs.getAndAccumulate(elapsedMs,
Math::max) and compare elapsedMs to the returned previousMax, or use result =
maxMs.accumulateAndGet(elapsedMs, Math::max) and check if result == elapsedMs)
and only then set sampleSql = normalizedSql; keep the existing
latencySamples/LATENCY_SAMPLE_CAP handling and synchronized block unchanged.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`:
- Around line 48-50: The code in RecommendationPrecomputeTask unconditionally
adds 0L to targetUserIds when monitor.isIncludeGuestPrecompute() is true, which
can produce duplicate entries if 0 is already present; modify the logic that
builds targetUserIds (the collection used later for computing/writing caches) to
deduplicate before processing — e.g., convert targetUserIds to a Set or check
targetUserIds.contains(0L) before calling targetUserIds.add(0L) (or ensure you
collect into a Set initially) so the guest user id is added at most once and
downstream compute/cache write loops operate on a de-duplicated collection.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java`:
- Around line 92-94: 当前在 queryWithMutex 的重试 while 循环内每次都调用
hotKeyMonitorService.recordAccess(key),导致同一请求在锁竞争时被重复计数并放大热点统计;请将对
hotKeyMonitorService.recordAccess(key) 的调用移出 while 循环(例如在进入 loop
之前或函数开头只调用一次),保证每次 queryWithMutex 调用只记录一次访问,同时保留原有的
key、stringRedisTemplate.opsForValue().get(key) 和重试逻辑不变。

---

Nitpick comments:
In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java`:
- Around line 68-129: Add centralized validation inside the
PerformanceProperties.Monitor class (e.g., a public void validate() called from
a `@PostConstruct` in the enclosing config) that enforces safe bounds instead of
relying on callers to use Math.max: clamp hotKeySampleRate and slowSqlSampleRate
to [0,1]; ensure all interval/threshold/topN/limit/count fields
(recommendPrecomputeIntervalMs, recommendPrecomputeInitialDelayMs,
precomputeActiveWindowHours, precomputeUserLimit, precomputePageNum,
precomputePageSize, hotKeyThresholdPerMinute, hotKeyAlertStep, hotKeyTopN,
hotKeyReportIntervalMs, slowSqlThresholdMs, slowSqlReportTopN,
slowSqlReportIntervalMs, slowSqlSampleSqlMaxLen) are set to sensible minima (>0)
using Math.max/defaults; keep boolean flags unchanged; call this validate method
during bean initialization so misconfigured properties are corrected early and
predictably.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java`:
- Around line 40-46: The query in UserBrowseRecordMapper (the `@Select` that
selects ubr.user_id with WHERE browse_time, GROUP BY user_id and ORDER BY
MAX(ubr.browse_time)) can cause scan amplification under high concurrency;
ensure the user_browse_record table has an appropriate composite index (for
example (browse_time, user_id) or (user_id, browse_time) depending on the
optimizer) to support the WHERE + GROUP BY + ORDER BY pattern, add the chosen
index via your DB migration (or DDL) and validate with an EXPLAIN plan to pick
the best ordering (consider a covering index including browse_time to avoid full
scans).

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`:
- Around line 32-35: The scheduled precompute method
(RecommendationPrecomputeTask.precompute) runs on every replica; add a
distributed mutex (e.g., Redis-backed lock via Redisson or Spring Integration's
LockRegistry) around the body so only one instance executes at a time: acquire a
lock with a unique key (e.g., "recommend:precompute:lock") and a sensible TTL
before running, if acquisition fails log and skip, run the existing logic only
while the lock is held, and always release the lock in a finally block; ensure
the lock acquisition is configurable and timed to avoid deadlocks and to honor
the existing `@Scheduled` timing.

In `@docs/后端全接口JMeter压测报告-2026-04-15.md`:
- Line 123: Replace the heading text "建议的下一步(可继续由我落地)" with a more natural
phrasing such as "下一步建议" or "建议如下" to improve readability; locate the exact
header string in the document and update it, and also update any matching
table-of-contents entries or internal links that reference the original header
text to keep references consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 714716d3-832b-4df0-812a-4caab227c944

📥 Commits

Reviewing files that changed from the base of the PR and between e08c292 and 13c0570.

📒 Files selected for processing (8)
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java
  • backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java
  • docs/后端全接口JMeter压测报告-2026-04-15.md

Comment on lines +55 to +83
@Scheduled(
fixedDelayString = "${performance.monitor.hot-key-report-interval-ms:60000}",
initialDelayString = "${performance.monitor.hot-key-report-interval-ms:60000}")
public void reportTopHotKeys() {
PerformanceProperties.Monitor monitor = performanceProperties.getMonitor();
if (!monitor.isHotKeyEnabled()) {
return;
}

long current = currentMinute();
long reportMinute = current - 1;
int topN = Math.max(1, monitor.getHotKeyTopN());

List<HotKeySnapshot> topKeys = minuteCounters.values().stream()
.filter(counter -> counter.minute() == reportMinute)
.map(counter -> new HotKeySnapshot(counter.key(), counter.count().get()))
.sorted(Comparator.comparingLong(HotKeySnapshot::count).reversed())
.limit(topN)
.toList();

if (!topKeys.isEmpty()) {
log.warn("热点Key窗口报告 minute={}, topN={}", reportMinute, topKeys.size());
for (HotKeySnapshot snapshot : topKeys) {
log.warn("热点Key minute={} key={} hits={}", reportMinute, snapshot.key(), snapshot.count());
}
}

minuteCounters.entrySet().removeIf(entry -> entry.getValue().minute() <= reportMinute);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

热 Key 窗口报告在非 60s 调度下会丢失数据。

当前仅汇报 reportMinute=current-1,但 Line 82 会清理 <= reportMinute 的全部分钟数据。若 hotKeyReportIntervalMs 大于 60 秒,会跳过并丢弃中间分钟的统计。

修复方向(示意)
-        long current = currentMinute();
-        long reportMinute = current - 1;
-        int topN = Math.max(1, monitor.getHotKeyTopN());
-
-        List<HotKeySnapshot> topKeys = minuteCounters.values().stream()
-                .filter(counter -> counter.minute() == reportMinute)
-                ...
-
-        minuteCounters.entrySet().removeIf(entry -> entry.getValue().minute() <= reportMinute);
+        long current = currentMinute();
+        int topN = Math.max(1, monitor.getHotKeyTopN());
+
+        // 对 current 之前的每个 minute 分别出 TopN,再清理
+        Map<Long, List<HotKeySnapshot>> byMinute = minuteCounters.values().stream()
+                .filter(counter -> counter.minute() < current)
+                .collect(java.util.stream.Collectors.groupingBy(
+                        HotKeyCounter::minute,
+                        java.util.stream.Collectors.mapping(
+                                c -> new HotKeySnapshot(c.key(), c.count().get()),
+                                java.util.stream.Collectors.toList()
+                        )));
+
+        byMinute.forEach((minute, snapshots) -> {
+            List<HotKeySnapshot> topKeys = snapshots.stream()
+                    .sorted(Comparator.comparingLong(HotKeySnapshot::count).reversed())
+                    .limit(topN)
+                    .toList();
+            if (!topKeys.isEmpty()) {
+                log.warn("热点Key窗口报告 minute={}, topN={}", minute, topKeys.size());
+                topKeys.forEach(s -> log.warn("热点Key minute={} key={} hits={}", minute, s.key(), s.count()));
+            }
+        });
+
+        minuteCounters.entrySet().removeIf(entry -> entry.getValue().minute() < current);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java`
around lines 55 - 83, The reportTopHotKeys() currently only reports reportMinute
= current - 1 and then removes all minuteCounters <= reportMinute, which loses
intermediate minutes when the scheduler interval > 60s; change
reportTopHotKeys() to collect all distinct minutes present in minuteCounters
that are < current (e.g.,
minuteCounters.values().stream().map(MinuteCounter::minute).filter(m -> m <
current).distinct().sorted()), then for each such minute produce the top N
HotKeySnapshot list and log them (reuse HotKeySnapshot and the existing logging
format), and finally remove entries with minute() <= maxReportedMinute (the
largest minute you reported) instead of just reportMinute. This preserves and
reports all missed minute windows when hotKeyReportIntervalMs > 60s.

Comment on lines +130 to +142
maxMs.accumulateAndGet(elapsedMs, Math::max);
if (throwable != null) {
errorCount.increment();
}
synchronized (latencySamples) {
if (latencySamples.size() >= LATENCY_SAMPLE_CAP) {
latencySamples.remove(0);
}
latencySamples.add(elapsedMs);
}
if (elapsedMs > maxMs.get()) {
sampleSql = normalizedSql;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

最大耗时样本 SQL 更新条件存在逻辑错误。

Line 130 先更新了 maxMs,Line 140 再比较 elapsedMs > maxMs.get() 基本不会成立,导致 sampleSql 不会按“新最大耗时”更新。

建议修改
-            maxMs.accumulateAndGet(elapsedMs, Math::max);
+            long prevMax = maxMs.getAndAccumulate(elapsedMs, Math::max);
@@
-            if (elapsedMs > maxMs.get()) {
+            if (elapsedMs >= prevMax) {
                 sampleSql = normalizedSql;
             }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
maxMs.accumulateAndGet(elapsedMs, Math::max);
if (throwable != null) {
errorCount.increment();
}
synchronized (latencySamples) {
if (latencySamples.size() >= LATENCY_SAMPLE_CAP) {
latencySamples.remove(0);
}
latencySamples.add(elapsedMs);
}
if (elapsedMs > maxMs.get()) {
sampleSql = normalizedSql;
}
long prevMax = maxMs.getAndAccumulate(elapsedMs, Math::max);
if (throwable != null) {
errorCount.increment();
}
synchronized (latencySamples) {
if (latencySamples.size() >= LATENCY_SAMPLE_CAP) {
latencySamples.remove(0);
}
latencySamples.add(elapsedMs);
}
if (elapsedMs >= prevMax) {
sampleSql = normalizedSql;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`
around lines 130 - 142, The maxMs update and sampleSql assignment are ordered so
the comparison elapsedMs > maxMs.get() will almost never be true; change the
logic to detect when elapsedMs becomes the new max by capturing the previous or
new max from the atomic update (e.g., use maxMs.getAndAccumulate(elapsedMs,
Math::max) and compare elapsedMs to the returned previousMax, or use result =
maxMs.accumulateAndGet(elapsedMs, Math::max) and check if result == elapsedMs)
and only then set sampleSql = normalizedSql; keep the existing
latencySamples/LATENCY_SAMPLE_CAP handling and synchronized block unchanged.

Comment on lines +48 to +50
if (monitor.isIncludeGuestPrecompute()) {
targetUserIds.add(0L);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

guest 用户可能被重复加入目标列表。

Line 49 直接 add(0L),若活跃用户结果本身包含 0(或后续数据演进引入),会重复计算与重复写缓存。建议去重后再执行。

建议修改
-        List<Long> targetUserIds = new ArrayList<>(activeUserIds == null ? List.of() : activeUserIds);
-        if (monitor.isIncludeGuestPrecompute()) {
-            targetUserIds.add(0L);
-        }
+        List<Long> targetUserIds = new ArrayList<>(activeUserIds == null ? List.of() : activeUserIds);
+        if (monitor.isIncludeGuestPrecompute() && !targetUserIds.contains(0L)) {
+            targetUserIds.add(0L);
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`
around lines 48 - 50, The code in RecommendationPrecomputeTask unconditionally
adds 0L to targetUserIds when monitor.isIncludeGuestPrecompute() is true, which
can produce duplicate entries if 0 is already present; modify the logic that
builds targetUserIds (the collection used later for computing/writing caches) to
deduplicate before processing — e.g., convert targetUserIds to a Set or check
targetUserIds.contains(0L) before calling targetUserIds.add(0L) (or ensure you
collect into a Set initially) so the guest user id is added at most once and
downstream compute/cache write loops operate on a de-duplicated collection.

Comment on lines 92 to 94
while (true) {
hotKeyMonitorService.recordAccess(key);
String cacheVal = stringRedisTemplate.opsForValue().get(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

互斥重试路径会放大热点统计计数。

Line 93 在 while 重试里每轮都记一次访问;锁竞争越激烈,同一真实请求被重复计数越多,热点监控会偏高。建议改为每次 queryWithMutex 调用只记录一次。

建议修改
-            while (true) {
-                hotKeyMonitorService.recordAccess(key);
+            hotKeyMonitorService.recordAccess(key);
+            while (true) {
                 String cacheVal = stringRedisTemplate.opsForValue().get(key);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while (true) {
hotKeyMonitorService.recordAccess(key);
String cacheVal = stringRedisTemplate.opsForValue().get(key);
hotKeyMonitorService.recordAccess(key);
while (true) {
String cacheVal = stringRedisTemplate.opsForValue().get(key);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java`
around lines 92 - 94, 当前在 queryWithMutex 的重试 while 循环内每次都调用
hotKeyMonitorService.recordAccess(key),导致同一请求在锁竞争时被重复计数并放大热点统计;请将对
hotKeyMonitorService.recordAccess(key) 的调用移出 while 循环(例如在进入 loop
之前或函数开头只调用一次),保证每次 queryWithMutex 调用只记录一次访问,同时保留原有的
key、stringRedisTemplate.opsForValue().get(key) 和重试逻辑不变。

@Uchkun07
Uchkun07 merged commit 89152c8 into main Jul 31, 2026
7 checks passed
@Uchkun07
Uchkun07 deleted the concurrence branch July 31, 2026 00:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant