RedisHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using Cksoft.Unity;
  2. using StackExchange.Redis;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace DllEapCommon.Redis
  9. {
  10. public class RedisHelper : IDisposable
  11. {
  12. //连接字符串
  13. private string _connectionString;
  14. //实例名称
  15. private string _instanceName;
  16. //默认数据库
  17. private int _defaultDB;
  18. private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
  19. public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
  20. {
  21. _connectionString = connectionString;
  22. _instanceName = instanceName;
  23. _defaultDB = defaultDB;
  24. _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
  25. }
  26. /// <summary>
  27. /// 获取ConnectionMultiplexer
  28. /// </summary>
  29. /// <returns></returns>
  30. private ConnectionMultiplexer GetConnect()
  31. {
  32. return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
  33. }
  34. /// <summary>
  35. /// 获取数据库
  36. /// </summary>
  37. /// <param name="configName"></param>
  38. /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
  39. /// <returns></returns>
  40. public IDatabase GetDatabase()
  41. {
  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 async Task<bool> SetHashValue(string key, IEnumerable<BaseEntity> datas)
  54. {
  55. var dbClient = GetDatabase();
  56. foreach (var item in datas)
  57. {
  58. var keyVals = GetEntityKeyVals(item);
  59. foreach (var kv in keyVals)
  60. {
  61. }
  62. }
  63. return true;
  64. }
  65. public IEnumerable<EntityKeyVal> GetEntityKeyVals<T>(T entity) where T : class, new()
  66. {
  67. var type = typeof(T);
  68. var pis = type.GetProperties(System.Reflection.BindingFlags.Public);
  69. var list = new List<EntityKeyVal>();
  70. foreach (var item in pis)
  71. {
  72. var value = item.GetValue(entity);
  73. list.Add(new EntityKeyVal { Key = item.Name, Value = value });
  74. }
  75. return list;
  76. }
  77. public void Dispose()
  78. {
  79. if (_connections != null && _connections.Count > 0)
  80. {
  81. foreach (var item in _connections.Values)
  82. {
  83. item.Close();
  84. }
  85. }
  86. }
  87. }
  88. }