redis——學習之路五(簡單的C#使用redis)


redis官方推薦使用的客戶端程序
打星星表示推薦使用的客戶端程序,一個笑臉表示最近6個月內有過正式活動的。 http://redis.io/clients/#c
從這里我們可以判斷官方推薦我們使用ServiceSatck.Redis與StackExchange.Redis,首先要注意的是在ServiceStack.Redis在4.0開始商業化收費的。所以我們這里就不做介紹了,我們只使用StackExChange.Redis做一些簡單的C#上面的操作。
這是StackExChange.Redis在Github官網上的 https://github.com/StackExchange/StackExchange.Redis代碼,下面有文檔教程大家可以自己去看看,同時我為大家找到了一位博友對上面一些文檔教程的翻譯,大家可以作為參考使用。http://www.cnblogs.com/deosky
下面是我對StackExCahnge.Redis做的一個簡單的例子以及一些簡單的處理。
復制代碼
  static void Main(string[] args)
  {
    #region 簡單dome
    ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=CeshiPassword");
    IDatabase db = redis.GetDatabase();
    string value = "name";
    db.StringSet("mykey", value);
    Console.WriteLine(db.StringGet("mykey"));
    #endregion
    #region 使用ConfigurationOptions連接redis服務器     ConfigurationOptions configurationOptions = new ConfigurationOptions()     {       EndPoints = { { "127.0.0.1", 6379 } },       CommandMap = CommandMap.Create(new HashSet<string>()       {         "INFO",         "CONFIG",         "CLUSTER",         "PING",         "ECHO",         "CLIENT"       }, available: false),       KeepAlive = 180,       DefaultVersion = new Version(2, 8, 24),       Password = "CeshiPassword"     };     IDatabase db1 = redis.GetDatabase();     string value2 = "name2";     db.StringSet("mykey2", value2);     Console.WriteLine(db.StringGet("mykey2"));     #endregion
    Console.ReadKey();   }
復制代碼
以上我參考說明作者的文檔一二簡單的寫出來了,大家可當成測試使用。
下面是本人做的了一些封裝
在文檔一中作者提到在ConnectionMulitiplexer在內部走了很多事情,所有我們不需要在每一步操作時創建ConnectionMulitiplexer對象。英文原文:
Because the  ConnectionMultiplexer does a lot, it is designed to be  shared and reused between callers. You should not create a  ConnectionMultiplexer per operation. It is fully thread-safe and ready for this usage. In all the subsequent examples it will be assumed that you have a  ConnectionMultiplexer instance stored away for re-use. But for now, let's create one.
所以我們創建一個單例來保存一個ConnectionMulitiplexer對象就可以了,同時我把一些配置放在config文件。
復制代碼
  public class RedisManager
    {
        /// <summary>
        /// redis配置文件信息
        /// </summary>
        private static RedisConfig RedisConfig = RedisConfig.GetConfig();
        private static ConnectionMultiplexer _redis;
        private static object _locker = new object();
        public static ConnectionMultiplexer Manager
        {
            get
            {
                if (_redis == null)
                {
                    lock (_locker)
                    {
                        if (_redis != null) return _redis;
                        _redis = GetManager();
                        return _redis;
                    }
                }
                return _redis;
            }
        }
        private static ConnectionMultiplexer GetManager(ConfigurationOptions configurationOptions = null)
        {
            if (configurationOptions == null)
            {
                configurationOptions = new ConfigurationOptions()
                {
                    EndPoints = { { RedisConfig.WriteServerConStr } },
                    CommandMap = CommandMap.Create(new HashSet<string>()
                    {
                        "INFO",
                        "CONFIG",
                        "CLUSTER",
                        "PING",
                        "ECHO",
                        "CLIENT"
                    }, available: false),
                    KeepAlive = RedisConfig.KeepAlive,
                    DefaultVersion = new Version(2, 8, 24),
                    Password = RedisConfig.PassWord
                };
            }
            return ConnectionMultiplexer.Connect(configurationOptions);
        }
    }
復制代碼
復制代碼
  public class RedisCacheManager : ICacheManager
    {
        public static RedisCacheManager Instance = new RedisCacheManager();
        public string Get(string key)
        {
            var db = RedisManager.Manager.GetDatabase();
            return db.StringGet(key);
        }
        public T Get<T>(string key)
        {
            var db = RedisManager.Manager.GetDatabase();
            return JsonConvert.DeserializeObject<T>(db.StringGet(key));
        }
        public void Set<T>(string key, T data, int cacheTime)
        {
            var db = RedisManager.Manager.GetDatabase();
            string str = JsonConvert.SerializeObject(data);
            db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime));
        }
        public void Set(string key, object data, int cacheTime)
        {
            var db = RedisManager.Manager.GetDatabase();
            string str = JsonConvert.SerializeObject(data);
            db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime));
        }
        public void Set(string key, object data)
        {
            var db = RedisManager.Manager.GetDatabase();
            string str = JsonConvert.SerializeObject(data);
            db.StringSet(key, str);
        }
        public bool IsSet(string key)
        {
            var db = RedisManager.Manager.GetDatabase();
            return db.KeyExists(key);
        }
        public void Remove(string key)
        {
            var db = RedisManager.Manager.GetDatabase();
            db.KeyDelete(key);
        }
復制代碼
我們只需要在每一個操作時獲取要操作的db,這里是否只需要獲取一次db就OK呢?這個本人還沒有弄明白,如果大家有誰了解的歡迎指正。
 
本來這篇文章我早就應該寫了,由於公司准備搬家到深圳,本人去不了,正准備面試換工作,所以一直沒有更新。
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM