RedisServiceCollectionExtension.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using CSRedis;
  2. using Microsoft.Extensions.Caching.Distributed;
  3. using Microsoft.Extensions.Caching.Redis;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. namespace Fuel.Infrastructure.Extension
  8. {
  9. /// <summary>
  10. /// redis 扩展方法
  11. /// </summary>
  12. public static class RedisServiceCollectionExtension
  13. {
  14. public static IServiceCollection AddRedisClients(this IServiceCollection services, RedisOptions options)
  15. {
  16. var redisConfig = options;
  17. CSRedisClient redisClient = null;
  18. List<string> panams = new List<string>();
  19. if (redisConfig != null)
  20. {
  21. //暂时不支持多个数据库连接
  22. //var config = redis.FirstOrDefault();
  23. if (redisConfig.Sentinels != null && redisConfig.Sentinels.Any())
  24. {
  25. //"127.0.0.1:6379,password=123,defaultDatabase=13,prefix=key前辍"
  26. redisClient =
  27. new CSRedisClient(
  28. $"{redisConfig.ConnectionString},defaultDatabase={redisConfig.DataBase},prefix={redisConfig.PrefixKey}",
  29. redisConfig.Sentinels);
  30. }
  31. else
  32. {
  33. //"127.0.0.1:6379,password=123,defaultDatabase=13,prefix=key前辍"
  34. redisClient =
  35. new CSRedisClient(
  36. $"{redisConfig.ConnectionString},password={redisConfig.Password},defaultDatabase={redisConfig.DataBase},prefix={redisConfig.PrefixKey}");
  37. }
  38. }
  39. CoreRedisHelper.AddClient(options.KeyName, redisClient);
  40. if (CoreRedisHelper.redisHelpers.Any() && CoreRedisHelper.redisHelpers.Count <= 1)
  41. {
  42. RedisHelper.Initialization(redisClient);
  43. services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
  44. }
  45. return services;
  46. }
  47. /// <summary>
  48. /// 单个redis 兼容旧版本
  49. /// </summary>
  50. /// <param name="services"></param>
  51. /// <returns></returns>
  52. public static IServiceCollection UseRedisClient(this IServiceCollection services, RedisOptions redisOptions )
  53. {
  54. //var redisOptions = new RedisOptions();
  55. //configuration.GetSection("Redis").Get<RedisOptions>();
  56. services.AddRedisClients(redisOptions);
  57. return services;
  58. }
  59. /// <summary>
  60. /// 多个redis database 的问题
  61. /// </summary>
  62. /// <param name="services"></param>
  63. /// <returns></returns>
  64. public static IServiceCollection UseRedisClients(this IServiceCollection services,List<RedisOptions> redisClients)
  65. {
  66. if (redisClients.Any())
  67. {
  68. redisClients = redisClients.OrderByDescending(p => p.Default).ToList();
  69. foreach (var client in redisClients)
  70. {
  71. if (!string.IsNullOrWhiteSpace(client.KeyName))
  72. {
  73. services.AddRedisClients(client);
  74. }
  75. }
  76. }
  77. return services;
  78. }
  79. }
  80. }