国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Redis總結(二)C#中如何使用redis

2019-11-14 13:45:48
字體:
來源:轉載
供稿:網友

  上一篇講述了安裝redis《Redis總結(一)Redis安裝》,同時也大致介紹了redis的優勢和應用場景。本篇著重講解.NET中如何使用redis和C#。

 

  Redis官網提供了很多開源的C#客戶端。例如,Nhiredis ,ServiceStack.Redis ,StackExchange.Redis等。其中ServiceStack.Redis應該算是比較流行的。它提供了一整套從Redis數據結構都強類型對象轉換的機制并將對象json序列化。所以這里只介紹ServiceStack.Redis,它也是目前我們產品中所使用的客戶端。 

 

  ServiceStack.Redis地址:https://github.com/ServiceStack/ServiceStack.Redis 

 

  1. 建立一個控制臺應用程序,并引用以下ServiceStack.Redis相關的四個類庫。或者通過Nuget進行安裝Redis常用組件ServiceStack.Redis。 下載示例代碼。

      

 

  2. 創建一個Redis操作的公用類RedisCacheHelper,

using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Web;using ServiceStack.Common.Extensions;using ServiceStack.Redis;using ServiceStack.Logging;namespace Weiz.Redis.RedisTest{    public class RedisCacheHelper    {        PRivate static readonly PooledRedisClientManager pool = null;        private static readonly string[] redisHosts = null;        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);        static RedisCacheHelper()        {            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];            if (!string.IsNullOrEmpty(redisHostStr))            {                redisHosts = redisHostStr.Split(',');                if (redisHosts.Length > 0)                {                    pool = new PooledRedisClientManager(redisHosts, redisHosts,                        new RedisClientManagerConfig()                        {                            MaxWritePoolSize = RedisMaxWritePool,                            MaxReadPoolSize = RedisMaxReadPool,                            AutoStart = true                        });                }            }        }        public static void Add<T>(string key, T value, DateTime expiry)        {            if (value == null)            {                return;            }            if (expiry <= DateTime.Now)            {                Remove(key);                return;            }            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Set(key, value, expiry - DateTime.Now);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "存儲", key);            }        }        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)        {            if (value == null)            {                return;            }            if (slidingExpiration.TotalSeconds <= 0)            {                Remove(key);                return;            }            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Set(key, value, slidingExpiration);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "存儲", key);            }        }        public static T Get<T>(string key)        {            if (string.IsNullOrEmpty(key))            {                return default(T);            }            T obj = default(T);            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            obj = r.Get<T>(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "獲取", key);            }            return obj;        }        public static void Remove(string key)        {            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            r.Remove(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "刪除", key);            }        }        public static bool Exists(string key)        {            try            {                if (pool != null)                {                    using (var r = pool.GetClient())                    {                        if (r != null)                        {                            r.SendTimeout = 1000;                            return r.ContainsKey(key);                        }                    }                }            }            catch (Exception ex)            {                string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "是否存在", key);            }            return false;        }    }}

  說明:RedisCacheHelper 使用的是客戶端鏈接池模式,這樣的存取效率應該是最高的。同時也更方便的支持讀寫分離,均衡負載。

 

  3. 配置文件

    <!-- redis Start   -->    <add key="SessionExpireMinutes" value="180" />    <add key="redis_server_session" value="127.0.0.1:6379" />    <add key="redis_max_read_pool" value="3" />    <add key="redis_max_write_pool" value="1" />    <!--redis end-->

 

  4. 測試程序調用

class Program    {        static void Main(string[] args)        {            Console.WriteLine("Redis寫入緩存:zhong");            RedisCacheHelper.Add("zhong", "zhongzhongzhong", DateTime.Now.AddDays(1));            Console.WriteLine("Redis獲取緩存:zhong");            string str3 = RedisCacheHelper.Get<string>("zhong");            Console.WriteLine(str3);            Console.WriteLine("Redis獲取緩存:nihao");            string str = RedisCacheHelper.Get<string>("nihao");            Console.WriteLine(str);            Console.WriteLine("Redis獲取緩存:wei");            string str1 = RedisCacheHelper.Get<string>("wei");            Console.WriteLine(str1);            Console.ReadKey();        }    }

  

  5. 輸出結果

     


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南和县| 清远市| 临潭县| 栾城县| 宁海县| 滨海县| 获嘉县| 武功县| 铁力市| 丰宁| 珲春市| 广元市| 房产| 台安县| 嵊泗县| 肥乡县| 绥滨县| 滨海县| 友谊县| 丁青县| 福安市| 广水市| 永平县| 海宁市| 巢湖市| 固始县| 敖汉旗| 德江县| 大悟县| 湘阴县| 威信县| 昭通市| 来凤县| 论坛| 屯门区| 鹤岗市| 尤溪县| 沅陵县| 苍溪县| 武隆县| 临湘市|