CacheResource.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Caching.Memory;
  7. using Benchmarks.Model;
  8. using GenHTTP.Modules.Webservices;
  9. namespace Benchmarks.Tests
  10. {
  11. public sealed class CacheResource
  12. {
  13. private static readonly Random _Random = new Random();
  14. private readonly MemoryCache _Cache = new MemoryCache(new MemoryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMinutes(60) });
  15. private static readonly object[] _CacheKeys = Enumerable.Range(0, 10001).Select((i) => new CacheKey(i)).ToArray();
  16. public sealed class CacheKey : IEquatable<CacheKey>
  17. {
  18. private readonly int _value;
  19. public CacheKey(int value) => _value = value;
  20. public bool Equals(CacheKey key) => key._value == _value;
  21. public override bool Equals(object obj) => ReferenceEquals(obj, this);
  22. public override int GetHashCode() => _value;
  23. public override string ToString() => _value.ToString();
  24. }
  25. [ResourceMethod(":queries")]
  26. public ValueTask<List<World>> GetWorldsFromPath(string queries) => GetWorlds(queries);
  27. [ResourceMethod]
  28. public async ValueTask<List<World>> GetWorlds(string queries)
  29. {
  30. var count = 1;
  31. int.TryParse(queries, out count);
  32. if (count < 1) count = 1;
  33. else if (count > 500) count = 500;
  34. var result = new List<World>(count);
  35. using var context = DatabaseContext.CreateNoTracking();
  36. for (var i = 0; i < count; i++)
  37. {
  38. var id = _Random.Next(1, 10001);
  39. var key = _CacheKeys[id];
  40. var data = _Cache.Get<World>(key);
  41. if (data != null)
  42. {
  43. result.Add(data);
  44. }
  45. else
  46. {
  47. var resolved = await context.World.FirstOrDefaultAsync(w => w.Id == id);
  48. _Cache.Set(key, resolved);
  49. result.Add(resolved);
  50. }
  51. }
  52. return result;
  53. }
  54. }
  55. }