序言
本篇從.Net如何接入Reis開始,直至.Net對Redis的各種操作,為了方便學習與做為文件的檢視,我做一遍註釋展現,其中會對list的阻塞功能和事務的運用做二個案例,進行記錄學習。
Redis官方推薦的.NET驅動類庫為Service.Stack.Redis。然而網上對這個類庫的中文文件不是很全面與合理,這篇文章主要就對這個類庫做註釋展現。不足遺漏之處還望見諒,海涵。
.Net使用Redis是非常方便與快捷與簡單的,下面就讓我展示下吧。
這裡有必要說一下,如果你對Redis 中的基本物件資料型別還不瞭解,建議你看下我的前幾篇Redis文章,保證要到病除。點選:我的Redis系列文章
專案中安裝下載Service.Stack.Redis類庫
右擊專案->管理NuGet程式包->在聯機中輸入Reis就能出現這個類庫,然後新增引入就行啦。
.Net連結Redis資料庫,支援讀寫分離
1、配置檔案
public sealed class RedisConfig : ConfigurationSection { public static RedisConfig GetConfig() { RedisConfig section = GetConfig("RedisConfig"); return section; } public static RedisConfig GetConfig(string sectionName) { RedisConfig section = (RedisConfig)ConfigurationManager.GetSection(sectionName); if (section == null) throw new ConfigurationErrorsException("Section " + sectionName + " is not found."); return section; } /// <summary> /// 可寫的Redis連結地址 /// </summary> [ConfigurationProperty("WriteServerConStr", IsRequired = false)] public string WriteServerConStr { get { return (string)base["WriteServerConStr"]; } set { base["WriteServerConStr"] = value; } } /// <summary> /// 可讀的Redis連結地址 /// </summary> [ConfigurationProperty("ReadServerConStr", IsRequired = false)] public string ReadServerConStr { get { return (string)base["ReadServerConStr"]; } set { base["ReadServerConStr"] = value; } } /// <summary> /// 最大寫連結數 /// </summary> [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)] public int MaxWritePoolSize { get { int _maxWritePoolSize = (int)base["MaxWritePoolSize"]; return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5; } set { base["MaxWritePoolSize"] = value; } } /// <summary> /// 最大讀連結數 /// </summary> [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)] public int MaxReadPoolSize { get { int _maxReadPoolSize = (int)base["MaxReadPoolSize"]; return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5; } set { base["MaxReadPoolSize"] = value; } } /// <summary> /// 自動重啟 /// </summary> [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)] public bool AutoStart { get { return (bool)base["AutoStart"]; } set { base["AutoStart"] = value; } } /// <summary> /// 本地快取到期時間,單位:秒 /// </summary> [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)] public int LocalCacheTime { get { return (int)base["LocalCacheTime"]; } set { base["LocalCacheTime"] = value; } } /// <summary> /// 是否記錄日誌,該設定僅用於排查redis執行時出現的問題,如redis工作正常,請關閉該項 /// </summary> [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)] public bool RecordeLog { get { return (bool)base["RecordeLog"]; } set { base["RecordeLog"] = value; } } }
2、配置Redis連結
public class RedisManager { /// <summary> /// redis配置檔案資訊 /// </summary> private static RedisConfig RedisConfig = RedisConfig.GetConfig(); private static PooledRedisClientManager prcm; /// <summary> /// 靜態構造方法,初始化連結池管理物件 /// </summary> static RedisManager() { CreateManager(); } /// <summary> /// 建立連結池管理物件 /// </summary> private static void CreateManager() { string[] WriteServerConStr = SplitString(RedisConfig.WriteServerConStr, ","); string[] ReadServerConStr = SplitString(RedisConfig.ReadServerConStr, ","); prcm = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr, new RedisClientManagerConfig { MaxWritePoolSize = RedisConfig.MaxWritePoolSize, MaxReadPoolSize = RedisConfig.MaxReadPoolSize, AutoStart = RedisConfig.AutoStart, }); } private static string[] SplitString(string strSource, string split) { return strSource.Split(split.ToArray()); } /// <summary> /// 客戶端快取操作物件 /// </summary> public static IRedisClient GetClient() { if (prcm == null) CreateManager(); return prcm.GetClient(); } }
3、IRedisClient為操作Redis的介面,是.Net操作Redis的主要類庫,這裡我們把它接入
/// <summary> /// RedisBase類,是redis操作的基類,繼承自IDisposable介面,主要用於釋放記憶體 /// </summary> public abstract class RedisBase : IDisposable { public static IRedisClient Core { get; private set; } private bool _disposed = false; static RedisBase() { Core = RedisManager.GetClient(); } protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { Core.Dispose(); Core = null; } } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// 儲存資料DB檔案到硬碟 /// </summary> public void Save() { Core.Save(); } /// <summary> /// 非同步儲存資料DB檔案到硬碟 /// </summary> public void SaveAsync() { Core.SaveAsync(); } }
.Net操作Redis資料型別String
public class DoRedisString : DoRedisBase { #region 賦值 /// <summary> /// 設定key的value /// </summary> public bool Set(string key, string value) { return RedisBase.Core.Set<string>(key, value); } /// <summary> /// 設定key的value並設定過期時間 /// </summary> public bool Set(string key, string value, DateTime dt) { return RedisBase.Core.Set<string>(key, value, dt); } /// <summary> /// 設定key的value並設定過期時間 /// </summary> public bool Set(string key, string value, TimeSpan sp) { return RedisBase.Core.Set<string>(key, value, sp); } /// <summary> /// 設定多個key/value /// </summary> public void Set(Dictionary<string, string> dic) { RedisBase.Core.SetAll(dic); } #endregion #region 追加 /// <summary> /// 在原有key的value值之後追加value /// </summary> public long Append(string key, string value) { return RedisBase.Core.AppendToValue(key, value); } #endregion #region 獲取值 /// <summary> /// 獲取key的value值 /// </summary> public string Get(string key) { return RedisBase.Core.GetValue(key); } /// <summary> /// 獲取多個key的value值 /// </summary> public List<string> Get(List<string> keys) { return RedisBase.Core.GetValues(keys); } /// <summary> /// 獲取多個key的value值 /// </summary> public List<T> Get<T>(List<string> keys) { return RedisBase.Core.GetValues<T>(keys); } #endregion #region 獲取舊值賦上新值 /// <summary> /// 獲取舊值賦上新值 /// </summary> public string GetAndSetValue(string key, string value) { return RedisBase.Core.GetAndSetValue(key, value); } #endregion #region 輔助方法 /// <summary> /// 獲取值的長度 /// </summary> public long GetCount(string key) { return RedisBase.Core.GetStringCount(key); } /// <summary> /// 自增1,返回自增後的值 /// </summary> public long Incr(string key) { return RedisBase.Core.IncrementValue(key); } /// <summary> /// 自增count,返回自增後的值 /// </summary> public double IncrBy(string key, double count) { return RedisBase.Core.IncrementValueBy(key, count); } /// <summary> /// 自減1,返回自減後的值 /// </summary> public long Decr(string key) { return RedisBase.Core.DecrementValue(key); } /// <summary> /// 自減count ,返回自減後的值 /// </summary> /// <param name="key"></param> /// <param name="count"></param> /// <returns></returns> public long DecrBy(string key, int count) { return RedisBase.Core.DecrementValueBy(key, count); } #endregion }
.Net操作Redis資料型別List
public class DoRedisList:DoRedisBase { #region 賦值 /// <summary> /// 從左側向list中新增值 /// </summary> public void LPush(string key,string value) { RedisBase.Core.PushItemToList(key,value); } /// <summary> /// 從左側向list中新增值,並設定過期時間 /// </summary> public void LPush(string key, string value,DateTime dt) { RedisBase.Core.PushItemToList(key, value); RedisBase.Core.ExpireEntryAt(key,dt); } /// <summary> /// 從左側向list中新增值,設定過期時間 /// </summary> public void LPush(string key, string value, TimeSpan sp) { RedisBase.Core.PushItemToList(key, value); RedisBase.Core.ExpireEntryIn(key, sp); } /// <summary> /// 從左側向list中新增值 /// </summary> public void RPush(string key, string value) { RedisBase.Core.PrependItemToList(key,value); } /// <summary> /// 從右側向list中新增值,並設定過期時間 /// </summary> public void RPush(string key, string value, DateTime dt) { RedisBase.Core.PrependItemToList(key, value); RedisBase.Core.ExpireEntryAt(key, dt); } /// <summary> /// 從右側向list中新增值,並設定過期時間 /// </summary> public void RPush(string key, string value, TimeSpan sp) { RedisBase.Core.PrependItemToList(key, value); RedisBase.Core.ExpireEntryIn(key, sp); } /// <summary> /// 新增key/value /// </summary> public void Add(string key, string value) { RedisBase.Core.AddItemToList(key,value); } /// <summary> /// 新增key/value ,並設定過期時間 /// </summary> public void Add(string key, string value,DateTime dt) { RedisBase.Core.AddItemToList(key, value); RedisBase.Core.ExpireEntryAt(key,dt); } /// <summary> /// 新增key/value。並新增過期時間 /// </summary> public void Add(string key, string value,TimeSpan sp) { RedisBase.Core.AddItemToList(key, value); RedisBase.Core.ExpireEntryIn(key,sp); } /// <summary> /// 為key新增多個值 /// </summary> public void Add(string key, List<string> values) { RedisBase.Core.AddRangeToList(key,values); } /// <summary> /// 為key新增多個值,並設定過期時間 /// </summary> public void Add(string key, List<string> values,DateTime dt) { RedisBase.Core.AddRangeToList(key, values); RedisBase.Core.ExpireEntryAt(key,dt); } /// <summary> /// 為key新增多個值,並設定過期時間 /// </summary> public void Add(string key, List<string> values,TimeSpan sp) { RedisBase.Core.AddRangeToList(key, values); RedisBase.Core.ExpireEntryIn(key,sp); } #endregion #region 獲取值 /// <summary> /// 獲取list中key包含的資料數量 /// </summary> public long Count(string key) { return RedisBase.Core.GetListCount(key); } /// <summary> /// 獲取key包含的所有資料集合 /// </summary> public List<string> Get(string key) { return RedisBase.Core.GetAllItemsFromList(key); } /// <summary> /// 獲取key中下標為star到end的值集合 /// </summary> public List<string> Get(string key,int star,int end) { return RedisBase.Core.GetRangeFromList(key,star,end); } #endregion #region 阻塞命令 /// <summary> /// 阻塞命令:從list中keys的尾部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public string BlockingPopItemFromList(string key,TimeSpan? sp) { return RedisBase.Core.BlockingDequeueItemFromList(key,sp); } /// <summary> /// 阻塞命令:從list中keys的尾部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public ItemRef BlockingPopItemFromLists(string[] keys, TimeSpan? sp) { return RedisBase.Core.BlockingPopItemFromLists(keys, sp); } /// <summary> /// 阻塞命令:從list中keys的尾部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public string BlockingDequeueItemFromList(string key, TimeSpan? sp) { return RedisBase.Core.BlockingDequeueItemFromList(key, sp); } /// <summary> /// 阻塞命令:從list中keys的尾部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public ItemRef BlockingDequeueItemFromLists(string[] keys, TimeSpan? sp) { return RedisBase.Core.BlockingDequeueItemFromLists(keys, sp); } /// <summary> /// 阻塞命令:從list中key的頭部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public string BlockingRemoveStartFromList(string keys, TimeSpan? sp) { return RedisBase.Core.BlockingRemoveStartFromList(keys, sp); } /// <summary> /// 阻塞命令:從list中key的頭部移除一個值,並返回移除的值,阻塞時間為sp /// </summary> public ItemRef BlockingRemoveStartFromLists(string[] keys, TimeSpan? sp) { return RedisBase.Core.BlockingRemoveStartFromLists(keys, sp); } /// <summary> /// 阻塞命令:從list中一個fromkey的尾部移除一個值,新增到另外一個tokey的頭部,並返回移除的值,阻塞時間為sp /// </summary> public string BlockingPopAndPushItemBetweenLists(string fromkey, string tokey, TimeSpan? sp) { return RedisBase.Core.BlockingPopAndPushItemBetweenLists(fromkey, tokey, sp); } #endregion #region 刪除 /// <summary> /// 從尾部移除資料,返回移除的資料 /// </summary> public string PopItemFromList(string key) { return RedisBase.Core.PopItemFromList(key); } /// <summary> /// 移除list中,key/value,與引數相同的值,並返回移除的數量 /// </summary> public long RemoveItemFromList(string key,string value) { return RedisBase.Core.RemoveItemFromList(key,value); } /// <summary> /// 從list的尾部移除一個資料,返回移除的資料 /// </summary> public string RemoveEndFromList(string key) { return RedisBase.Core.RemoveEndFromList(key); } /// <summary> /// 從list的頭部移除一個資料,返回移除的值 /// </summary> public string RemoveStartFromList(string key) { return RedisBase.Core.RemoveStartFromList(key); } #endregion #region 其它 /// <summary> /// 從一個list的尾部移除一個資料,新增到另外一個list的頭部,並返回移動的值 /// </summary> public string PopAndPushItemBetweenLists(string fromKey, string toKey) { return RedisBase.Core.PopAndPushItemBetweenLists(fromKey,toKey); } #endregion }
展現List的阻塞功能,類似一個簡單的訊息佇列功能
static void Main(string[] args) { string key = "zlh"; //清空資料庫 DoRedisBase.Core.FlushAll(); //給list賦值 DoRedisBase.Core.PushItemToList(key, "1"); DoRedisBase.Core.PushItemToList(key, "2"); DoRedisBase.Core.AddItemToList(key, "3"); DoRedisBase.Core.PrependItemToList(key, "0"); DoRedisBase.Core.AddRangeToList(key, new List<string>() { "4", "5", "6" }); #region 阻塞 //啟用一個執行緒來處理阻塞的資料集合 new Thread(new ThreadStart(RunBlock)).Start(); #endregion Console.ReadKey(); } public static void RunBlock() { while (true) { //如果key為zlh的list集合中有資料,則讀出,如果沒有則等待2個小時,2個小時中只要有資料進入這裡就可以給列印出來,類似一個簡易的訊息佇列功能。 Console.WriteLine(DoRedisBase.Core.BlockingPopItemFromList("zlh", TimeSpan.FromHours(2))); } }
.Net操作Redis資料型別Set
public class DoRedisSet:DoRedisBase { #region 新增 /// <summary> /// key集合中新增value值 /// </summary> public void Add(string key, string value) { RedisBase.Core.AddItemToSet(key,value); } /// <summary> /// key集合中新增list集合 /// </summary> public void Add(string key, List<string> list) { RedisBase.Core.AddRangeToSet(key, list); } #endregion #region 獲取 /// <summary> /// 隨機獲取key集合中的一個值 /// </summary> public string GetRandomItemFromSet(string key) { return RedisBase.Core.GetRandomItemFromSet(key); } /// <summary> /// 獲取key集合值的數量 /// </summary> public long GetCount(string key) { return RedisBase.Core.GetSetCount(key); } /// <summary> /// 獲取所有key集合的值 /// </summary> public HashSet<string> GetAllItemsFromSet(string key) { return RedisBase.Core.GetAllItemsFromSet(key); } #endregion #region 刪除 /// <summary> /// 隨機刪除key集合中的一個值 /// </summary> public string PopItemFromSet(string key) { return RedisBase.Core.PopItemFromSet(key); } /// <summary> /// 刪除key集合中的value /// </summary> public void RemoveItemFromSet(string key, string value) { RedisBase.Core.RemoveItemFromSet(key,value); } #endregion #region 其它 /// <summary> /// 從fromkey集合中移除值為value的值,並把value新增到tokey集合中 /// </summary> public void MoveBetweenSets(string fromkey,string tokey,string value) { RedisBase.Core.MoveBetweenSets(fromkey,tokey,value); } /// <summary> /// 返回keys多個集合中的並集,返還hashset /// </summary> public HashSet<string> GetUnionFromSets(string[] keys) { return RedisBase.Core.GetUnionFromSets(keys); } /// <summary> /// keys多個集合中的並集,放入newkey集合中 /// </summary> public void StoreUnionFromSets(string newkey, string[] keys) { RedisBase.Core.StoreUnionFromSets(newkey,keys); } /// <summary> /// 把fromkey集合中的資料與keys集合中的資料對比,fromkey集合中不存在keys集合中,則把這些不存在的資料放入newkey集合中 /// </summary> public void StoreDifferencesFromSet(string newkey, string fromkey, string[] keys) { RedisBase.Core.StoreDifferencesFromSet(newkey,fromkey,keys); } #endregion }
.Net操作Redis資料型別有序集合Zset
public class DoRedisZSet : DoRedisBase { #region 新增 /// <summary> /// 新增key/value,預設分數是從1.多*10的9次方以此遞增的,自帶自增效果 /// </summary> public bool AddItemToSortedSet(string key, string value) { return RedisBase.Core.AddItemToSortedSet(key, value); } /// <summary> /// 新增key/value,並設定value的分數 /// </summary> public bool AddItemToSortedSet(string key, string value, double score) { return RedisBase.Core.AddItemToSortedSet(key, value, score); } /// <summary> /// 為key新增values集合,values集合中每個value的分數設定為score /// </summary> public bool AddRangeToSortedSet(string key,List<string> values,double score) { return RedisBase.Core.AddRangeToSortedSet(key, values, score); } /// <summary> /// 為key新增values集合,values集合中每個value的分數設定為score /// </summary> public bool AddRangeToSortedSet(string key, List<string> values, long score) { return RedisBase.Core.AddRangeToSortedSet(key, values, score); } #endregion #region 獲取 /// <summary> /// 獲取key的所有集合 /// </summary> public List<string> GetAllItemsFromSortedSet(string key) { return RedisBase.Core.GetAllItemsFromSortedSet(key); } /// <summary> /// 獲取key的所有集合,倒敘輸出 /// </summary> public List<string> GetAllItemsFromSortedSetDesc(string key) { return RedisBase.Core.GetAllItemsFromSortedSetDesc(key); } /// <summary> /// 獲取可以的說有集合,帶分數 /// </summary> public IDictionary<string, double> GetAllWithScoresFromSortedSet(string key) { return RedisBase.Core.GetAllWithScoresFromSortedSet(key); } /// <summary> /// 獲取key為value的下標值 /// </summary> public long GetItemIndexInSortedSet(string key, string value) { return RedisBase.Core.GetItemIndexInSortedSet(key, value); } /// <summary> /// 倒敘排列獲取key為value的下標值 /// </summary> public long GetItemIndexInSortedSetDesc(string key, string value) { return RedisBase.Core.GetItemIndexInSortedSetDesc(key, value); } /// <summary> /// 獲取key為value的分數 /// </summary> public double GetItemScoreInSortedSet(string key,string value) { return RedisBase.Core.GetItemScoreInSortedSet(key,value); } /// <summary> /// 獲取key所有集合的資料總數 /// </summary> public long GetSortedSetCount(string key) { return RedisBase.Core.GetSortedSetCount(key); } /// <summary> /// key集合資料從分數為fromscore到分數為toscore的資料總數 /// </summary> public long GetSortedSetCount(string key,double fromScore,double toScore) { return RedisBase.Core.GetSortedSetCount(key,fromScore,toScore); } /// <summary> /// 獲取key集合從高分到低分排序資料,分數從fromscore到分數為toscore的資料 /// </summary> public List<string> GetRangeFromSortedSetByHighestScore(string key, double fromscore, double toscore) { return RedisBase.Core.GetRangeFromSortedSetByHighestScore(key, fromscore, toscore); } /// <summary> /// 獲取key集合從低分到高分排序資料,分數從fromscore到分數為toscore的資料 /// </summary> public List<string> GetRangeFromSortedSetByLowestScore(string key, double fromscore, double toscore) { return RedisBase.Core.GetRangeFromSortedSetByLowestScore(key, fromscore, toscore); } /// <summary> /// 獲取key集合從高分到低分排序資料,分數從fromscore到分數為toscore的資料,帶分數 /// </summary> public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string key, double fromscore, double toscore) { return RedisBase.Core.GetRangeWithScoresFromSortedSetByHighestScore(key, fromscore, toscore); } /// <summary> /// 獲取key集合從低分到高分排序資料,分數從fromscore到分數為toscore的資料,帶分數 /// </summary> public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string key, double fromscore, double toscore) { return RedisBase.Core.GetRangeWithScoresFromSortedSetByLowestScore(key, fromscore, toscore); } /// <summary> /// 獲取key集合資料,下標從fromRank到分數為toRank的資料 /// </summary> public List<string> GetRangeFromSortedSet(string key, int fromRank, int toRank) { return RedisBase.Core.GetRangeFromSortedSet(key, fromRank, toRank); } /// <summary> /// 獲取key集合倒敘排列資料,下標從fromRank到分數為toRank的資料 /// </summary> public List<string> GetRangeFromSortedSetDesc(string key, int fromRank, int toRank) { return RedisBase.Core.GetRangeFromSortedSetDesc(key, fromRank, toRank); } /// <summary> /// 獲取key集合資料,下標從fromRank到分數為toRank的資料,帶分數 /// </summary> public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string key, int fromRank, int toRank) { return RedisBase.Core.GetRangeWithScoresFromSortedSet(key, fromRank, toRank); } /// <summary> /// 獲取key集合倒敘排列資料,下標從fromRank到分數為toRank的資料,帶分數 /// </summary> public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string key, int fromRank, int toRank) { return RedisBase.Core.GetRangeWithScoresFromSortedSetDesc(key, fromRank, toRank); } #endregion #region 刪除 /// <summary> /// 刪除key為value的資料 /// </summary> public bool RemoveItemFromSortedSet(string key,string value) { return RedisBase.Core.RemoveItemFromSortedSet(key, value); } /// <summary> /// 刪除下標從minRank到maxRank的key集合資料 /// </summary> public long RemoveRangeFromSortedSet(string key,int minRank,int maxRank) { return RedisBase.Core.RemoveRangeFromSortedSet(key,minRank,maxRank); } /// <summary> /// 刪除分數從fromscore到toscore的key集合資料 /// </summary> public long RemoveRangeFromSortedSetByScore(string key, double fromscore, double toscore) { return RedisBase.Core.RemoveRangeFromSortedSetByScore(key, fromscore, toscore); } /// <summary> /// 刪除key集合中分數最大的資料 /// </summary> public string PopItemWithHighestScoreFromSortedSet(string key) { return RedisBase.Core.PopItemWithHighestScoreFromSortedSet(key); } /// <summary> /// 刪除key集合中分數最小的資料 /// </summary> public string PopItemWithLowestScoreFromSortedSet(string key) { return RedisBase.Core.PopItemWithLowestScoreFromSortedSet(key); } #endregion #region 其它 /// <summary> /// 判斷key集合中是否存在value資料 /// </summary> public bool SortedSetContainsItem(string key, string value) { return RedisBase.Core.SortedSetContainsItem(key,value); } /// <summary> /// 為key集合值為value的資料,分數加scoreby,返回相加後的分數 /// </summary> public double IncrementItemInSortedSet(string key,string value,double scoreBy) { return RedisBase.Core.IncrementItemInSortedSet(key,value,scoreBy); } /// <summary> /// 獲取keys多個集合的交集,並把交集新增的newkey集合中,返回交集資料的總數 /// </summary> public long StoreIntersectFromSortedSets(string newkey, string[] keys) { return RedisBase.Core.StoreIntersectFromSortedSets(newkey,keys); } /// <summary> /// 獲取keys多個集合的並集,並把並集資料新增到newkey集合中,返回並集資料的總數 /// </summary> public long StoreUnionFromSortedSets(string newkey, string[] keys) { return RedisBase.Core.StoreUnionFromSortedSets(newkey, keys); } #endregion }
.Net操作Redis資料型別雜湊Hash
public class DoRedisHash :DoRedisBase { #region 新增 /// <summary> /// 向hashid集合中新增key/value /// </summary> public bool SetEntryInHash(string hashid, string key, string value) { return RedisBase.Core.SetEntryInHash(hashid,key,value); } /// <summary> /// 如果hashid集合中存在key/value則不新增返回false,如果不存在在新增key/value,返回true /// </summary> public bool SetEntryInHashIfNotExists(string hashid, string key, string value) { return RedisBase.Core.SetEntryInHashIfNotExists(hashid, key, value); } /// <summary> /// 儲存物件T t到hash集合中 /// </summary> public void StoreAsHash<T>(T t) { RedisBase.Core.StoreAsHash<T>(t); } #endregion #region 獲取 /// <summary> /// 獲取物件T中ID為id的資料。 /// </summary> public T GetFromHash<T>(object id) { return RedisBase.Core.GetFromHash<T>(id); } /// <summary> /// 獲取所有hashid資料集的key/value資料集合 /// </summary> public Dictionary<string, string> GetAllEntriesFromHash(string hashid) { return RedisBase.Core.GetAllEntriesFromHash(hashid); } /// <summary> /// 獲取hashid資料集中的資料總數 /// </summary> public long GetHashCount(string hashid) { return RedisBase.Core.GetHashCount(hashid); } /// <summary> /// 獲取hashid資料集中所有key的集合 /// </summary> public List<string> GetHashKeys(string hashid) { return RedisBase.Core.GetHashKeys(hashid); } /// <summary> /// 獲取hashid資料集中的所有value集合 /// </summary> public List<string> GetHashValues(string hashid) { return RedisBase.Core.GetHashValues(hashid); } /// <summary> /// 獲取hashid資料集中,key的value資料 /// </summary> public string GetValueFromHash(string hashid, string key) { return RedisBase.Core.GetValueFromHash(hashid, key); } /// <summary> /// 獲取hashid資料集中,多個keys的value集合 /// </summary> public List<string> GetValuesFromHash(string hashid, string[] keys) { return RedisBase.Core.GetValuesFromHash(hashid, keys); } #endregion #region 刪除 #endregion /// <summary> /// 刪除hashid資料集中的key資料 /// </summary> public bool RemoveEntryFromHash(string hashid, string key) { return RedisBase.Core.RemoveEntryFromHash(hashid, key); } #region 其它 /// <summary> /// 判斷hashid資料集中是否存在key的資料 /// </summary> public bool HashContainsEntry(string hashid, string key) { return RedisBase.Core.HashContainsEntry(hashid,key); } /// <summary> /// 給hashid資料集key的value加countby,返回相加後的資料 /// </summary> public double IncrementValueInHash(string hashid, string key, double countBy) { return RedisBase.Core.IncrementValueInHash(hashid, key, countBy); } #endregion }
.Net操作Redis中的事務與鎖
static void Main(string[] args) { //清空資料庫 DoRedisBase.Core.FlushAll(); //宣告事務 using (var tran = RedisManager.GetClient().CreateTransaction()) { try { tran.QueueCommand(p => { //操作redis資料命令 DoRedisBase.Core.Set<int>("name", 30); long i = DoRedisBase.Core.IncrementValueBy("name", 1); }); //提交事務 tran.Commit(); } catch { //回滾事務 tran.Rollback(); } ////操作redis資料命令 //RedisManager.GetClient().Set<int>("zlh", 30); ////宣告鎖,網頁程式可獲得鎖效果 //using (RedisManager.GetClient().AcquireLock("zlh")) //{ // RedisManager.GetClient().Set<int>("zlh", 31); // Thread.Sleep(10000); //} } Console.ReadKey(); }
小結
此文是作為我自己的ServiceStack.Redis文件觀看,如果你有什麼疑問,或者想一起交流學習,歡迎加入左上角的群。