首頁  >  文章  >  後端開發  >  詳解StackExchange.Redis通用封裝類別分享

詳解StackExchange.Redis通用封裝類別分享

高洛峰
高洛峰原創
2017-02-08 09:30:171769瀏覽

前兩天朋友問我,有沒有使用過StackExchange.Redis,問我要個封裝類,由於之前都是使用ServiceStack.Redis,由於ServiceStack.Redis v4版本後是收費版的,所以現在也很有公司都在使用StackExchange.Redis而拋棄ServiceStack.Redis了。其實個人覺得,兩個驅動都不錯,只是因為ServiceStack.Redis收費導致目前很多公司都是基於V3版本的使用,也有人說V3版本有很多Bug,沒有維護和升級,不過至少目前我是沒發現Bug 。

不過ServiceStack.Redis同StackExchange.Redis比較,拋開收費的來說,確認比StackExchange.Redis 更有優勢。 StackExchange.Redis文檔很少,更不要說國內的文檔了,連github上面對應的介紹文檔都是很片面,這點我真的覺得StackExchange.Redis的作者至少要完善下文檔,很多都是要看源碼的例子才有。網路上對StackExchange.Redis的使用範例也比ServiceStack.Redis少很多,不是說沒人用,只是我查來查去,大部分都是基於String類型的資料進行使用的封裝類,對於List,SortedSet, Hash的封裝操作都很少,基本上都是東寫一點,西寫一點,很難找到完整的。在參考了一些文章和原始碼後,這裡提供一個自己封裝的類,基本提供對於各種類型的使用封裝,提供給大家學習使用,如果有哪裡寫的不好的,大家也可以互相交流。

ConnectionMultiplexer 封裝

首先是 ConnectionMultiplexer 的封裝,ConnectionMultiplexer物件是StackExchange.Redis最中樞的物件。這個類別的實例需要被整個應用程式域共享和重用的,所以不需要在每個操作中不停的創建該對象的實例,一般都是使用單例來創建和存放這個對象,這個在官網上也有說明。

/// <summary>
 /// ConnectionMultiplexer对象管理帮助类
 /// </summary>
 public static class RedisConnectionHelp
 {
  //系统自定义Key前缀
  public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";
 
  //"127.0.0.1:6379,allowadmin=true
  private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;
 
  private static readonly object Locker = new object();
  private static ConnectionMultiplexer _instance;
  private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();
 
  /// <summary>
  /// 单例获取
  /// </summary>
  public static ConnectionMultiplexer Instance
  {
   get
   {
    if (_instance == null)
    {
     lock (Locker)
     {
      if (_instance == null || !_instance.IsConnected)
      {
       _instance = GetManager();
      }
     }
    }
    return _instance;
   }
  }
 
  /// <summary>
  /// 缓存获取
  /// </summary>
  /// <param name="connectionString"></param>
  /// <returns></returns>
  public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
  {
   if (!ConnectionCache.ContainsKey(connectionString))
   {
    ConnectionCache[connectionString] = GetManager(connectionString);
   }
   return ConnectionCache[connectionString];
  }
 
  private static ConnectionMultiplexer GetManager(string connectionString = null)
  {
   connectionString = connectionString ?? RedisConnectionString;
   var connect = ConnectionMultiplexer.Connect(connectionString);
 
   //注册如下事件
   connect.ConnectionFailed += MuxerConnectionFailed;
   connect.ConnectionRestored += MuxerConnectionRestored;
   connect.ErrorMessage += MuxerErrorMessage;
   connect.ConfigurationChanged += MuxerConfigurationChanged;
   connect.HashSlotMoved += MuxerHashSlotMoved;
   connect.InternalError += MuxerInternalError;
 
   return connect;
  }
 
  #region 事件
 
  /// <summary>
  /// 配置更改时
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
  {
   Console.WriteLine("Configuration changed: " + e.EndPoint);
  }
 
  /// <summary>
  /// 发生错误时
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
  {
   Console.WriteLine("ErrorMessage: " + e.Message);
  }
 
  /// <summary>
  /// 重新建立连接之前的错误
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
  {
   Console.WriteLine("ConnectionRestored: " + e.EndPoint);
  }
 
  /// <summary>
  /// 连接失败 , 如果重新连接成功你将不会收到这个通知
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
  {
   Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
  }
 
  /// <summary>
  /// 更改集群
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
  {
   Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
  }
 
  /// <summary>
  /// redis类库错误
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
  {
   Console.WriteLine("InternalError:Message" + e.Exception.Message);
  }
 
  #endregion 事件
 }

RedisHelper 通用操作類別封

public class RedisHelper
 {
  private int DbNum { get; }
  private readonly ConnectionMultiplexer _conn;
  public string CustomKey;
 
  #region 构造函数
 
  public RedisHelper(int dbNum = 0)
    : this(dbNum, null)
  {
  }
 
  public RedisHelper(int dbNum, string readWriteHosts)
  {
   DbNum = dbNum;
   _conn =
    string.IsNullOrWhiteSpace(readWriteHosts) ?
    RedisConnectionHelp.Instance :
    RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
  }
 
#region 辅助方法
 
  private string AddSysCustomKey(string oldKey)
  {
   var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
   return prefixKey + oldKey;
  }
 
  private T Do<T>(Func<IDatabase, T> func)
  {
   var database = _conn.GetDatabase(DbNum);
   return func(database);
  }
 
  private string ConvertJson<T>(T value)
  {
   string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
   return result;
  }
 
  private T ConvertObj<T>(RedisValue value)
  {
   return JsonConvert.DeserializeObject<T>(value);
  }
 
  private List<T> ConvetList<T>(RedisValue[] values)
  {
   List<T> result = new List<T>();
   foreach (var item in values)
   {
    var model = ConvertObj<T>(item);
    result.Add(model);
   }
   return result;
  }
 
  private RedisKey[] ConvertRedisKeys(List<string> redisKeys)
  {
   return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
  }
 
  #endregion 辅助方法
 
  #endregion 构造函数
}

其中CustomKey用來表示系統前綴,AddSysCustomKey方法對每個key都進行前綴的添加處理,這裡推薦大家在命名redis的key的時候最好的加上前綴,並且使用:來分割前綴,這裡在使用視覺化工具查看的時候就比較好區分,例如我的前綴是Demo:test:(一般是  系統名稱:業務名稱:),然後你查看的時候你會發現整齊,好區分了很多

詳解StackExchange.Redis通用封裝類別分享

String類型的封裝

#region String
 
  #region 同步方法
 
  /// <summary>
  /// 保存单个key value
  /// </summary>
  /// <param name="key">Redis Key</param>
  /// <param name="value">保存的值</param>
  /// <param name="expiry">过期时间</param>
  /// <returns></returns>
  public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
  {
   key = AddSysCustomKey(key);
   return Do(db => db.StringSet(key, value, expiry));
  }
 
  /// <summary>
  /// 保存多个key value
  /// </summary>
  /// <param name="keyValues">键值对</param>
  /// <returns></returns>
  public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
  {
   List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
    keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
   return Do(db => db.StringSet(newkeyValues.ToArray()));
  }
 
  /// <summary>
  /// 保存一个对象
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="obj"></param>
  /// <param name="expiry"></param>
  /// <returns></returns>
  public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
  {
   key = AddSysCustomKey(key);
   string json = ConvertJson(obj);
   return Do(db => db.StringSet(key, json, expiry));
  }
 
  /// <summary>
  /// 获取单个key的值
  /// </summary>
  /// <param name="key">Redis Key</param>
  /// <returns></returns>
  public string StringGet(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.StringGet(key));
  }
 
  /// <summary>
  /// 获取多个Key
  /// </summary>
  /// <param name="listKey">Redis Key集合</param>
  /// <returns></returns>
  public RedisValue[] StringGet(List<string> listKey)
  {
   List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
   return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
  }
 
  /// <summary>
  /// 获取一个key的对象
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public T StringGet<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db => ConvertObj<T>(db.StringGet(key)));
  }
 
  /// <summary>
  /// 为数字增长val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="val">可以为负</param>
  /// <returns>增长后的值</returns>
  public double StringIncrement(string key, double val = 1)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.StringIncrement(key, val));
  }
 
  /// <summary>
  /// 为数字减少val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="val">可以为负</param>
  /// <returns>减少后的值</returns>
  public double StringDecrement(string key, double val = 1)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.StringDecrement(key, val));
  }
 
  #endregion 同步方法
 
  #region 异步方法
 
  /// <summary>
  /// 保存单个key value
  /// </summary>
  /// <param name="key">Redis Key</param>
  /// <param name="value">保存的值</param>
  /// <param name="expiry">过期时间</param>
  /// <returns></returns>
  public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.StringSetAsync(key, value, expiry));
  }
 
  /// <summary>
  /// 保存多个key value
  /// </summary>
  /// <param name="keyValues">键值对</param>
  /// <returns></returns>
  public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
  {
   List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
    keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
   return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
  }
 
  /// <summary>
  /// 保存一个对象
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="obj"></param>
  /// <param name="expiry"></param>
  /// <returns></returns>
  public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
  {
   key = AddSysCustomKey(key);
   string json = ConvertJson(obj);
   return await Do(db => db.StringSetAsync(key, json, expiry));
  }
 
  /// <summary>
  /// 获取单个key的值
  /// </summary>
  /// <param name="key">Redis Key</param>
  /// <returns></returns>
  public async Task<string> StringGetAsync(string key)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.StringGetAsync(key));
  }
 
  /// <summary>
  /// 获取多个Key
  /// </summary>
  /// <param name="listKey">Redis Key集合</param>
  /// <returns></returns>
  public async Task<RedisValue[]> StringGetAsync(List<string> listKey)
  {
   List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
   return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
  }
 
  /// <summary>
  /// 获取一个key的对象
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<T> StringGetAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   string result = await Do(db => db.StringGetAsync(key));
   return ConvertObj<T>(result);
  }
 
  /// <summary>
  /// 为数字增长val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="val">可以为负</param>
  /// <returns>增长后的值</returns>
  public async Task<double> StringIncrementAsync(string key, double val = 1)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.StringIncrementAsync(key, val));
  }
 
  /// <summary>
  /// 为数字减少val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="val">可以为负</param>
  /// <returns>减少后的值</returns>
  public async Task<double> StringDecrementAsync(string key, double val = 1)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.StringDecrementAsync(key, val));
  }
 
  #endregion 异步方法
 
  #endregion String

這裡說一下,StackExchange.Redis 中物件的儲存是不自帶序列化和反序列化的方法,所以在ConvertJson和ConvertObj裡面我是使用了JsonConvert來操作,如果需要換成其他的序列化和序列化,直接修改這兩個方面就好了,另外,StackExchange.Redis 相對於ServiceStack.Redis 來說提供了異步的方法,所以這裡也同樣封裝了異步和同步的方法。

List類型的封裝

#region List
 
  #region 同步方法
 
  /// <summary>
  /// 移除指定ListId的内部List的值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public void ListRemove<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   Do(db => db.ListRemove(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 获取指定key的List
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public List<T> ListRange<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(redis =>
   {
    var values = redis.ListRange(key);
    return ConvetList<T>(values);
   });
  }
 
  /// <summary>
  /// 入队
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public void ListRightPush<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   Do(db => db.ListRightPush(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 出队
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public T ListRightPop<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db =>
    {
     var value = db.ListRightPop(key);
     return ConvertObj<T>(value);
    });
  }
 
  /// <summary>
  /// 入栈
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public void ListLeftPush<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   Do(db => db.ListLeftPush(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 出栈
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public T ListLeftPop<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db =>
   {
    var value = db.ListLeftPop(key);
    return ConvertObj<T>(value);
   });
  }
 
  /// <summary>
  /// 获取集合中的数量
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public long ListLength(string key)
  {
   key = AddSysCustomKey(key);
   return Do(redis => redis.ListLength(key));
  }
 
  #endregion 同步方法
 
  #region 异步方法
 
  /// <summary>
  /// 移除指定ListId的内部List的值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public async Task<long> ListRemoveAsync<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 获取指定key的List
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<List<T>> ListRangeAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   var values = await Do(redis => redis.ListRangeAsync(key));
   return ConvetList<T>(values);
  }
 
  /// <summary>
  /// 入队
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public async Task<long> ListRightPushAsync<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 出队
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<T> ListRightPopAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   var value = await Do(db => db.ListRightPopAsync(key));
   return ConvertObj<T>(value);
  }
 
  /// <summary>
  /// 入栈
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public async Task<long> ListLeftPushAsync<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 出栈
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<T> ListLeftPopAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   var value = await Do(db => db.ListLeftPopAsync(key));
   return ConvertObj<T>(value);
  }
 
  /// <summary>
  /// 获取集合中的数量
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<long> ListLengthAsync(string key)
  {
   key = AddSysCustomKey(key);
   return await Do(redis => redis.ListLengthAsync(key));
  }
 
  #endregion 异步方法
 
  #endregion List

Hash類型的封裝

#region Hash
 
  #region 同步方法
 
  /// <summary>
  /// 判断某个数据是否已经被缓存
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public bool HashExists(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.HashExists(key, dataKey));
  }
 
  /// <summary>
  /// 存储数据到hash表
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="t"></param>
  /// <returns></returns>
  public bool HashSet<T>(string key, string dataKey, T t)
  {
   key = AddSysCustomKey(key);
   return Do(db =>
   {
    string json = ConvertJson(t);
    return db.HashSet(key, dataKey, json);
   });
  }
 
  /// <summary>
  /// 移除hash中的某值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public bool HashDelete(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.HashDelete(key, dataKey));
  }
 
  /// <summary>
  /// 移除hash中的多个值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKeys"></param>
  /// <returns></returns>
  public long HashDelete(string key, List<RedisValue> dataKeys)
  {
   key = AddSysCustomKey(key);
   //List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
   return Do(db => db.HashDelete(key, dataKeys.ToArray()));
  }
 
  /// <summary>
  /// 从hash表获取数据
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public T HashGet<T>(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   return Do(db =>
   {
    string value = db.HashGet(key, dataKey);
    return ConvertObj<T>(value);
   });
  }
 
  /// <summary>
  /// 为数字增长val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="val">可以为负</param>
  /// <returns>增长后的值</returns>
  public double HashIncrement(string key, string dataKey, double val = 1)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.HashIncrement(key, dataKey, val));
  }
 
  /// <summary>
  /// 为数字减少val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="val">可以为负</param>
  /// <returns>减少后的值</returns>
  public double HashDecrement(string key, string dataKey, double val = 1)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.HashDecrement(key, dataKey, val));
  }
 
  /// <summary>
  /// 获取hashkey所有Redis key
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public List<T> HashKeys<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db =>
   {
    RedisValue[] values = db.HashKeys(key);
    return ConvetList<T>(values);
   });
  }
 
  #endregion 同步方法
 
  #region 异步方法
 
  /// <summary>
  /// 判断某个数据是否已经被缓存
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public async Task<bool> HashExistsAsync(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.HashExistsAsync(key, dataKey));
  }
 
  /// <summary>
  /// 存储数据到hash表
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="t"></param>
  /// <returns></returns>
  public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
  {
   key = AddSysCustomKey(key);
   return await Do(db =>
   {
    string json = ConvertJson(t);
    return db.HashSetAsync(key, dataKey, json);
   });
  }
 
  /// <summary>
  /// 移除hash中的某值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public async Task<bool> HashDeleteAsync(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.HashDeleteAsync(key, dataKey));
  }
 
  /// <summary>
  /// 移除hash中的多个值
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKeys"></param>
  /// <returns></returns>
  public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
  {
   key = AddSysCustomKey(key);
   //List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
   return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
  }
 
  /// <summary>
  /// 从hash表获取数据
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <returns></returns>
  public async Task<T> HashGeAsync<T>(string key, string dataKey)
  {
   key = AddSysCustomKey(key);
   string value = await Do(db => db.HashGetAsync(key, dataKey));
   return ConvertObj<T>(value);
  }
 
  /// <summary>
  /// 为数字增长val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="val">可以为负</param>
  /// <returns>增长后的值</returns>
  public async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.HashIncrementAsync(key, dataKey, val));
  }
 
  /// <summary>
  /// 为数字减少val
  /// </summary>
  /// <param name="key"></param>
  /// <param name="dataKey"></param>
  /// <param name="val">可以为负</param>
  /// <returns>减少后的值</returns>
  public async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1)
  {
   key = AddSysCustomKey(key);
   return await Do(db => db.HashDecrementAsync(key, dataKey, val));
  }
 
  /// <summary>
  /// 获取hashkey所有Redis key
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<List<T>> HashKeysAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   RedisValue[] values = await Do(db => db.HashKeysAsync(key));
   return ConvetList<T>(values);
  }
 
  #endregion 异步方法
 
  #endregion Hash

SortedSet 類型的封裝

#region SortedSet 有序集合
 
  #region 同步方法
 
  /// <summary>
  /// 添加
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  /// <param name="score"></param>
  public bool SortedSetAdd<T>(string key, T value, double score)
  {
   key = AddSysCustomKey(key);
   return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score));
  }
 
  /// <summary>
  /// 删除
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public bool SortedSetRemove<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 获取全部
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public List<T> SortedSetRangeByRank<T>(string key)
  {
   key = AddSysCustomKey(key);
   return Do(redis =>
   {
    var values = redis.SortedSetRangeByRank(key);
    return ConvetList<T>(values);
   });
  }
 
  /// <summary>
  /// 获取集合中的数量
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public long SortedSetLength(string key)
  {
   key = AddSysCustomKey(key);
   return Do(redis => redis.SortedSetLength(key));
  }
 
  #endregion 同步方法
 
  #region 异步方法
 
  /// <summary>
  /// 添加
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  /// <param name="score"></param>
  public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score)
  {
   key = AddSysCustomKey(key);
   return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score));
  }
 
  /// <summary>
  /// 删除
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  public async Task<bool> SortedSetRemoveAsync<T>(string key, T value)
  {
   key = AddSysCustomKey(key);
   return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
  }
 
  /// <summary>
  /// 获取全部
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key)
  {
   key = AddSysCustomKey(key);
   var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
   return ConvetList<T>(values);
  }
 
  /// <summary>
  /// 获取集合中的数量
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public async Task<long> SortedSetLengthAsync(string key)
  {
   key = AddSysCustomKey(key);
   return await Do(redis => redis.SortedSetLengthAsync(key));
  }
 
  #endregion 异步方法
 
  #endregion SortedSet 有序集合

key的管理

#region key
 
  /// <summary>
  /// 删除单个key
  /// </summary>
  /// <param name="key">redis key</param>
  /// <returns>是否删除成功</returns>
  public bool KeyDelete(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.KeyDelete(key));
  }
 
  /// <summary>
  /// 删除多个key
  /// </summary>
  /// <param name="keys">rediskey</param>
  /// <returns>成功删除的个数</returns>
  public long KeyDelete(List<string> keys)
  {
   List<string> newKeys = keys.Select(AddSysCustomKey).ToList();
   return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
  }
 
  /// <summary>
  /// 判断key是否存储
  /// </summary>
  /// <param name="key">redis key</param>
  /// <returns></returns>
  public bool KeyExists(string key)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.KeyExists(key));
  }
 
  /// <summary>
  /// 重新命名key
  /// </summary>
  /// <param name="key">就的redis key</param>
  /// <param name="newKey">新的redis key</param>
  /// <returns></returns>
  public bool KeyRename(string key, string newKey)
  {
   key = AddSysCustomKey(key);
   return Do(db => db.KeyRename(key, newKey));
  }
 
  /// <summary>
  /// 设置Key的时间
  /// </summary>
  /// <param name="key">redis key</param>
  /// <param name="expiry"></param>
  /// <returns></returns>
  public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
  {
   key = AddSysCustomKey(key);
   return Do(db => db.KeyExpire(key, expiry));
  }
 
  #endregion key

發布和訂閱對以上的通用操作和訂閱對以上; ,提供給大家學習參考,如果有哪裡寫錯的,也希望能一起交流。

問題:

StackExchange.Redis沒有提供Redis分散式鎖定的操作麼? ServiceStack.Redis 提供了AcquireLock 的方法來操作,StackExchange.Redis 原始碼中只找到了LockTake的方法,並沒有找到其他的方法了,如果有人使用過,還希望能提供下。

更多詳解StackExchange.Redis通用封裝類分享相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn