程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 詳解StackExchange.Redis通用封裝類分享

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

編輯:C#入門知識

詳解StackExchange.Redis通用封裝類分享。本站提示廣大學習愛好者:(詳解StackExchange.Redis通用封裝類分享)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解StackExchange.Redis通用封裝類分享正文


前兩天冤家問我,有沒有運用過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:(普通是  零碎名:業務名:),然後你檢查的時分你會發現劃一,好區分了很多

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

發布和訂閱

#region 發布訂閱

  /// <summary>
  /// Redis發布訂閱 訂閱
  /// </summary>
  /// <param name="subChannel"></param>
  /// <param name="handler"></param>
  public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
  {
   ISubscriber sub = _conn.GetSubscriber();
   sub.Subscribe(subChannel, (channel, message) =>
   {
    if (handler == null)
    {
     Console.WriteLine(subChannel + " 訂閱收到音訊:" + message);
    }
    else
    {
     handler(channel, message);
    }
   });
  }

  /// <summary>
  /// Redis發布訂閱 發布
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="channel"></param>
  /// <param name="msg"></param>
  /// <returns></returns>
  public long Publish<T>(string channel, T msg)
  {
   ISubscriber sub = _conn.GetSubscriber();
   return sub.Publish(channel, ConvertJson(msg));
  }

  /// <summary>
  /// Redis發布訂閱 取消訂閱
  /// </summary>
  /// <param name="channel"></param>
  public void Unsubscribe(string channel)
  {
   ISubscriber sub = _conn.GetSubscriber();
   sub.Unsubscribe(channel);
  }

  /// <summary>
  /// Redis發布訂閱 取消全部訂閱
  /// </summary>
  public void UnsubscribeAll()
  {
   ISubscriber sub = _conn.GetSubscriber();
   sub.UnsubscribeAll();
  }

  #endregion 發布訂閱

其他

#region 其他

  public ITransaction CreateTransaction()
  {
   return GetDatabase().CreateTransaction();
  }

  public IDatabase GetDatabase()
  {
   return _conn.GetDatabase(DbNum);
  }

  public IServer GetServer(string hostAndPort)
  {
   return _conn.GetServer(hostAndPort);
  }

  /// <summary>
  /// 設置前綴
  /// </summary>
  /// <param name="customKey"></param>
  public void SetSysCustomKey(string customKey)
  {
   CustomKey = customKey;
  }

  #endregion 其他

以上就是對StackExchange.Redis根本操作的通用封裝,提供應大家學習參考,假如有哪裡寫錯的,也希望能一同交流。

問題:

StackExchange.Redis沒有提供Redis散布式鎖的操作麼?ServiceStack.Redis 提供了AcquireLock 的辦法來操作,StackExchange.Redis 源碼中只找到了LockTake的辦法,並沒有找到其他的辦法了,假如有人運用過,還希望能提供下。

最後,附上源碼地址:demo

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved