Skip to content

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

Closed
Uchkun07 wants to merge 3 commits into
mainfrom
newindex
Closed

Uchkun07 wants to merge 3 commits into
mainfrom
newindex

Conversation

@Uchkun07

@Uchkun07 Uchkun07 commented May 15, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added performance monitoring for slow-running database queries with configurable thresholds and sampling.
    • Added hot-key detection to identify and track frequently accessed data.
    • Added automatic precomputation and caching of recommendations for active users.
    • Enhanced attraction count tracking in city views.
  • Chores

    • Updated .gitignore to exclude documentation directory.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 15, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds comprehensive performance monitoring and cache optimization to the travel system. Configuration enables monitoring for slow SQL and hot cache keys. MyBatis interception captures slow queries; analysis service normalizes, aggregates, and reports with p95 latency. Hot key monitoring tracks cache access patterns. Recommendation precomputation warms cache for active users. City endpoints compute attraction counts from live data. .gitignore is updated.

Changes

Performance Monitoring and Cache Optimization

Layer / File(s) Summary
Monitoring configuration foundation
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.java
New Monitor nested class in PerformanceProperties centralizes configuration for slow-SQL and hot-key monitoring thresholds, sampling rates, reporting intervals, and recommendation precomputation scheduling.
Slow SQL monitoring infrastructure
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.java, backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java
SlowSqlInterceptor wraps MyBatis executor methods, measures elapsed time, applies threshold and sampling gates, and reports slow SQL to analysis service. SlowSqlAnalysisService normalizes SQL, aggregates by fingerprint with bounded latency samples, and periodically logs warnings with p95, max, and error-rate metrics.
Hot key monitoring service
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java
Tracks per-minute cache key access counters with probabilistic sampling, threshold-based warning alarms, and scheduled reporting of top-N hot keys ranked by frequency.
Cache client integration with hot key monitoring
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java
Records cache key access across pass-through, mutex, and filter-key paths to feed hot-key monitoring with real usage data.
Active user retrieval and recommendation cache warming
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java, backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java
UserBrowseRecordMapper queries active users by recent browse history; scheduled RecommendationPrecomputeTask precomputes home recommendations for those users and caches results with configured TTL and jitter.
City response enrichment with live attraction counts
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.java
getCityCards now injects AttractionMapper and replaces denormalized entity counts with a live grouped query filtered by enabled and audited status.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • Uchkun07/travel-system#101: Both PRs modify city-list and attraction-count data retrieval in CityServiceImpl#getCityCards(...), impacting the city response schema and caching patterns.

Poem

A rabbit hops through metrics deep,
Watching slow queries in a heap,
Hot keys dance in cached delight,
Prewarmed homes shine ever bright,
Performance now in perfect sight! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title in Chinese translates to 'feat: second round concurrency optimization and testing', which accurately reflects the main changes introducing performance monitoring, slow SQL tracking, hot key monitoring, and recommendation precomputation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 newindex

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java (1)

93-105: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

互斥重试循环内重复 recordAccess 会放大热键计数。

当前每次抢锁失败重试都会记一次访问,统计值会偏离真实请求量并导致误告警。建议把 recordAccess(key) 挪到 while 外层(每次 API 调用仅记录一次)。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java`
around lines 93 - 105, The hot-key access is being recorded inside the retry
loop, so hotKeyMonitorService.recordAccess(key) is called on every retry and
inflates counts; move the single call to hotKeyMonitorService.recordAccess(key)
out of the retry loop so it is invoked once per API call (i.e. call it before
entering the while/retry that uses tryLock(lockKey), sleepBriefly(), and cache
lookup logic), ensuring the rest of the loop (tryLock, cache get, deserialize,
sleepBriefly) remains unchanged.
🧹 Nitpick comments (4)
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java (1)

67-69: 🏗️ Heavy lift

statMap.clear()会丢失并发写入的慢SQL样本。

snapshots 生成后到 clear() 之间仍可能有新数据写入,这部分会被直接清空,造成统计窗口数据丢失。建议按快照键定向移除(或使用双缓冲 map 轮转)避免漏记。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`
around lines 67 - 69, 在 SlowSqlAnalysisService 中直接调用 statMap.clear() 会丢失在生成
snapshots(或读取 fingerprintCount)后并发写入的新样本;请改为先基于 statMap 做一个快照副本(例如取 keySet 或构造新的
Map 引用),然后只定向移除快照中的键(通过循环调用 statMap.remove(key) 或使用并发安全的替换/轮换双缓冲策略替换整个 map
引用),确保 fingerprintCount 仍基于快照计算且不会清掉并发写入的数据。
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.java (2)

175-195: ⚡ Quick win

Consider caching per-city attraction counts to avoid per-request aggregate query.

getCityCards is a customer-facing listing endpoint. Replacing the denormalized City.attractionCount with a live grouped aggregate adds one extra DB roundtrip on every page request, and the aggregate filters (status=1, audit_status=2) won't typically change between requests. Given this PR's broader push for cache prewarming and hot-key monitoring, the per-city attraction count is a strong candidate for a short-TTL cached map (e.g., refreshed on attraction status/audit changes, or simply a 1–5 min TTL behind CacheClient). Make sure attraction(city_id, status, audit_status) is also indexed so the grouped count stays cheap during cache misses.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.java`
around lines 175 - 195, The current getCityCards implementation in
CityServiceImpl builds attractionCountMap by running a grouped aggregate via
attractionMapper.selectMaps on every request; instead, cache per-city attraction
counts (the map keyed by city_id used to fill City.attractionCount) behind the
existing CacheClient with a short TTL (1–5 min) and/or invalidate/update the
cached map when Attraction entities change (status or audit_status updates) so
requests read the cached map first and only query the DB on cache miss; keep the
same filtering (status=1, audit_status=2) and ensure attraction(city_id, status,
audit_status) is indexed, and update code paths around attractionCountMap and
attractionMapper to read from the cache and fall back to the grouped aggregate
only when needed.

186-194: 💤 Low value

Optional: Make column-key lookup case-insensitive if considering database portability.

The code currently relies on row.get("city_id") and row.get("attraction_count") receiving lowercase column labels. This works correctly with MySQL (your configured database), which preserves label case as written in SQL. However, if you ever migrate to a database that uppercases column labels (e.g., Oracle, H2 default), both lookups would silently return null and default to 0 for all cities.

For defensive coding without depending on driver behavior, you can use a case-insensitive key lookup:

Optional defensive approach
             List<Map<String, Object>> countRows = attractionMapper.selectMaps(countWrapper);
             for (Map<String, Object> row : countRows) {
-                Object cityId = row.get("city_id");
-                Object count = row.get("attraction_count");
+                Map<String, Object> ci = new java.util.TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+                ci.putAll(row);
+                Object cityId = ci.get("city_id");
+                Object count = ci.get("attraction_count");
                 if (cityId instanceof Number) {
                     int parsedCount = count instanceof Number ? ((Number) count).intValue() : 0;
                     attractionCountMap.put(((Number) cityId).intValue(), parsedCount);
                 }
             }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.java`
around lines 186 - 194, The loop in CityServiceImpl reading
attractionMapper.selectMaps(countWrapper) assumes column labels "city_id" and
"attraction_count" are lower-case; to make this robust across DB drivers,
perform a case-insensitive lookup when extracting values from each
Map<String,Object> (countRows). For example, create or inline a small helper
that given a Map and a target key (e.g., "city_id" or "attraction_count") scans
the map keys and returns the value for the matching key ignoring case, then use
that value to populate attractionCountMap; update the loop that references
countRows, the cityId/count extraction logic, and ensure parsedCount handling
remains the same.
backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java (1)

48-50: 💤 Low value

Simplify guest user handling.

The code adds 0L to represent the guest user (line 49), then immediately converts it to null in the loop (line 61: userId <= 0 ? null). This indirection adds complexity. Consider either adding null directly to targetUserIds or processing the guest user separately outside the loop for clarity.

♻️ Clearer alternative
 List<Long> targetUserIds = new ArrayList<>(activeUserIds == null ? List.of() : activeUserIds);
-if (monitor.isIncludeGuestPrecompute()) {
-    targetUserIds.add(0L);
-}
+// Guest user will be added separately below

 if (targetUserIds.isEmpty()) {
+    if (!monitor.isIncludeGuestPrecompute()) {
+        return;
+    }
-    return;
 }

 long start = System.currentTimeMillis();
 int success = 0;
 int failed = 0;

+// Precompute for guest user if enabled
+if (monitor.isIncludeGuestPrecompute()) {
+    precomputeForUser(null, pageNum, pageSize, ...);
+}
+
 for (Long userId : targetUserIds) {
-    Long actualUserId = (userId == null || userId <= 0) ? null : userId;
+    precomputeForUser(userId, pageNum, pageSize, ...);
-    try {
-        ...

Or simply add null directly:

 if (monitor.isIncludeGuestPrecompute()) {
-    targetUserIds.add(0L);
+    targetUserIds.add(null);
 }

Also applies to: 61-61

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`
around lines 48 - 50, Replace the sentinel 0L guest marker with a real null in
targetUserIds to remove the needless indirection: when
monitor.isIncludeGuestPrecompute() is true, add null (not 0L) to targetUserIds,
and update the processing loop in RecommendationPrecomputeTask (where
targetUserIds are iterated and currently checked with userId <= 0 ? null) to
treat a null userId as the guest case directly (or alternatively handle the
guest user in a separate branch outside the targetUserIds loop); adjust any
null/primitive checks accordingly so no 0L sentinel is used.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.gitignore:
- Around line 1-2: The .gitignore currently contains unanchored patterns
"node_modules" and "docs" which will ignore any matching folders at any depth;
change these to anchored or scoped entries (e.g. prefix with a leading slash
like "/docs" or "/node_modules" if you only mean the repo root, or replace with
per-subproject paths like "frontend/node_modules/" and
"backend/.../target/docs/") so only the intended root/generated directories are
ignored and not nested documentation or node_modules folders in subprojects.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java`:
- Around line 47-48: The method selectActiveUserIds in UserBrowseRecordMapper
currently uses nullable Integer parameters for hours and limit which can lead to
runtime SQL errors if null; change the parameter types to primitive int (e.g.,
int hours, int limit) in the selectActiveUserIds signature so callers and the
mapper contract cannot pass null values, update any calling code or interface
implementations to pass primitives accordingly, and run tests to ensure the SQL
INTERVAL #{hours} HOUR and LIMIT #{limit} bindings work with the new types.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java`:
- Around line 51-52: The log statement in HotKeyMonitorService that calls
log.warn("热点Key告警 key={}, minute={}, hits={}", shortKey, minute, count) exposes
raw cache keys (shortKey) and risks leaking sensitive IDs; update these logging
calls (the log.warn invocations that use shortKey at the locations around the
existing lines and the similar calls near lines 78-79) to instead log a
de-identified value — e.g., replace shortKey with a deterministic hash or
prefix-only token (hashPrefix(shortKey) or maskShortKey(shortKey)) or log only a
key pattern/type — and keep minute and count as-is so the warning remains
informative without exposing full key contents.
- Around line 65-66: The current logic in HotKeyMonitorService computes a single
reportMinute (reportMinute = current - 1) and reports only that minute then
deletes entries <= reportMinute, which loses data if the scheduled job is
delayed; change the flow to collect all unreported minute windows between the
lastReportedMinute (or the earliest stored minute) and current-1, group hot-key
entries by minute, emit a report for each minute (using the same topN via
monitor.getHotKeyTopN()), and only after successfully reporting all those
minutes perform cleanup of stored minutes <= the newest reported minute; update
the code paths that set reportMinute and the cleanup condition (the blocks
referencing reportMinute) to iterate and report per-minute groups instead of a
single minute.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`:
- Around line 140-142: The condition to update sampleSql is wrong because you
call maxMs.accumulateAndGet(elapsedMs, Math::max) before comparing, so elapsedMs
> maxMs.get() will almost never be true; change the atomic update to capture the
previous max and compare against that. For example, use
maxMs.getAndAccumulate(elapsedMs, Math::max) (or getAndUpdate) to obtain the
prior value into a variable (prev), then do if (elapsedMs > prev) sampleSql =
normalizedSql; — update the logic in SlowSqlAnalysisService where elapsedMs,
maxMs and sampleSql are handled (normalizedSql is the sample content to assign).

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`:
- Line 66: The call to recommendationService.getHomeRecommendations in
RecommendationPrecomputeTask can block indefinitely; wrap the call in a timed
asynchronous invocation (e.g., use CompletableFuture.supplyAsync(...) with
orTimeout(timeout, TimeUnit.SECONDS) or submit to a Scheduled/ExecutorService
and use future.get(timeout,...)) to enforce a max wait (e.g., 30s), handle
TimeoutException/ExecutionException by logging via the task's logger and
proceeding (or cancelling the future) so the scheduled thread isn't blocked, and
ensure you still handle or persist partial failures when RecommendHomeResponse
is unavailable.
- Around line 35-87: Wrap the body of RecommendationPrecomputeTask.precompute()
in a distributed lock so only one instance runs the precompute at a time:
attempt to acquire a lock (e.g., key "lock:recommend-precompute") before doing
any work using cacheClient.setIfAbsent(...) or a Redisson RLock (use a TTL from
performanceProperties.getCache() or a hard 5min if none), log and return if
acquisition fails, run the existing logic only when acquired, and always release
the lock in a finally block (or use Redisson's tryLock/unlock pattern); ensure
you only delete/unlock if you successfully acquired the lock and handle
exceptions around lock operations cleanly.

---

Outside diff comments:
In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.java`:
- Around line 93-105: The hot-key access is being recorded inside the retry
loop, so hotKeyMonitorService.recordAccess(key) is called on every retry and
inflates counts; move the single call to hotKeyMonitorService.recordAccess(key)
out of the retry loop so it is invoked once per API call (i.e. call it before
entering the while/retry that uses tryLock(lockKey), sleepBriefly(), and cache
lookup logic), ensuring the rest of the loop (tryLock, cache get, deserialize,
sleepBriefly) remains unchanged.

---

Nitpick comments:
In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`:
- Around line 67-69: 在 SlowSqlAnalysisService 中直接调用 statMap.clear() 会丢失在生成
snapshots(或读取 fingerprintCount)后并发写入的新样本;请改为先基于 statMap 做一个快照副本(例如取 keySet 或构造新的
Map 引用),然后只定向移除快照中的键(通过循环调用 statMap.remove(key) 或使用并发安全的替换/轮换双缓冲策略替换整个 map
引用),确保 fingerprintCount 仍基于快照计算且不会清掉并发写入的数据。

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.java`:
- Around line 175-195: The current getCityCards implementation in
CityServiceImpl builds attractionCountMap by running a grouped aggregate via
attractionMapper.selectMaps on every request; instead, cache per-city attraction
counts (the map keyed by city_id used to fill City.attractionCount) behind the
existing CacheClient with a short TTL (1–5 min) and/or invalidate/update the
cached map when Attraction entities change (status or audit_status updates) so
requests read the cached map first and only query the DB on cache miss; keep the
same filtering (status=1, audit_status=2) and ensure attraction(city_id, status,
audit_status) is indexed, and update code paths around attractionCountMap and
attractionMapper to read from the cache and fall back to the grouped aggregate
only when needed.
- Around line 186-194: The loop in CityServiceImpl reading
attractionMapper.selectMaps(countWrapper) assumes column labels "city_id" and
"attraction_count" are lower-case; to make this robust across DB drivers,
perform a case-insensitive lookup when extracting values from each
Map<String,Object> (countRows). For example, create or inline a small helper
that given a Map and a target key (e.g., "city_id" or "attraction_count") scans
the map keys and returns the value for the matching key ignoring case, then use
that value to populate attractionCountMap; update the loop that references
countRows, the cityId/count extraction logic, and ensure parsedCount handling
remains the same.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`:
- Around line 48-50: Replace the sentinel 0L guest marker with a real null in
targetUserIds to remove the needless indirection: when
monitor.isIncludeGuestPrecompute() is true, add null (not 0L) to targetUserIds,
and update the processing loop in RecommendationPrecomputeTask (where
targetUserIds are iterated and currently checked with userId <= 0 ? null) to
treat a null userId as the guest case directly (or alternatively handle the
guest user in a separate branch outside the targetUserIds loop); adjust any
null/primitive checks accordingly so no 0L sentinel is used.
🪄 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: e97b1f31-1c7c-4934-aa6a-a08426ee40c3

📥 Commits

Reviewing files that changed from the base of the PR and between e08c292 and 40304ce.

⛔ Files ignored due to path filters (1)
  • jmeter.log is excluded by !**/*.log
📒 Files selected for processing (11)
  • .gitignore
  • 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/service/impl/CityServiceImpl.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
  • backend/sql/travel_system.sql
  • docs/毕业论文.md

Comment thread .gitignore
Comment on lines +1 to +2
node_modules
docs No newline at end of file

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 | ⚡ Quick win

Scope docs to avoid silently ignoring any nested documentation folder.

docs without a leading slash matches a file or directory named docs at any depth in the repo. If any subproject (frontend, backend module, sample, etc.) ever ships a docs/ folder of real documentation, git will untrack it without warning. If the intent is to ignore a generated docs directory at the repo root, anchor the pattern; same for node_modules if it's only expected under the frontend.

🛠️ Proposed fix
-node_modules
-docs
+/node_modules/
+/docs/

Or scope per-subproject, e.g. frontend/node_modules/ and backend/.../target/docs/.

📝 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
node_modules
docs
/node_modules/
/docs/
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.gitignore around lines 1 - 2, The .gitignore currently contains unanchored
patterns "node_modules" and "docs" which will ignore any matching folders at any
depth; change these to anchored or scoped entries (e.g. prefix with a leading
slash like "/docs" or "/node_modules" if you only mean the repo root, or replace
with per-subproject paths like "frontend/node_modules/" and
"backend/.../target/docs/") so only the intended root/generated directories are
ignored and not nested documentation or node_modules folders in subprojects.

Comment on lines +47 to +48
List<Long> selectActiveUserIds(@Param("hours") Integer hours,
@Param("limit") Integer limit);

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 | ⚡ Quick win

Consider using non-nullable primitive types for SQL parameters.

The Integer wrapper types allow null values, but the SQL query requires actual numeric values for INTERVAL #{hours} HOUR and LIMIT #{limit}. If either parameter is null, the query will fail at runtime. Using primitive int types would prevent null values at compile time and make the contract clearer.

🛡️ Proposed fix
-    List<Long> selectActiveUserIds(`@Param`("hours") Integer hours,
-                                   `@Param`("limit") Integer limit);
+    List<Long> selectActiveUserIds(`@Param`("hours") int hours,
+                                   `@Param`("limit") int limit);
📝 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
List<Long> selectActiveUserIds(@Param("hours") Integer hours,
@Param("limit") Integer limit);
List<Long> selectActiveUserIds(`@Param`("hours") int hours,
`@Param`("limit") int limit);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.java`
around lines 47 - 48, The method selectActiveUserIds in UserBrowseRecordMapper
currently uses nullable Integer parameters for hours and limit which can lead to
runtime SQL errors if null; change the parameter types to primitive int (e.g.,
int hours, int limit) in the selectActiveUserIds signature so callers and the
mapper contract cannot pass null values, update any calling code or interface
implementations to pass primitives accordingly, and run tests to ensure the SQL
INTERVAL #{hours} HOUR and LIMIT #{limit} bindings work with the new types.

Comment on lines +51 to +52
log.warn("热点Key告警 key={}, minute={}, hits={}", shortKey, minute, count);
}

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 | ⚡ Quick win

热键日志直接输出 key 存在敏感标识泄露风险。

缓存 key 往往包含用户标识/业务ID,直接写入 warn 日志不利于隐私合规。建议日志里改为脱敏值(如 hash 前缀)或只打 pattern/type。

Also applies to: 78-79

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java`
around lines 51 - 52, The log statement in HotKeyMonitorService that calls
log.warn("热点Key告警 key={}, minute={}, hits={}", shortKey, minute, count) exposes
raw cache keys (shortKey) and risks leaking sensitive IDs; update these logging
calls (the log.warn invocations that use shortKey at the locations around the
existing lines and the similar calls near lines 78-79) to instead log a
de-identified value — e.g., replace shortKey with a deterministic hash or
prefix-only token (hashPrefix(shortKey) or maskShortKey(shortKey)) or log only a
key pattern/type — and keep minute and count as-is so the warning remains
informative without exposing full key contents.

Comment on lines +65 to +66
long reportMinute = current - 1;
int topN = Math.max(1, monitor.getHotKeyTopN());

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 | ⚡ Quick win

调度延迟时会跳过并丢弃未上报分钟的数据。

当前只上报 current-1 分钟,但清理时删除 <= reportMinute;若任务延迟超过 1 分钟,中间窗口未上报就会被删掉。建议按“所有未上报分钟”分组输出后再清理。

Also applies to: 82-83

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.java`
around lines 65 - 66, The current logic in HotKeyMonitorService computes a
single reportMinute (reportMinute = current - 1) and reports only that minute
then deletes entries <= reportMinute, which loses data if the scheduled job is
delayed; change the flow to collect all unreported minute windows between the
lastReportedMinute (or the earliest stored minute) and current-1, group hot-key
entries by minute, emit a report for each minute (using the same topN via
monitor.getHotKeyTopN()), and only after successfully reporting all those
minutes perform cleanup of stored minutes <= the newest reported minute; update
the code paths that set reportMinute and the cleanup condition (the blocks
referencing reportMinute) to iterate and report per-minute groups instead of a
single minute.

Comment on lines +140 to +142
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 | 🟡 Minor | ⚡ Quick win

sampleSql更新条件永远不成立,导致样本SQL无法按最慢请求刷新。

这里先执行了 maxMs.accumulateAndGet(elapsedMs, Math::max),随后再判断 elapsedMs > maxMs.get(),条件基本恒为 false。结果是 sampleSql 不会按预期在更慢样本出现时更新。

Suggested fix
         private void record(long elapsedMs, Throwable throwable) {
             count.increment();
             totalMs.add(elapsedMs);
-            maxMs.accumulateAndGet(elapsedMs, Math::max);
+            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 > maxMs.get()) {
+            if (elapsedMs > prevMax) {
                 sampleSql = normalizedSql;
             }
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.java`
around lines 140 - 142, The condition to update sampleSql is wrong because you
call maxMs.accumulateAndGet(elapsedMs, Math::max) before comparing, so elapsedMs
> maxMs.get() will almost never be true; change the atomic update to capture the
previous max and compare against that. For example, use
maxMs.getAndAccumulate(elapsedMs, Math::max) (or getAndUpdate) to obtain the
prior value into a variable (prev), then do if (elapsedMs > prev) sampleSql =
normalizedSql; — update the logic in SlowSqlAnalysisService where elapsedMs,
maxMs and sampleSql are handled (normalizedSql is the sample content to assign).

Comment on lines +35 to +87
public void precompute() {
PerformanceProperties.Monitor monitor = performanceProperties.getMonitor();
if (!monitor.isRecommendPrecomputeEnabled()) {
return;
}

int activeWindowHours = Math.max(1, monitor.getPrecomputeActiveWindowHours());
int userLimit = Math.max(1, monitor.getPrecomputeUserLimit());
long pageNum = Math.max(1, monitor.getPrecomputePageNum());
long pageSize = Math.max(1, monitor.getPrecomputePageSize());

List<Long> activeUserIds = userBrowseRecordMapper.selectActiveUserIds(activeWindowHours, userLimit);
List<Long> targetUserIds = new ArrayList<>(activeUserIds == null ? List.of() : activeUserIds);
if (monitor.isIncludeGuestPrecompute()) {
targetUserIds.add(0L);
}

if (targetUserIds.isEmpty()) {
return;
}

long start = System.currentTimeMillis();
int success = 0;
int failed = 0;

for (Long userId : targetUserIds) {
Long actualUserId = (userId == null || userId <= 0) ? null : userId;
try {
RecommendHomeRequest request = new RecommendHomeRequest();
request.setPageNum(pageNum);
request.setPageSize(pageSize);
RecommendHomeResponse response = recommendationService.getHomeRecommendations(actualUserId, request);

String cacheKey = CacheConstants.RECOMMEND_HOME_KEY
+ (actualUserId == null ? 0L : actualUserId)
+ ":" + pageNum
+ ":" + pageSize;
cacheClient.set(
cacheKey,
response,
performanceProperties.getCache().getRecommendTtlSec(),
performanceProperties.getCache().getTtlJitterSec());
success++;
} catch (Exception ex) {
failed++;
log.warn("推荐预计算失败 userId={}", userId, ex);
}
}

long costMs = System.currentTimeMillis() - start;
log.info("推荐预计算完成 users={}, success={}, failed={}, pageNum={}, pageSize={}, costMs={}",
targetUserIds.size(), success, failed, pageNum, pageSize, costMs);
}

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 | 🏗️ Heavy lift

Add distributed locking for multi-instance deployments.

In a multi-instance deployment, this scheduled task will run concurrently on all instances, causing duplicate precomputation for the same users. This wastes resources and could cause cache thrashing. Consider adding distributed locking (e.g., using Redis SETNX, or a dedicated distributed lock library like Redisson) to ensure only one instance executes the precomputation at a time.

Example pattern with distributed lock
`@Scheduled`(...)
public void precompute() {
    String lockKey = "lock:recommend-precompute";
    boolean acquired = false;
    try {
        // Try to acquire lock with expiration
        acquired = cacheClient.setIfAbsent(lockKey, "locked", 300); // 5 min max
        if (!acquired) {
            log.info("Another instance is running precompute, skipping");
            return;
        }
        
        // existing precompute logic...
    } finally {
        if (acquired) {
            cacheClient.delete(lockKey);
        }
    }
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`
around lines 35 - 87, Wrap the body of RecommendationPrecomputeTask.precompute()
in a distributed lock so only one instance runs the precompute at a time:
attempt to acquire a lock (e.g., key "lock:recommend-precompute") before doing
any work using cacheClient.setIfAbsent(...) or a Redisson RLock (use a TTL from
performanceProperties.getCache() or a hard 5min if none), log and return if
acquisition fails, run the existing logic only when acquired, and always release
the lock in a finally block (or use Redisson's tryLock/unlock pattern); ensure
you only delete/unlock if you successfully acquired the lock and handle
exceptions around lock operations cleanly.

RecommendHomeRequest request = new RecommendHomeRequest();
request.setPageNum(pageNum);
request.setPageSize(pageSize);
RecommendHomeResponse response = recommendationService.getHomeRecommendations(actualUserId, request);

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 | ⚡ Quick win

Add timeout to prevent blocking indefinitely.

The recommendationService.getHomeRecommendations() call has no timeout. If the service is slow or hangs, this scheduled task thread will block indefinitely, potentially preventing future executions. Consider adding a timeout using @Timeout annotation or wrapping the call with a timeout mechanism.

Example with timeout
`@Timeout`(value = 30, unit = TimeUnit.SECONDS)
RecommendHomeResponse response = recommendationService.getHomeRecommendations(actualUserId, request);

Or use CompletableFuture.orTimeout():

CompletableFuture<RecommendHomeResponse> future = CompletableFuture.supplyAsync(
    () -> recommendationService.getHomeRecommendations(actualUserId, request));
RecommendHomeResponse response = future.orTimeout(30, TimeUnit.SECONDS).get();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.java`
at line 66, The call to recommendationService.getHomeRecommendations in
RecommendationPrecomputeTask can block indefinitely; wrap the call in a timed
asynchronous invocation (e.g., use CompletableFuture.supplyAsync(...) with
orTimeout(timeout, TimeUnit.SECONDS) or submit to a Scheduled/ExecutorService
and use future.get(timeout,...)) to enforce a max wait (e.g., 30s), handle
TimeoutException/ExecutionException by logging via the task's logger and
proceeding (or cancelling the future) so the scheduled thread isn't blocked, and
ensure you still handle or persist partial failures when RecommendHomeResponse
is unavailable.

@Uchkun07 Uchkun07 closed this Jul 31, 2026
@Uchkun07
Uchkun07 deleted the newindex branch September 17, 2026 09:10
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