| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using dodohold.core;
- using System.Security.Cryptography;
- using System.Text;
- namespace molilian.core
- {
- public static class TaobaoShortLinkCacheCore
- {
- public const int CacheExpireSeconds = 7 * 86400;
- public static async Task<string?> GetAsync(string shortUrl)
- {
- try
- {
- string longUrl = await CenterHub.Redis.GetAsync<string>(GetCacheKey(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(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
- {
- await CenterHub.Redis.SetAsync(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds);
- }
- catch (Exception ex)
- {
- LogFailure("write", ex);
- }
- }
- public static void Save(string shortUrl, string longUrl)
- {
- if (!IsLongUrl(longUrl)) return;
- try
- {
- CenterHub.Redis.Set(GetCacheKey(shortUrl), 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!);
- }
- private static string GetCacheKey(string shortUrl)
- {
- string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(shortUrl.Trim())));
- return $"cache:taobao:short_link_http:v1:{hash}";
- }
- private static void LogFailure(string operation, Exception ex)
- {
- _ = new LoggerLibrary("taobao_short_link_cache", operation)
- .Info(ex.Message, ex.StackTrace)
- .SaveAsync();
- }
- }
- }
|