StartupExtensions.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using EasyCaching.Core.Configurations;
  2. using EasyCaching.Serialization.SystemTextJson.Configurations;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using XF.Domain.Cache;
  5. using XF.Domain.Queues;
  6. namespace XF.EasyCaching
  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.AddEasyCaching(d =>
  15. {
  16. d.WithSystemTextJson("xjson");
  17. // local
  18. d.UseInMemory("m1");
  19. d.UseRedis(config =>
  20. {
  21. config.DBConfig.Endpoints.Add(new ServerEndPoint(options.Host, options.Port));
  22. config.DBConfig.Database = options.Database;
  23. config.DBConfig.Password = options.Password;
  24. config.SerializerName = "xjson";
  25. }, "r1");
  26. // combine local and distributed
  27. d.UseHybrid(config =>
  28. {
  29. config.TopicName = options.TopicName;
  30. config.EnableLogging = false;
  31. // specify the local cache provider name after v0.5.4
  32. config.LocalCacheProviderName = "m1";
  33. // specify the distributed cache provider name after v0.5.4
  34. config.DistributedCacheProviderName = "r1";
  35. }, "h1")
  36. // use redis bus
  37. .WithRedisBus(busConf =>
  38. {
  39. busConf.Endpoints.Add(new ServerEndPoint(options.Host, options.Port));
  40. busConf.Password = options.Password;
  41. // do not forget to set the SerializerName for the bus here !!
  42. busConf.SerializerName = "xjson";
  43. });
  44. })
  45. .Configure(action)
  46. .AddSingleton(typeof(ITypedCache<>), typeof(DefaultTypedCache<>))
  47. .AddSingleton(typeof(IQueue), typeof(DistributedQueue))
  48. ;
  49. return services;
  50. }
  51. }
  52. public class CacheOptions
  53. {
  54. public string Host { get; set; }
  55. public int Port { get; set; }
  56. public string Password { get; set; }
  57. public int Database { get; set; } = 1;
  58. public string Prefix { get; set; }
  59. public int MaxRdSecond { get; set; }
  60. public string TopicName { get; set; }
  61. }
  62. }