1. 程式人生 > >C# 通過ServiceStack 操作Redis——String型別的使用及示例

C# 通過ServiceStack 操作Redis——String型別的使用及示例

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;
    }
View Code

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();
        }
    }
View Code

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
        }
    }
View Code

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
    }
View Code

 

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

//12. 刪除多個key
                IEnumerable<string> delete_keys = new List<string> { "101", "103", "105" };
                client.RemoveAll(delete_keys);

//13.清除全部資料 請小心
client.FlushAll();

&n