1. 程式人生 > >Redis 新手小白上路

Redis 新手小白上路

一、安裝Redis

Redis官網下載地址:http://redis.io/download,下載相應版本的Redis,在執行中輸入cmd,然後把目錄指向解壓的Redis目錄。

 我是Windows 10 + C# 開發,所以找一個 Windows 版本就好

我們去找一個 Windows 的版本

https://github.com/MicrosoftArchive/redis/releases

下載解壓,然後啟動

D:\Redis>redis-server.exe redis.windows.conf

看到如下,就已經好了

2016/07/01  09:17            14,265 Windows Service Documentation.docx
              14 個檔案     22,470,282 位元組
               2 個目錄 40,509,333,504 可用位元組

D:\Redis>redis-server.exe redis.windows.conf
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 3.2.100 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 22860
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

[22860] 06 Jan 13:45:11.605 # Server started, Redis version 3.2.100
[22860] 06 Jan 13:45:11.609 * The server is now ready to accept connections on port 6379
[22860] 06 Jan 14:00:12.048 * 1 changes in 900 seconds. Saving...
[22860] 06 Jan 14:00:12.056 * Background saving started by pid 18424
[22860] 06 Jan 14:00:12.266 # fork operation complete
[22860] 06 Jan 14:00:12.267 * Background saving terminated with success

二、Redis 的 C# 應用

C# Helper 類

public class RedisHelper
     {
        private static RedisClient Redis = null;

        static RedisHelper()
        {
            Redis = new RedisClient("127.0.0.1", 6379);
        }

        public static void SetMem<T>(T t, string key, int minute)
        {
            if (minute == 0)
            {
                Redis.Set<T>(key, t);
            }
            else
            {
                DateTime expiryTime = DateTime.Now.AddMinutes(minute);
                Redis.Set<T>(key, t, expiryTime);
            }
        }

        public static T GetMem<T>(string key)
        {
            return Redis.Get<T>(key);
        }
        /// <summary>
        /// 插入DATASET快取
        /// </summary>
        /// <param name="key">快取鍵</param>
        /// <param name="item">快取物件</param>
        /// <param name="minute">過期時間(分鐘)</param>
        public static void SetMemByDataSet(string key, DataTable dt, int minute)
        {

            DateTime expiryTime = DateTime.Now.AddMinutes(minute);
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();//定義BinaryFormatter以序列化DataSet物件   
            System.IO.MemoryStream ms = new System.IO.MemoryStream();//建立記憶體流物件   
            formatter.Serialize(ms, dt);//把dt物件序列化到記憶體流   
            byte[] buffer = ms.ToArray();//把記憶體流物件寫入位元組陣列   
            ms.Close();//關閉記憶體流物件   
            ms.Dispose();//釋放資源   
            if (minute == 0)
            {
                Redis.Set(key, buffer);
            }
            else
            {
                Redis.Set(key, buffer, expiryTime);
            }
        }
        public static object Get(string key)
        {
            byte[] buffer = Redis.Get(key);

            return GetObjFromBytes(buffer);
        }
        /// <summary>
        /// 從二進位制流得到物件(data專用,data資料要序列化為二進位制才可儲存
        /// /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static object GetObjFromBytes(byte[] buffer)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer))
            {
                stream.Position = 0;
                System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Object reobj = bf.Deserialize(stream);
                return reobj;
            }
        }
        /// <summary>
        /// 判斷是否失效或沒有
        /// </summary>如果為false已失效
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExpired(string key)
        {
            bool result = true;
            byte[] buffer = Redis.Get(key);
            if (buffer == null)
            {
                result = false;
            }
            return result;
        }
        public static DataTable GetMemByDataSet(string key)
        {
            var item = Get(key);
            return (DataTable)item;
        }
        /// <summary>
        /// 清空快取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public static bool Remove(string key)
        {
            return Redis.Remove(key);
        }
        /// <summary>
        /// 清空所有快取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public static void FlushAll()
        {
            Redis.FlushAll();
        }
    }

三、檢視資料

使用 redis-cli 就可以方便的檢視資料

D:\Redis>redis-cli
127.0.0.1:6379> set test 1000
OK
127.0.0.1:6379> get test
"1000"