C# 通過ServiceStack 操作Redis
作 者 : 明志德道
1.引用Nuget包 ServiceStack.Redis
我這裡就用別人已經封裝好的Reids操作類來和大傢一起參考瞭下,看看怎麼使用ServiceStack.Redis 操作Redis數據
RedisConfigInfo–redis配置文件信息
/// <summary> /// redis配置文件信息 /// 也可以放到配置文件去 /// </summary> public sealed class RedisConfigInfo { /// <summary> /// 可寫的Redis鏈接地址 /// format:ip1,ip2 /// /// 默認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> /// 最大寫鏈接數 /// </summary> public int MaxWritePoolSize = 60; /// <summary> /// 最大讀鏈接數 /// </summary> public int MaxReadPoolSize = 60; /// <summary> /// 本地緩存到期時間,單位:秒 /// </summary> public int LocalCacheTime = 180; /// <summary> /// 自動重啟 /// </summary> public bool AutoStart = true; /// <summary> /// 是否記錄日志,該設置僅用於排查redis運行時出現的問題, /// 如redis工作正常,請關閉該項 /// </summary> public bool RecordeLog = false; }
RedisManager –Redis管理中心 創建Redis鏈接
/// <summary> /// Redis管理中心 創建Redis鏈接 /// </summary> public class RedisManager { /// <summary> /// redis配置文件信息 /// </summary> private static RedisConfigInfo RedisConfigInfo = new RedisConfigInfo(); /// <summary> /// Redis客戶端池化管理 /// </summary> private static PooledRedisClientManager prcManager; /// <summary> /// 靜態構造方法,初始化鏈接池管理對象 /// </summary> static RedisManager() { CreateManager(); } /// <summary> /// 創建鏈接池管理對象 /// </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接口,主要用於釋放內存
/// <summary> /// RedisBase類,是redis操作的基類,繼承自IDisposable接口,主要用於釋放內存 /// </summary> public abstract class RedisBase : IDisposable { public IRedisClient iClient { get; private set; } /// <summary> /// 構造時完成鏈接的打開 /// </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(); // 提交事務 } catch (Exception ex) { irt.Rollback(); throw ex; } } } /// <summary> /// 清除全部數據 請小心 /// </summary> public virtual void FlushAll() { iClient.FlushAll(); } /// <summary> /// 保存數據DB文件到硬盤 /// </summary> public void Save() { iClient.Save();//阻塞式save } /// <summary> /// 異步保存數據DB文件到硬盤 /// </summary> public void SaveAsync() { iClient.SaveAsync();//異步save } }
RedisStringService–String類型操作幫助類
/// <summary> /// key-value 鍵值對:value可以是序列化的數據 /// </summary> public class RedisStringService : RedisBase { #region 賦值 /// <summary> /// 設置key的value /// </summary> public bool Set<T>(string key, T value) { //iClient.Db =2; return base.iClient.Set<T>(key, value); } /// <summary> /// 設置key的value並設置過期時間 /// </summary> public bool Set<T>(string key, T value, DateTime dt) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, dt); } /// <summary> /// 設置key的value並設置過期時間 /// </summary> public bool Set<T>(string key, T value, TimeSpan sp) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, sp); } /// <summary> /// 設置多個key/value 可以一次保存多個key value ---多個key value 不是分多次,是一個獨立的命令; /// </summary> public void Set(Dictionary<string, string> dic) { //iClient.Db = 2; base.iClient.SetAll(dic); } #endregion #region 追加 /// <summary> /// 在原有key的value值之後追加value,沒有就新增一項 /// </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> /// 獲取多個key的value值 /// </summary> public List<string> Get(List<string> keys) { return base.iClient.GetValues(keys); } /// <summary> /// 獲取多個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 調用後,+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操作是單線程操作;不會出現超賣的情況 /// </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包是外國人寫的,在國內並沒有完整的中文文檔,也沒有專門的人來翻譯、封裝它,所以上面的代碼方法不是很全,還有很多api方法需要自己去官網找然後自己封裝。
在這裡,上面的封裝我就放一邊,還是給大傢演示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. 根據key獲取值 string data1= client.GetValue("key_name"); //3. 在原有的value上進行追加 long data2 = client.AppendToValue("key_name", "value_11"); // 4.獲取值的長度 var data3=client.GetStringCount("key_name"); //5. 數值自增/減,返回自增、自減後的值 client.Set("小明分數", 100); //自增20,可以自增負值 var data4= client.IncrementValueBy("小明分數", 20); //自減50 var data5 = client.DecrementValueBy("小明分數", 50); //6. 插入實體和讀取實體 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. 一次性添加多個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.獲取多個key的 value值集合 List<string> keys = new List<string>(){ "101", "103", "105" }; List<string> data8= client.GetValues(keys);
//9. 重命名key client.Rename("106", "1066"); //10. 設置key的過期時間(30秒後自動銷毀) bool b2= client.Expire("102", 30); //11. 刪除單個key bool d1 = client.Remove("101");//刪除成功,返回true bool d2 = client.Remove("ffff"); //刪除不存在的數據,返回false
//13.清除全部數據 請小心 client.FlushAll();
以上就是C# 通過ServiceStack 操作Redis的詳細內容,更多關於C# ServiceStack 操作Redis的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- .Net Core使用SignalR實現鬥地主遊戲
- 詳解C#中普通緩存的使用
- Redis基於Bitmap實現用戶簽到功能
- C#實現自由組合本地緩存、分佈式緩存和數據查詢
- Redis全局ID生成器的實現