RedisHelper.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using StackExchange.Redis;
  2. using System;
  3. using System.Collections.Concurrent;
  4. namespace RedisDemo
  5. {
  6. public class RedisHelper : IDisposable
  7. {
  8. //连接字符串
  9. private string _connectionString;
  10. //实例名称
  11. private string _instanceName;
  12. //默认数据库
  13. private int _defaultDB;
  14. private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
  15. public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
  16. {
  17. _connectionString = connectionString;
  18. _instanceName = instanceName;
  19. _defaultDB = defaultDB;
  20. _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
  21. }
  22. /// <summary>
  23. /// 获取ConnectionMultiplexer
  24. /// </summary>
  25. /// <returns></returns>
  26. private ConnectionMultiplexer GetConnect()
  27. {
  28. return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
  29. }
  30. /// <summary>
  31. /// 获取数据库
  32. /// </summary>
  33. /// <param name="configName"></param>
  34. /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
  35. /// <returns></returns>
  36. public IDatabase GetDatabase()
  37. {
  38. var connectStr = _connectionString;
  39. var conmper = ConnectionMultiplexer.Connect(connectStr);
  40. var database = conmper.GetDatabase(0);
  41. return database;
  42. //return GetConnect().GetDatabase(_defaultDB);
  43. }
  44. public IServer GetServer(string configName = null, int endPointsIndex = 0)
  45. {
  46. var confOption = ConfigurationOptions.Parse(_connectionString);
  47. return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
  48. }
  49. public ISubscriber GetSubscriber(string configName = null)
  50. {
  51. return GetConnect().GetSubscriber();
  52. }
  53. public void Dispose()
  54. {
  55. if (_connections != null && _connections.Count > 0)
  56. {
  57. foreach (var item in _connections.Values)
  58. {
  59. item.Close();
  60. }
  61. }
  62. }
  63. }
  64. }