| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using dodohold.core;
- using System.Security.Cryptography;
- using System.Text;
- namespace molilian.core
- {
- public static class TaobaoShortLinkCacheCore
- {
- // 短链每次走 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(Hash(shortUrl)));
- return IsLongUrl(longUrl) ? longUrl : null;
- }
- catch (Exception ex)
- {
- LogFailure("read", ex);
- return null;
- }
- }
- public static string? Get(string shortUrl)
- {
- try
- {
- string longUrl = CenterHub.Redis.Get<string>(GetCacheKey(Hash(shortUrl)));
- return IsLongUrl(longUrl) ? longUrl : null;
- }
- catch (Exception ex)
- {
- LogFailure("read", ex);
- return null;
- }
- }
- public static async Task SaveAsync(string shortUrl, string longUrl)
- {
- if (!IsLongUrl(longUrl)) return;
- try
- {
- 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)
- {
- LogFailure("write", ex);
- }
- }
- public static void Save(string shortUrl, string longUrl)
- {
- if (!IsLongUrl(longUrl)) return;
- try
- {
- 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)
- {
- LogFailure("write", ex);
- }
- }
- private static bool IsLongUrl(string? url)
- {
- return Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
- (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
- !AlimamaPlus.IsShortLink(url!);
- }
- // 取 SHA256 前 8 字节(16 位十六进制),压缩 key 占用,碰撞概率可忽略
- private static string Hash(string shortUrl)
- {
- 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)
- .Info(ex.Message, ex.StackTrace)
- .SaveAsync();
- }
- }
- }
|