StartupExtensions.cs 2.4 KB

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