緩衝技術Redis在C#中的使用及Redis的封裝

來源:互聯網
上載者:User
Redis是一款開源的、高效能的鍵-值儲存(key-value store)。它常被稱作是一款資料結構伺服器(data structure server)。Redis的索引值可以包括字串(strings)、雜湊(hashes)、列表(lists)、集合(sets)和 有序集合(sorted sets)等資料類型。 對於這些資料類型,你可以執行原子操作。例如:對字串進行附加操作(append);遞增雜湊中的值;向列表中增加元素;計算集合的交集、並集與差集等。

    為了獲得優異的效能,Redis採用了記憶體中(in-memory)資料集(dataset)的方式。根據使用情境的不同,你可以每隔一段時間將資料集轉存到磁碟上來持久化資料,或者在日誌尾部追加每一條操作命令。

    Redis同樣支援主從複製(master-slave replication),並且具有非常快速的非阻塞首次同步(non-blocking first synchronization)、網路斷開自動重連等功能。同時Redis還具有其它一些特性,其中包括簡單的check-and-set機制、pub/sub和配置設定等,以便使得Redis能夠表現得更像緩衝(cache)。

    Redis還提供了豐富的用戶端,以便支援現階段流行的大多數程式設計語言。詳細的支援列表可以參看Redis官方文檔:http://redis.io/clients。Redis自身使用ANSI C來編寫,並且能夠在不產生外部依賴(external dependencies)的情況下運行在大多數POSIX系統上,例如:Linux、*BSD、OS X和Solaris等。

Redis 由四個可執行檔:redis-benchmark、redis-cli、redis-server、redis-stat 這四個檔案,加上一個redis.conf就構成了整個redis的最終可用包。它們的作用如下:

    redis-server:Redis伺服器的daemon啟動程式
    redis-cli:Redis命令列操作工具。當然,你也可以用telnet根據其純文字協議來操作
    redis-benchmark:Redis效能測試工具,測試Redis在你的系統及你的配置下的讀寫效能
    redis-stat:Redis狀態偵查工具,可以檢測Redis目前狀態參數及延遲狀況

現在就可以啟動redis了,redis只有一個啟動參數,就是他的設定檔路徑。


首選,你先得開啟redis-server,否則無法串連服務:


開啟redis-server:



接下來你就可以調用Redis的屬性來進行資料的儲存及擷取:



關鍵性代碼:

<span style="color:#000000;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using ServiceStack.Redis;using ServiceStack.Redis.Support;namespace RedisStudy{    class Program    {        static void Main(string[] args)        {            try            {                //擷取Redis操作介面                IRedisClient Redis = RedisManager.GetClient();                //Hash表操作                HashOperator operators = new HashOperator();                //移除某個快取資料                bool isTrue = Redis.Remove("additemtolist");                //將字串列表添加到redis                List<string> storeMembers = new List<string>() { "韓梅梅", "李雷", "露西" };                storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));                //得到指定的key所對應的value集合                Console.WriteLine("得到指定的key所對應的value集合:");                var members = Redis.GetAllItemsFromList("additemtolist");                members.ForEach(s => Console.WriteLine("additemtolist :" + s));                Console.WriteLine("");                // 擷取指定索引位置資料                Console.WriteLine("擷取指定索引位置資料:");                var item = Redis.GetItemFromList("additemtolist", 2);                Console.WriteLine(item);                Console.WriteLine("");                //將資料存入Hash表中                Console.WriteLine("Hash表資料存放區:");                UserInfo userInfos = new UserInfo() { UserName = "李雷", Age = 45 };                var ser = new ObjectSerializer();    //位於namespace ServiceStack.Redis.Support;                bool results = operators.Set<byte[]>("userInfosHash", "userInfos", ser.Serialize(userInfos));                byte[] infos = operators.Get<byte[]>("userInfosHash", "userInfos");                userInfos = ser.Deserialize(infos) as UserInfo;                Console.WriteLine("name=" + userInfos.UserName + "   age=" + userInfos.Age);                Console.WriteLine("");                //object序列化方式儲存                Console.WriteLine("object序列化方式儲存:");                UserInfo uInfo = new UserInfo() { UserName = "張三", Age = 12 };                bool result = Redis.Set<byte[]>("uInfo", ser.Serialize(uInfo));                UserInfo userinfo2 = ser.Deserialize(Redis.Get<byte[]>("uInfo")) as UserInfo;                Console.WriteLine("name=" + userinfo2.UserName + "   age=" + userinfo2.Age);                Console.WriteLine("");                //儲存實值型別資料                Console.WriteLine("儲存實值型別資料:");                Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12);                int age = Redis.Get<int>("my_age");                Console.WriteLine("age=" + age);                Console.WriteLine("");                //序列化列表資料                Console.WriteLine("列表資料:");                List<UserInfo> userinfoList = new List<UserInfo> {                new UserInfo{UserName="露西",Age=1,Id=1},                new UserInfo{UserName="瑪麗",Age=3,Id=2},            };                Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList));                List<UserInfo> userList = ser.Deserialize(Redis.Get<byte[]>("userinfolist_serialize")) as List<UserInfo>;                userList.ForEach(i =>                {                    Console.WriteLine("name=" + i.UserName + "   age=" + i.Age);                });                //釋放記憶體                Redis.Dispose();                operators.Dispose();                Console.ReadKey();            }            catch (Exception ex)            {                Console.WriteLine(ex.Message.ToString());                Console.WriteLine("Please open the redis-server.exe ");                Console.ReadKey();            }        }    }}</span>

RedisManager類:

<span style="color:#000000;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using ServiceStack.Redis;namespace RedisStudy{    /// <summary>    /// RedisManager類主要是建立連結池管理對象的    /// </summary>    public class RedisManager    {        /// <summary>        /// redis設定檔資訊        /// </summary>        private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"];        private static PooledRedisClientManager _prcm;        /// <summary>        /// 靜態構造方法,初始化連結池管理對象        /// </summary>        static RedisManager()        {            CreateManager();        }        /// <summary>        /// 建立連結池管理對象        /// </summary>        private static void CreateManager()        {            _prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath });        }                private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)        {            //WriteServerList:可寫的Redis連結地址。            //ReadServerList:可讀的Redis連結地址。            //MaxWritePoolSize:最大寫連結數。            //MaxReadPoolSize:最大讀連結數。            //AutoStart:自動重啟。            //LocalCacheTime:本機快取到期時間,單位:秒。            //RecordeLog:是否記錄日誌,該設定僅用於排查redis運行時出現的問題,如redis工作正常,請關閉該項。            //RedisConfigInfo類是記錄redis串連資訊,此資訊和設定檔中的RedisConfig相呼應            // 支援讀寫分離,均衡負載             return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig            {                MaxWritePoolSize = 5, // “寫”連結池連結數                 MaxReadPoolSize = 5, // “讀”連結池連結數                 AutoStart = true,            });        }        private static IEnumerable<string> SplitString(string strSource, string split)        {            return strSource.Split(split.ToArray());        }        /// <summary>        /// 用戶端快取作業對象        /// </summary>        public static IRedisClient GetClient()        {            if (_prcm == null)            {                CreateManager();            }            return _prcm.GetClient();        }    }}</span>

RedisOperatorBase類:

<span style="color:#000000;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using ServiceStack.Redis;namespace RedisStudy{    /// <summary>    /// RedisOperatorBase類,是redis操作的基類,繼承自IDisposable介面,主要用於釋放記憶體    /// </summary>    public abstract class RedisOperatorBase : IDisposable    {        protected IRedisClient Redis { get; private set; }        private bool _disposed = false;        protected RedisOperatorBase()        {            Redis = RedisManager.GetClient();        }        protected virtual void Dispose(bool disposing)        {            if (!this._disposed)            {                if (disposing)                {                    Redis.Dispose();                    Redis = null;                }            }            this._disposed = true;        }        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        /// <summary>        /// 儲存資料DB檔案到硬碟        /// </summary>        public void Save()        {            Redis.Save();        }        /// <summary>        /// 非同步儲存資料DB檔案到硬碟        /// </summary>        public void SaveAsync()        {            Redis.SaveAsync();        }    }}</span>

HashOperator類:

<span style="color:#000000;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using ServiceStack.Text;namespace RedisStudy{    /// <summary>    /// HashOperator類,是操作雜湊表類。繼承自RedisOperatorBase類    /// </summary>    public class HashOperator : RedisOperatorBase    {        public HashOperator() : base() { }        /// <summary>        /// 判斷某個資料是否已經被緩衝        /// </summary>        public bool Exist<T>(string hashId, string key)        {            return Redis.HashContainsEntry(hashId, key);        }        /// <summary>        /// 儲存資料到hash表        /// </summary>        public bool Set<T>(string hashId, string key, T t)        {            var value = JsonSerializer.SerializeToString<T>(t);            return Redis.SetEntryInHash(hashId, key, value);        }        /// <summary>        /// 移除hash中的某值        /// </summary>        public bool Remove(string hashId, string key)        {            return Redis.RemoveEntryFromHash(hashId, key);        }        /// <summary>        /// 移除整個hash        /// </summary>        public bool Remove(string key)        {            return Redis.Remove(key);        }        /// <summary>        /// 從hash表擷取資料        /// </summary>        public T Get<T>(string hashId, string key)        {            string value = Redis.GetValueFromHash(hashId, key);            return JsonSerializer.DeserializeFromString<T>(value);        }        /// <summary>        /// 擷取整個hash的資料        /// </summary>        public List<T> GetAll<T>(string hashId)        {            var result = new List<T>();            var list = Redis.GetHashValues(hashId);            if (list != null && list.Count > 0)            {                list.ForEach(x =>                {                    var value = JsonSerializer.DeserializeFromString<T>(x);                    result.Add(value);                });            }            return result;        }        /// <summary>        /// 設定緩衝到期        /// </summary>        public void SetExpire(string key, DateTime datetime)        {            Redis.ExpireEntryAt(key, datetime);        }    }}</span>

UserInfo類:

<span style="color:#000000;">using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace RedisStudy{    [Serializable]    public class UserInfo    {        public int Id;        public string UserName;        public int Age;    }}</span>


app.config配置:

<?xml version="1.0"?><configuration><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>  <appSettings>    <add key="RedisPath" value="127.0.0.1:6379"/>  </appSettings></configuration>





以上是Redis操作的封裝類,直接拿來調用即可。

具體代碼下載:

Redis代碼


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.