C# 通過ServiceStack 操作Redis
作 者 : 明志德道
1.引用Nuget包 ServiceStack.Redis
我這里就用別人已經(jīng)封裝好的Reids操作類來和大家一起參考了下,看看怎么使用ServiceStack.Redis 操作Redis數(shù)據(jù)
RedisConfigInfo--redis配置文件信息
/// <summary> /// redis配置文件信息 /// 也可以放到配置文件去 /// </summary> public sealed class RedisConfigInfo { /// <summary> /// 可寫的Redis鏈接地址 /// format:ip1,ip2 /// /// 默認(rèn)6379端口 /// </summary> public string WriteServerList = "127.0.0.1:6379"; /// <summary> /// 可讀的Redis鏈接地址 /// format:ip1,ip2 /// </summary> public string ReadServerList = "127.0.0.1:6379"; /// <summary> /// 最大寫鏈接數(shù) /// </summary> public int MaxWritePoolSize = 60; /// <summary> /// 最大讀鏈接數(shù) /// </summary> public int MaxReadPoolSize = 60; /// <summary> /// 本地緩存到期時(shí)間,單位:秒 /// </summary> public int LocalCacheTime = 180; /// <summary> /// 自動重啟 /// </summary> public bool AutoStart = true; /// <summary> /// 是否記錄日志,該設(shè)置僅用于排查redis運(yùn)行時(shí)出現(xiàn)的問題, /// 如redis工作正常,請關(guān)閉該項(xiàng) /// </summary> public bool RecordeLog = false; }
RedisManager --Redis管理中心 創(chuàng)建Redis鏈接
/// <summary> /// Redis管理中心 創(chuàng)建Redis鏈接 /// </summary> public class RedisManager { /// <summary> /// redis配置文件信息 /// </summary> private static RedisConfigInfo RedisConfigInfo = new RedisConfigInfo(); /// <summary> /// Redis客戶端池化管理 /// </summary> private static PooledRedisClientManager prcManager; /// <summary> /// 靜態(tài)構(gòu)造方法,初始化鏈接池管理對象 /// </summary> static RedisManager() { CreateManager(); } /// <summary> /// 創(chuàng)建鏈接池管理對象 /// </summary> private static void CreateManager() { string[] WriteServerConStr = RedisConfigInfo.WriteServerList.Split(','); string[] ReadServerConStr = RedisConfigInfo.ReadServerList.Split(','); prcManager = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr, new RedisClientManagerConfig { MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize, MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize, AutoStart = RedisConfigInfo.AutoStart, }); } /// <summary> /// 客戶端緩存操作對象 /// </summary> public static IRedisClient GetClient() { return prcManager.GetClient(); } }
RedisBase-- 是redis操作的基類,繼承自IDisposable接口,主要用于釋放內(nèi)存
/// <summary> /// RedisBase類,是redis操作的基類,繼承自IDisposable接口,主要用于釋放內(nèi)存 /// </summary> public abstract class RedisBase : IDisposable { public IRedisClient iClient { get; private set; } /// <summary> /// 構(gòu)造時(shí)完成鏈接的打開 /// </summary> public RedisBase() { iClient = RedisManager.GetClient(); } //public static IRedisClient iClient { get; private set; } //static RedisBase() //{ // iClient = RedisManager.GetClient(); //} private bool _disposed = false; protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { iClient.Dispose(); iClient = null; } } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Transcation() { using (IRedisTransaction irt = this.iClient.CreateTransaction()) { try { irt.QueueCommand(r => r.Set("key", 20)); irt.QueueCommand(r => r.Increment("key", 1)); irt.Commit(); // 提交事務(wù) } catch (Exception ex) { irt.Rollback(); throw ex; } } } /// <summary> /// 清除全部數(shù)據(jù) 請小心 /// </summary> public virtual void FlushAll() { iClient.FlushAll(); } /// <summary> /// 保存數(shù)據(jù)DB文件到硬盤 /// </summary> public void Save() { iClient.Save();//阻塞式save } /// <summary> /// 異步保存數(shù)據(jù)DB文件到硬盤 /// </summary> public void SaveAsync() { iClient.SaveAsync();//異步save } }
RedisStringService--String類型操作幫助類
/// <summary> /// key-value 鍵值對:value可以是序列化的數(shù)據(jù) /// </summary> public class RedisStringService : RedisBase { #region 賦值 /// <summary> /// 設(shè)置key的value /// </summary> public bool Set<T>(string key, T value) { //iClient.Db =2; return base.iClient.Set<T>(key, value); } /// <summary> /// 設(shè)置key的value并設(shè)置過期時(shí)間 /// </summary> public bool Set<T>(string key, T value, DateTime dt) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, dt); } /// <summary> /// 設(shè)置key的value并設(shè)置過期時(shí)間 /// </summary> public bool Set<T>(string key, T value, TimeSpan sp) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, sp); } /// <summary> /// 設(shè)置多個(gè)key/value 可以一次保存多個(gè)key value ---多個(gè)key value 不是分多次,是一個(gè)獨(dú)立的命令; /// </summary> public void Set(Dictionary<string, string> dic) { //iClient.Db = 2; base.iClient.SetAll(dic); } #endregion #region 追加 /// <summary> /// 在原有key的value值之后追加value,沒有就新增一項(xiàng) /// </summary> public long Append(string key, string value) { return base.iClient.AppendToValue(key, value); } #endregion #region 獲取值 /// <summary> /// 獲取key的value值 /// </summary> public string Get(string key) { return base.iClient.GetValue(key); } /// <summary> /// 獲取多個(gè)key的value值 /// </summary> public List<string> Get(List<string> keys) { return base.iClient.GetValues(keys); } /// <summary> /// 獲取多個(gè)key的value值 /// </summary> public List<T> Get<T>(List<string> keys) { return base.iClient.GetValues<T>(keys); } #endregion #region 獲取舊值賦上新值 /// <summary> /// 獲取舊值賦上新值 /// </summary> public string GetAndSetValue(string key, string value) { return base.iClient.GetAndSetValue(key, value); } #endregion #region 輔助方法 /// <summary> /// 獲取值的長度 /// </summary> public long GetLength(string key) { return base.iClient.GetStringCount(key); } /// <summary> /// 自增1,返回自增后的值 保存的是10 調(diào)用后,+1 返回11 /// </summary> public long Incr(string key) { return base.iClient.IncrementValue(key); } /// <summary> /// 自增count,返回自增后的值 自定義自增的步長值 /// </summary> public long IncrBy(string key, int count) { return base.iClient.IncrementValueBy(key, count); } /// <summary> /// 自減1,返回自減后的值,Redis操作是單線程操作;不會出現(xiàn)超賣的情況 /// </summary> public long Decr(string key) { return base.iClient.DecrementValue(key); } /// <summary> /// 自減count ,返回自減后的值 /// </summary> /// <param name="key"></param> /// <param name="count"></param> /// <returns></returns> public long DecrBy(string key, int count) { return base.iClient.DecrementValueBy(key, count); } #endregion }
nuget包是外國人寫的,在國內(nèi)并沒有完整的中文文檔,也沒有專門的人來翻譯、封裝它,所以上面的代碼方法不是很全,還有很多api方法需要自己去官網(wǎng)找然后自己封裝。
在這里,上面的封裝我就放一邊,還是給大家演示ServiceStack原生的API如何使用
2. string 類型的使用
public static RedisClient client = new RedisClient("127.0.0.1", 6379); //1.存入鍵值對 bool a = client.Set("key_name", "value_11"); //2. 根據(jù)key獲取值 string data1= client.GetValue("key_name"); //3. 在原有的value上進(jìn)行追加 long data2 = client.AppendToValue("key_name", "value_11"); // 4.獲取值的長度 var data3=client.GetStringCount("key_name"); //5. 數(shù)值自增/減,返回自增、自減后的值 client.Set("小明分?jǐn)?shù)", 100); //自增20,可以自增負(fù)值 var data4= client.IncrementValueBy("小明分?jǐn)?shù)", 20); //自減50 var data5 = client.DecrementValueBy("小明分?jǐn)?shù)", 50); //6. 插入實(shí)體和讀取實(shí)體 UserInfo userInfo = new UserInfo() { Id = 3, Age = 50, Name = "zxl", Pwd = "123456" }; client.Set("UserInfo_Id_3", userInfo); UserInfo data6 = client.Get<UserInfo>("UserInfo_Id_3"); //7. 一次性添加多個(gè)key-value集合 Dictionary<string, string> dic = new Dictionary<string, string>() { { "101", Guid.NewGuid().ToString("N")}, { "102", Guid.NewGuid().ToString("N")}, { "103", Guid.NewGuid().ToString("N")}, { "104", Guid.NewGuid().ToString("N")}, { "105", Guid.NewGuid().ToString("N")}, { "106", Guid.NewGuid().ToString("N")} }; client.SetAll(dic); //8.獲取多個(gè)key的 value值集合 List<string> keys = new List<string>(){ "101", "103", "105" }; List<string> data8= client.GetValues(keys);
//9. 重命名key client.Rename("106", "1066"); //10. 設(shè)置key的過期時(shí)間(30秒后自動銷毀) bool b2= client.Expire("102", 30); //11. 刪除單個(gè)key bool d1 = client.Remove("101");//刪除成功,返回true bool d2 = client.Remove("ffff"); //刪除不存在的數(shù)據(jù),返回false
//13.清除全部數(shù)據(jù) 請小心 client.FlushAll();
以上就是C# 通過ServiceStack 操作Redis的詳細(xì)內(nèi)容,更多關(guān)于C# ServiceStack 操作Redis的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#數(shù)據(jù)庫操作類AccessHelper實(shí)例
這篇文章主要介紹了C#數(shù)據(jù)庫操作類AccessHelper實(shí)例,可實(shí)現(xiàn)針對access數(shù)據(jù)庫的各種常見操作,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-10-10C# Winfrom實(shí)現(xiàn)Skyline畫直線功能的示例代碼
這篇文章主要介紹了C# Winfrom實(shí)現(xiàn)Skyline畫直線功能的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12C#編程實(shí)現(xiàn)向并口設(shè)備發(fā)送指令、獲取并口設(shè)備的狀態(tài)
這篇文章主要介紹了C#編程實(shí)現(xiàn)向并口設(shè)備發(fā)送指令、獲取并口設(shè)備的狀態(tài),本文直接給出實(shí)例代碼,需要的朋友可以參考下2015-06-06.NET操作NPOI實(shí)現(xiàn)Excel的導(dǎo)入導(dǎo)出
NPOI是指構(gòu)建在POI 3.x版本之上的一個(gè)程序,NPOI可以在沒有安裝Office的情況下對Word或Excel文檔進(jìn)行讀寫操作,下面小編為大家介紹了如何操作NPOI實(shí)現(xiàn)Excel的導(dǎo)入導(dǎo)出,需要的可以參考一下2023-09-09超炫酷的WPF實(shí)現(xiàn)Loading控件效果
這篇文章主要介紹了超炫酷的WPF實(shí)現(xiàn)Loading控件效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-11-11C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-08-08