TaobaoShortLinkCacheCore.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using dodohold.core;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace molilian.core
  5. {
  6. public static class TaobaoShortLinkCacheCore
  7. {
  8. public const int CacheExpireSeconds = 7 * 86400;
  9. public static async Task<string?> GetAsync(string shortUrl)
  10. {
  11. try
  12. {
  13. string longUrl = await CenterHub.Redis.GetAsync<string>(GetCacheKey(shortUrl));
  14. return IsLongUrl(longUrl) ? longUrl : null;
  15. }
  16. catch (Exception ex)
  17. {
  18. LogFailure("read", ex);
  19. return null;
  20. }
  21. }
  22. public static string? Get(string shortUrl)
  23. {
  24. try
  25. {
  26. string longUrl = CenterHub.Redis.Get<string>(GetCacheKey(shortUrl));
  27. return IsLongUrl(longUrl) ? longUrl : null;
  28. }
  29. catch (Exception ex)
  30. {
  31. LogFailure("read", ex);
  32. return null;
  33. }
  34. }
  35. public static async Task SaveAsync(string shortUrl, string longUrl)
  36. {
  37. if (!IsLongUrl(longUrl)) return;
  38. try
  39. {
  40. await CenterHub.Redis.SetAsync(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds);
  41. }
  42. catch (Exception ex)
  43. {
  44. LogFailure("write", ex);
  45. }
  46. }
  47. public static void Save(string shortUrl, string longUrl)
  48. {
  49. if (!IsLongUrl(longUrl)) return;
  50. try
  51. {
  52. CenterHub.Redis.Set(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds);
  53. }
  54. catch (Exception ex)
  55. {
  56. LogFailure("write", ex);
  57. }
  58. }
  59. private static bool IsLongUrl(string? url)
  60. {
  61. return Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
  62. (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
  63. !AlimamaPlus.IsShortLink(url!);
  64. }
  65. private static string GetCacheKey(string shortUrl)
  66. {
  67. string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(shortUrl.Trim())));
  68. return $"cache:taobao:short_link_http:v1:{hash}";
  69. }
  70. private static void LogFailure(string operation, Exception ex)
  71. {
  72. _ = new LoggerLibrary("taobao_short_link_cache", operation)
  73. .Info(ex.Message, ex.StackTrace)
  74. .SaveAsync();
  75. }
  76. }
  77. }