12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using Cksoft.Unity;
- using StackExchange.Redis;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
- namespace DllEapCommon.Redis
- {
- public class RedisHelper : IDisposable
- {
- //连接字符串
- private string _connectionString;
- //实例名称
- private string _instanceName;
- //默认数据库
- private int _defaultDB;
- private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
- public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
- {
- _connectionString = connectionString;
- _instanceName = instanceName;
- _defaultDB = defaultDB;
- _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
- }
- /// <summary>
- /// 获取ConnectionMultiplexer
- /// </summary>
- /// <returns></returns>
- private ConnectionMultiplexer GetConnect()
- {
- return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
- }
- /// <summary>
- /// 获取数据库
- /// </summary>
- /// <param name="configName"></param>
- /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
- /// <returns></returns>
- public IDatabase GetDatabase()
- {
- return GetConnect().GetDatabase(_defaultDB);
- }
- public IServer GetServer(string configName = null, int endPointsIndex = 0)
- {
- var confOption = ConfigurationOptions.Parse(_connectionString);
- return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
- }
- public ISubscriber GetSubscriber(string configName = null)
- {
- return GetConnect().GetSubscriber();
- }
- public async Task<bool> SetHashValue(string key, IEnumerable<BaseEntity> datas)
- {
- var dbClient = GetDatabase();
- foreach (var item in datas)
- {
- var keyVals = GetEntityKeyVals(item);
- foreach (var kv in keyVals)
- {
-
- }
- }
- return true;
- }
- public IEnumerable<EntityKeyVal> GetEntityKeyVals<T>(T entity) where T : class, new()
- {
- var type = typeof(T);
- var pis = type.GetProperties(System.Reflection.BindingFlags.Public);
- var list = new List<EntityKeyVal>();
- foreach (var item in pis)
- {
- var value = item.GetValue(entity);
- list.Add(new EntityKeyVal { Key = item.Name, Value = value });
- }
- return list;
- }
- public void Dispose()
- {
- if (_connections != null && _connections.Count > 0)
- {
- foreach (var item in _connections.Values)
- {
- item.Close();
- }
- }
- }
- }
- }
|