Explorar o código

优化redis占用

dodo hold hai 3 semanas
pai
achega
7f91fafc7b

+ 10 - 4
molilian.core/Core/taoke/TaobaoGeneralLinkParseCacheCore.cs

@@ -6,7 +6,9 @@ namespace molilian.core
 {
     public static class TaobaoGeneralLinkParseCacheCore
     {
-        public const int CacheExpireSeconds = 7 * 86400;
+        // 成功结果缓存 1 天;确定无法解析的链接缓存 1 小时;网络异常等临时错误不缓存
+        public const int SuccessExpireSeconds = 86400;
+        public const int FailureExpireSeconds = 3600;
 
         // 统计跨天保留,每次通知领取上次通知后的全部次数;同一天只允许领取一次。
         private const string ClaimNotificationScript = @"
@@ -32,11 +34,12 @@ return count";
             }
         }
 
-        public static async Task SaveAsync(TaobaoGeneralLinkParseCacheDTO record)
+        public static async Task SaveAsync(string content, TaobaoGeneralLinkParseCacheDTO record, int expireSeconds)
         {
+            if (expireSeconds <= 0) return;
             try
             {
-                await CenterHub.Redis.SetAsync(GetCacheKey(record.RequestContent), record, CacheExpireSeconds);
+                await CenterHub.Redis.SetAsync(GetCacheKey(content), record, expireSeconds);
             }
             catch (Exception ex)
             {
@@ -79,7 +82,10 @@ return count";
 
         private static string GetCacheKey(string content)
         {
-            return $"cache:taobao:general_link_parse:v1:{Hash(content.Trim())}";
+            // v2:精简缓存结构,不与 v1 旧数据混用
+            // 取 SHA256 前 8 字节(16 位十六进制),压缩 key 占用
+            string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(content.Trim())), 0, 8);
+            return $"cache:taobao:general_link_parse:v2:{hash}";
         }
 
         private static string Hash(string value)

+ 28 - 8
molilian.core/Core/taoke/TaobaoShortLinkCacheCore.cs

@@ -6,13 +6,16 @@ namespace molilian.core
 {
     public static class TaobaoShortLinkCacheCore
     {
-        public const int CacheExpireSeconds = 7 * 86400;
+        // 短链每次走 HTTP 解析都计数(保留 1 天),超过 CacheAfterCount 次才缓存长链,避免一次性短链占用内存
+        public const int CacheExpireSeconds = 86400;
+        public const int CounterExpireSeconds = 86400;
+        public const int CacheAfterCount = 3;
 
         public static async Task<string?> GetAsync(string shortUrl)
         {
             try
             {
-                string longUrl = await CenterHub.Redis.GetAsync<string>(GetCacheKey(shortUrl));
+                string longUrl = await CenterHub.Redis.GetAsync<string>(GetCacheKey(Hash(shortUrl)));
                 return IsLongUrl(longUrl) ? longUrl : null;
             }
             catch (Exception ex)
@@ -26,7 +29,7 @@ namespace molilian.core
         {
             try
             {
-                string longUrl = CenterHub.Redis.Get<string>(GetCacheKey(shortUrl));
+                string longUrl = CenterHub.Redis.Get<string>(GetCacheKey(Hash(shortUrl)));
                 return IsLongUrl(longUrl) ? longUrl : null;
             }
             catch (Exception ex)
@@ -41,7 +44,13 @@ namespace molilian.core
             if (!IsLongUrl(longUrl)) return;
             try
             {
-                await CenterHub.Redis.SetAsync(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds);
+                string hash = Hash(shortUrl);
+                string counterKey = GetCounterKey(hash);
+                long count = await CenterHub.Redis.IncrByAsync(counterKey);
+                if (count == 1) await CenterHub.Redis.ExpireAsync(counterKey, CounterExpireSeconds);
+                if (count <= CacheAfterCount) return;
+
+                await CenterHub.Redis.SetAsync(GetCacheKey(hash), longUrl, CacheExpireSeconds);
             }
             catch (Exception ex)
             {
@@ -54,7 +63,13 @@ namespace molilian.core
             if (!IsLongUrl(longUrl)) return;
             try
             {
-                CenterHub.Redis.Set(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds);
+                string hash = Hash(shortUrl);
+                string counterKey = GetCounterKey(hash);
+                long count = CenterHub.Redis.IncrBy(counterKey);
+                if (count == 1) CenterHub.Redis.Expire(counterKey, CounterExpireSeconds);
+                if (count <= CacheAfterCount) return;
+
+                CenterHub.Redis.Set(GetCacheKey(hash), longUrl, CacheExpireSeconds);
             }
             catch (Exception ex)
             {
@@ -69,12 +84,17 @@ namespace molilian.core
                 !AlimamaPlus.IsShortLink(url!);
         }
 
-        private static string GetCacheKey(string shortUrl)
+        // 取 SHA256 前 8 字节(16 位十六进制),压缩 key 占用,碰撞概率可忽略
+        private static string Hash(string shortUrl)
         {
-            string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(shortUrl.Trim())));
-            return $"cache:taobao:short_link_http:v1:{hash}";
+            return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(shortUrl.Trim())), 0, 8);
         }
 
+        // v2:改为计数达标后才缓存,不与 v1 旧数据混用
+        private static string GetCacheKey(string hash) => $"cache:taobao:short_link_http:v2:{hash}";
+
+        private static string GetCounterKey(string hash) => $"cache:taobao:short_link_http:cnt:{hash}";
+
         private static void LogFailure(string operation, Exception ex)
         {
             _ = new LoggerLibrary("taobao_short_link_cache", operation)

+ 3 - 3
molilian.core/DTO/alimama/TaobaoGeneralLinkParseCacheDTO.cs

@@ -1,9 +1,10 @@
 namespace molilian.core
 {
+    /// <summary>
+    /// 万能解析缓存,只保存命中时需要回填的字段(不存请求内容和接口原始返回,控制 Redis 占用)
+    /// </summary>
     public sealed class TaobaoGeneralLinkParseCacheDTO
     {
-        public string RequestContent { get; set; } = string.Empty;
-        public DateTime RequestedAtUtc { get; set; }
         public int ParseAccountId { get; set; }
         public bool Success { get; set; }
         public string Reason { get; set; } = string.Empty;
@@ -11,6 +12,5 @@ namespace molilian.core
         public LinkTypeEnum LinkType { get; set; }
         public string ItemId { get; set; } = string.Empty;
         public string ItemUrl { get; set; } = string.Empty;
-        public string ResponseBody { get; set; } = string.Empty;
     }
 }

+ 9 - 12
molilian.core/Plus/Alimama/parse_endpoint/endpoint_tbk_dg_general_link_parse.cs

@@ -12,10 +12,10 @@ namespace molilian.core
             result.channel = TkChannelEnum.tb;
             result.commercial = false;
             result.remote_response = string.Empty;
-            bool requestSent = false;
             bool resultCompleted = false;
             int parseAccountId = 0;
-            DateTime requestedAtUtc = default;
+            // 缓存时长:0 表示不缓存(只缓存成功和确定无法解析的结果)
+            int cacheExpireSeconds = 0;
 
             TkDataDTO Fail(string reason, TkSubCodeEnum subCode = TkSubCodeEnum.Other)
             {
@@ -55,7 +55,6 @@ namespace molilian.core
                     result.item_url = cached.ItemUrl;
                     result.deeplink_url = cached.Success ? GetDeeplink(cached.ItemUrl) : string.Empty;
                     result.item_deeplink_url = result.deeplink_url;
-                    result.remote_response = cached.ResponseBody;
                     result.content = cached.Success ? ReplaceUrls(content, cached.ItemUrl) : content;
                     resultCompleted = true;
                     return result;
@@ -81,8 +80,6 @@ namespace molilian.core
                         .SaveAsync();
                 }
                 cancellationToken.ThrowIfCancellationRequested();
-                requestedAtUtc = DateTime.UtcNow;
-                requestSent = true;
                 var response = taobao.GeneralLinkParseRequest(content);
                 result.remote_response = response?.Body ?? string.Empty;
 
@@ -114,12 +111,14 @@ namespace molilian.core
 
                 if (material.Code != 0)
                 {
+                    cacheExpireSeconds = TaobaoGeneralLinkParseCacheCore.FailureExpireSeconds;
                     return Fail($"{material.Code}:{material.Msg}", TkSubCodeEnum.NoConvert);
                 }
 
                 var linkInfo = material.LinkInfoDto;
                 if (linkInfo == null || string.IsNullOrWhiteSpace(linkInfo.TpwdOriginUrl))
                 {
+                    cacheExpireSeconds = TaobaoGeneralLinkParseCacheCore.FailureExpireSeconds;
                     return Fail("解析结果缺少原始链接", TkSubCodeEnum.NoConvert);
                 }
 
@@ -145,6 +144,7 @@ namespace molilian.core
                 result.item_url = url;
                 result.item_deeplink_url = result.deeplink_url;
                 resultCompleted = true;
+                cacheExpireSeconds = TaobaoGeneralLinkParseCacheCore.SuccessExpireSeconds;
                 return result;
             }
             catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
@@ -157,21 +157,18 @@ namespace molilian.core
             }
             finally
             {
-                if (requestSent && resultCompleted)
+                if (cacheExpireSeconds > 0 && resultCompleted)
                 {
-                    await TaobaoGeneralLinkParseCacheCore.SaveAsync(new TaobaoGeneralLinkParseCacheDTO
+                    await TaobaoGeneralLinkParseCacheCore.SaveAsync(content, new TaobaoGeneralLinkParseCacheDTO
                     {
-                        RequestContent = content,
-                        RequestedAtUtc = requestedAtUtc,
                         ParseAccountId = parseAccountId,
                         Success = result.success,
                         Reason = result.reason,
                         SubCode = result.subCode,
                         LinkType = result.success ? result.link_type : LinkTypeEnum.unknown,
                         ItemId = result.success ? result.itemId : string.Empty,
-                        ItemUrl = result.success ? result.item_url : string.Empty,
-                        ResponseBody = result.remote_response
-                    });
+                        ItemUrl = result.success ? result.item_url : string.Empty
+                    }, cacheExpireSeconds);
                 }
 
                 if (resultCompleted && !result.success && !cancellationToken.IsCancellationRequested)