CacheResource.cs 2.2 KB

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