基于用户套餐实现每日点击量限制的代码优化求助
修复基于套餐的每日点击量限制功能的实现建议
Let's break down what's wrong with your current code and fix it step by step to get the daily click limit working correctly.
Issues in Your Current Implementation
- Time calculation is incorrect: You named a variable
tenSecondsLaterbut added 1 day tonow, which is confusing. More importantly, your way of checking if a new day has started is flawed—you're comparing the last activity time to tomorrow instead of checking if it's in a different calendar day than today. - Logic is reversed: Your code returns
true(allowing the click) when the user has hit their daily limit AND a day has passed, which is the opposite of what you need. We need to reset the count when a new day starts, then check if the current count is under the limit to allow the click. - No database persistence: You're modifying
todayHitsin memory but never saving those changes back to the database. This means the count will reset every time you fetch the user again. - Null handling missing: If a user has never had any activity (
planLastActivityisnull), your code will throw an error when calculating the date difference.
Corrected Implementation
First, let's define the daily limits clearly, then handle the date check properly, update the database, and fix the logic flow.
public boolean calculateClickTimes() { String userName = SecurityUtils.getSubject().getPrincipal().toString(); QueryDashboardHelper queryHelper = new QueryDashboardHelper(); UsersModel user = queryHelper.getUserByUserName(userName); // Define daily limits per plan for easy maintenance Map<String, Integer> planDailyLimits = new HashMap<>(); planDailyLimits.put("diamond", 20); planDailyLimits.put("platinum", 15); planDailyLimits.put("gold", 10); planDailyLimits.put("silver", 5); String userPlan = user.getPlan(); Integer dailyLimit = planDailyLimits.getOrDefault(userPlan, 0); // Default to 0 for unknown plans LocalDateTime lastActivityTime = user.getPlanLastActivity(); LocalDateTime currentTime = LocalDateTime.now(); int currentDailyHits = user.getTradesPerDay(); // Check if we've entered a new calendar day (or user has no prior activity) boolean isNewCalendarDay = lastActivityTime == null || !LocalDate.from(lastActivityTime).equals(LocalDate.from(currentTime)); if (isNewCalendarDay) { // Reset hit count for the new day and update activity time currentDailyHits = 0; user.setPlanLastActivity(currentTime); } // Check if user still has remaining clicks today if (currentDailyHits < dailyLimit) { // Increment hit count and update last activity timestamp user.setTradesPerDay(currentDailyHits + 1); user.setPlanLastActivity(currentTime); // Persist changes to database (ensure your helper has an update method) queryHelper.updateUser(user); return true; // Allow the click } else { // User has exhausted daily click limit return false; // Block the click } }
Key Improvements
- Cleaner limit management: Using a
Mapmakes it simple to adjust limits later without rewriting switch-case logic. - Accurate new day check: We compare the date-only component of the last activity to today's date, which correctly identifies when a new calendar day starts (regardless of time of day).
- Proper state persistence: All changes to the user's hit count and activity time are saved back to the database, so state persists across sessions and server restarts.
- Null safety: Handles new users with no prior activity by treating their first click as the start of a new day.
- Intuitive logic flow: Reset count if new day → check remaining clicks → allow/block accordingly.
Additional Recommendations
- Use constants for plan names: Define
public static final String PLAN_DIAMOND = "diamond";and similar constants to avoid typos in string literals. - Add logging for unknown plans: If a user has an invalid plan, the code defaults to 0 clicks—add a log warning to catch and fix these cases.
- Handle concurrency: For high-traffic scenarios, use database optimistic locking or row-level locks to prevent race conditions where two requests increment the count simultaneously.
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

