Repository navigation
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesPerformance Monitoring and Cache Optimization
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
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 winConsider caching per-city attraction counts to avoid per-request aggregate query.
getCityCardsis a customer-facing listing endpoint. Replacing the denormalizedCity.attractionCountwith 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 behindCacheClient). Make sureattraction(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 valueOptional: Make column-key lookup case-insensitive if considering database portability.
The code currently relies on
row.get("city_id")androw.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 returnnulland default to0for 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 valueSimplify guest user handling.
The code adds
0Lto represent the guest user (line 49), then immediately converts it tonullin the loop (line 61:userId <= 0 ? null). This indirection adds complexity. Consider either addingnulldirectly totargetUserIdsor 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
nulldirectly: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
⛔ Files ignored due to path filters (1)
jmeter.logis excluded by!**/*.log
📒 Files selected for processing (11)
.gitignorebackend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/PerformanceProperties.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/config/SlowSqlInterceptor.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/mapper/UserBrowseRecordMapper.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/HotKeyMonitorService.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/monitor/SlowSqlAnalysisService.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/service/impl/CityServiceImpl.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/task/RecommendationPrecomputeTask.javabackend/springProject/src/main/java/io/github/uchkun07/travelsystem/util/CacheClient.javabackend/sql/travel_system.sqldocs/毕业论文.md
| node_modules | ||
| docs No newline at end of file |
There was a problem hiding this comment.
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.
| 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.
| List<Long> selectActiveUserIds(@Param("hours") Integer hours, | ||
| @Param("limit") Integer limit); |
There was a problem hiding this comment.
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.
| 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.
| log.warn("热点Key告警 key={}, minute={}, hits={}", shortKey, minute, count); | ||
| } |
There was a problem hiding this comment.
热键日志直接输出 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.
| long reportMinute = current - 1; | ||
| int topN = Math.max(1, monitor.getHotKeyTopN()); |
There was a problem hiding this comment.
调度延迟时会跳过并丢弃未上报分钟的数据。
当前只上报 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.
| if (elapsedMs > maxMs.get()) { | ||
| sampleSql = normalizedSql; | ||
| } |
There was a problem hiding this comment.
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).
| 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); | ||
| } |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
Summary by CodeRabbit
New Features
Chores
.gitignoreto exclude documentation directory.