YouTubeChannelCache.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Text.Json;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.YouTube;
  4. using StackExchange.Redis;
  5. namespace Infrastructure.YouTube;
  6. internal sealed class YouTubeChannelCache(IConnectionMultiplexer redis) : IYouTubeChannelCache
  7. {
  8. private static readonly TimeSpan CacheTtl = TimeSpan.FromHours(24);
  9. public async Task SetAsync(YouTubeChannelInfo info)
  10. {
  11. var db = redis.GetDatabase();
  12. var key = CacheKeys.YouTubeChannel(info.ChannelID);
  13. var json = JsonSerializer.Serialize(info);
  14. await db.StringSetAsync(key, json, CacheTtl);
  15. }
  16. public async Task<YouTubeChannelInfo?> GetAsync(string channelID)
  17. {
  18. var db = redis.GetDatabase();
  19. var key = CacheKeys.YouTubeChannel(channelID);
  20. var json = await db.StringGetAsync(key);
  21. if (json.IsNullOrEmpty)
  22. {
  23. return null;
  24. }
  25. return JsonSerializer.Deserialize<YouTubeChannelInfo>((string)json!);
  26. }
  27. public async Task<Dictionary<string, YouTubeChannelInfo>> GetManyAsync(IEnumerable<string> channelIds)
  28. {
  29. var db = redis.GetDatabase();
  30. var ids = channelIds.ToList();
  31. var keys = ids.Select(id => (RedisKey)CacheKeys.YouTubeChannel(id)).ToArray();
  32. var values = await db.StringGetAsync(keys);
  33. var result = new Dictionary<string, YouTubeChannelInfo>();
  34. for (var i = 0; i < ids.Count; i++)
  35. {
  36. if (!values[i].IsNullOrEmpty)
  37. {
  38. var info = JsonSerializer.Deserialize<YouTubeChannelInfo>((string)values[i]!);
  39. if (info is not null)
  40. {
  41. result[ids[i]] = info;
  42. }
  43. }
  44. }
  45. return result;
  46. }
  47. public async Task RemoveAsync(string channelID)
  48. {
  49. var db = redis.GetDatabase();
  50. var key = CacheKeys.YouTubeChannel(channelID);
  51. await db.KeyDeleteAsync(key);
  52. }
  53. }