StartupExtensions.cs 2.5 KB

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