StartupExtensions.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Text.Json;
  2. using System.Text.Json.Serialization;
  3. using CacheManager.Core;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using XF.Domain.Cache;
  6. namespace Hotline.CacheManager
  7. {
  8. public static class StartupExtensions
  9. {
  10. public static IServiceCollection AddCache(this IServiceCollection services, Action<CacheOptions> action)
  11. {
  12. var options = new CacheOptions();
  13. action(options);
  14. services.AddCacheManagerConfiguration(cfg =>
  15. {
  16. cfg
  17. .WithUpdateMode(CacheUpdateMode.Up)
  18. .WithMicrosoftMemoryCacheHandle()
  19. .And
  20. .WithRedisConfiguration("redis", options.ConnectionString, 1)
  21. // .WithRedisConfiguration("redis", d =>
  22. //{
  23. // d.WithDatabase(0).WithEndpoint("redis.fengwo.com", 6380);
  24. //})
  25. .WithSerializer(typeof(SystemTextJsonSerializer), new JsonSerializerOptions
  26. {
  27. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  28. DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
  29. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
  30. })
  31. .WithRedisBackplane("redis")
  32. .WithRedisCacheHandle("redis", true);
  33. //cfg.AddCacheEvents(services);
  34. })
  35. .AddCacheManager()
  36. .Configure(action)
  37. .AddSingleton(typeof(ITypedCache<>), typeof(DefaultTypedCache<>))
  38. ;
  39. return services;
  40. }
  41. }
  42. public class CacheOptions
  43. {
  44. public string ConnectionString { get; set; }
  45. public int Port { get; set; }
  46. public string Prefix { get; set; }
  47. public bool EnableKeyspaceNotifications { get; set; }
  48. }
  49. }