From 8e904e87287454013a7b2b54f4c959adf0151c12 Mon Sep 17 00:00:00 2001
From: liujiming <liujm@wealthgrow.cn>
Date: Mon, 14 Feb 2022 18:02:38 +0800
Subject: [PATCH] visit log fix

---
 .../community/dao/mapper/community/VisitLogMapper.java    | 2 +-
 .../java/com/tanpu/community/service/VisitLogService.java | 8 ++++----
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/community-service/src/main/java/com/tanpu/community/dao/mapper/community/VisitLogMapper.java b/community-service/src/main/java/com/tanpu/community/dao/mapper/community/VisitLogMapper.java
index 0777fb2..97ea8cf 100644
--- a/community-service/src/main/java/com/tanpu/community/dao/mapper/community/VisitLogMapper.java
+++ b/community-service/src/main/java/com/tanpu/community/dao/mapper/community/VisitLogMapper.java
@@ -21,7 +21,7 @@ import java.util.List;
  * @since 2021-07-28
  */
 public interface VisitLogMapper extends BaseMapper<VisitLogEntity> {
-    @Select("select * from visit_log where ident=#{ident} and ref_id=#{refId} and ref_type=#{refType}")
+    @Select("select * from visit_log where ident=#{ident} and ref_id=#{refId} and ref_type=#{refType} for update")
     VisitLogEntity selectByIdentAndRefId(@Param("ident") String ident, @Param("refId") String refId, @Param("refType") String refType);
 
     @Update("update visit_log set duration=duration+#{duration} where ident=#{ident} and ref_id=#{refId} and ref_type=#{refType}")
diff --git a/community-service/src/main/java/com/tanpu/community/service/VisitLogService.java b/community-service/src/main/java/com/tanpu/community/service/VisitLogService.java
index 66416b3..fb4ca58 100644
--- a/community-service/src/main/java/com/tanpu/community/service/VisitLogService.java
+++ b/community-service/src/main/java/com/tanpu/community/service/VisitLogService.java
@@ -65,16 +65,16 @@ public class VisitLogService {
     @Transactional
     public void insertOrUpdateDur(VisitLogEntity vs) {
         // 分布式锁
-        for (;;) {
+        for (int i = 0; i < 5 * 10; i++) {
             String key = getVisitLogRedisKey(vs);
-            if (redisCache.setIfAbsent(key, "1", 15)) {
+            String rand = String.valueOf((int) Math.floor(Math.random() * 100));
+            if (redisCache.setIfAbsent(key, rand, 15)) {
                 if (visitLogMapper.selectByIdentAndRefId(vs.getIdent(), vs.getRefId(), vs.getRefType()) == null) {
                     visitLogMapper.insert(vs);
                 } else {
                     visitLogMapper.updateDurByIdent(vs.getDuration(), vs.getIdent(), vs.getRefId(), vs.getRefType());
                 }
-                // 如果执行超时,会删除别的实例的key
-                redisCache.evict(key);
+                redisCache.evict(key + ":" + rand);
                 return;
             }
             try {
-- 
2.18.1