| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using dodohold.core;
- using System.Security.Cryptography;
- using System.Text;
- namespace molilian.core
- {
- public static class TaobaoGeneralLinkParseCacheCore
- {
- public const int CacheExpireSeconds = 7 * 86400;
- // 统计跨天保留,每次通知领取上次通知后的全部次数;同一天只允许领取一次。
- private const string ClaimNotificationScript = @"
- local count = redis.call('HINCRBY', KEYS[1], 'pending', 1)
- local lastDate = redis.call('HGET', KEYS[1], 'last_notify_date')
- if lastDate and lastDate >= ARGV[1] then
- return 0
- end
- redis.call('HSET', KEYS[1], 'last_notify_date', ARGV[1])
- redis.call('HSET', KEYS[1], 'pending', 0)
- return count";
- public static async Task<TaobaoGeneralLinkParseCacheDTO?> GetAsync(string content)
- {
- try
- {
- return await CenterHub.Redis.GetAsync<TaobaoGeneralLinkParseCacheDTO>(GetCacheKey(content));
- }
- catch (Exception ex)
- {
- LogFailure("cache_read_error", ex);
- return null;
- }
- }
- public static async Task SaveAsync(TaobaoGeneralLinkParseCacheDTO record)
- {
- try
- {
- await CenterHub.Redis.SetAsync(GetCacheKey(record.RequestContent), record, CacheExpireSeconds);
- }
- catch (Exception ex)
- {
- LogFailure("cache_write_error", ex);
- }
- }
- public static async Task NotifyFailureOnceAsync(string reason, int parseAccountId, int consumerAccountId)
- {
- reason = string.IsNullOrWhiteSpace(reason) ? "未知错误" : reason.Trim();
- string key = $"notify:taobao:general_link_parse:v1:{Hash(reason)}";
- long count = 0;
- try
- {
- count = Convert.ToInt64(await CenterHub.Redis.EvalAsync(ClaimNotificationScript, key, DateTime.Now.ToString("yyyyMMdd")));
- if (count <= 0) return;
- await NotifyCore.NotifyAsync(
- $"【淘宝万能解析失败】\n错误信息:{reason}\n" +
- $"自上次相同错误通知以来发生:{count} 次(含本次)\n" +
- $"使用账号:{consumerAccountId},解析账号:{parseAccountId}\n已回退原短链解析逻辑。");
- }
- catch (Exception ex)
- {
- if (count > 0)
- {
- try
- {
- // 发送失败的次数留给下一次通知,同一天不重复尝试发送。
- await CenterHub.Redis.HIncrByAsync(key, "pending", count);
- }
- catch (Exception restoreException)
- {
- LogFailure("notify_count_restore_error", restoreException);
- }
- }
- LogFailure("notify_error", ex);
- }
- }
- private static string GetCacheKey(string content)
- {
- return $"cache:taobao:general_link_parse:v1:{Hash(content.Trim())}";
- }
- private static string Hash(string value)
- {
- return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
- }
- private static void LogFailure(string operation, Exception ex)
- {
- _ = new LoggerLibrary("tbk_dg_general_link_parse", operation)
- .Info(ex.Message, ex.StackTrace)
- .SaveAsync();
- }
- }
- }
|