Redis 學習筆記 安裝/啟動/測試/配置

  • 2019 年 12 月 9 日
  • 筆記

Docker 安裝 Redis

docker 安裝服務當然是非常簡單方便的。

獲取容器鏡像

$ docker pull redis

啟動第一個容器

$ docker run --name test-redis -p 6379:6379 -d redis

附加方式運行 redis-cli

$ docker exec -it test-redis redis-cli

測試一個鍵值對 (exec 進入容器後)

$ set name nick  #設置 key-value  $ get name #獲取鍵值 返回 "nick"

準備 .Net Core 項目用於測試

新建一個 .Net Core 的控制台程式,並添加 Redis 客戶端。

Redis 客戶端有很多,C# 的就有很多可供選擇,可以參考 https://redis.io/clients#c

這裡使用的是 StackExchange.Redis (https://stackexchange.github.io/StackExchange.Redis/)。

Nuget 或 使用包管理控制台指令:

dotnet add package StackExchange.Redis

最簡單的讀取測試

main.cs 中引用 StackExchange.Redis ,建立連接,獲取值

using System;  using StackExchange.Redis;    namespace ConsoleApp1  {      class Program      {          static void Main(string[] args)          {              //建立連接              ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("leepush.com");                //訪問 Redis 資料庫              IDatabase db = redis.GetDatabase();              var name = db.StringGet("name");  //通過Key 獲取值                Console.WriteLine("Hello World! " + $"{name}");          }      }  }

調試運行,就會輸出 「Hello World! nick」

寫入點啥

讀取是 String.Get,不用舉一反三,寫入自然是 Sting.Set

//建立連接  ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("leepush.com");    //訪問 Redis 資料庫  IDatabase db = redis.GetDatabase();  db.StringSet("age", 18);    var name = db.StringGet("name");  var age = db.StringGet("age");      Console.WriteLine($"{name} is {age} years old.");

運行結果 : 「nick is 18 years old.」

Redis 的數據類型

上面的讀寫操作都是使用的 String 數據類型,Redis 一共有如下幾種數據類型:

  • Key:就是鍵的意思
  • String:字元串
  • List:有序字元串的集合
  • Hashes:有點像對象,裡面可以有若干個欄位,欄位都有自己的值,欄位和值都是字元串類型的。
  • Set:無序唯一字元串的集合
  • Sorted-Set:跟Set很像,但是每一個字元串元素都對應一個浮點數值,該數值叫做分數。它裡面的元素通常是按照分數來排序的。
  • 參考 http://www.runoob.com/redis/redis-keys.html 中每個數據類型的介紹及命令

Redis 持久化

一共有兩種方式:

  • AOF(Append-only file)
  • RDB(Redis database file) 首先需要知道Redis的操作都是在記憶體中完成的,因為這樣速度快。

AOF

說重點:

  1. 每個操作都記錄到文件系統
  2. Redis伺服器重啟,自動重建,故文件逐漸變大
  3. Redis自動使用最新版本的數據,並壓縮文件

RDB

同樣說重點:

  1. Redis 默認模式,類似資料庫快照
  2. 時間點記錄寫入 RDB ,時間點恢復

最佳實踐是兩者都用,使用AOF因為其速度和可用性,使用RDB做災難恢復。

Redis 配置

Redis 標準配置文件 https://raw.githubusercontent.com/antirez/redis/4.0/redis.conf

看關鍵部分:

Redis 快照相關

檢索關鍵詞 – SNAPSHOTTING

################################ SNAPSHOTTING  ################################  #  # Save the DB on disk:  #  #   save <seconds> <changes>  #  #   Will save the DB if both the given number of seconds and the given  #   number of write operations against the DB occurred.  #  #   In the example below the behaviour will be to save:  #   after 900 sec (15 min) if at least 1 key changed  #   after 300 sec (5 min) if at least 10 keys changed  #   after 60 sec if at least 10000 keys changed  #  #   Note: you can disable saving completely by commenting out all "save" lines.  #  #   It is also possible to remove all the previously configured save  #   points by adding a save directive with a single empty string argument  #   like in the following example:  #  #   save ""    save 900 1  save 300 10  save 60 10000

裡面的save 900 1.

這部分是指,900秒過後,如果至少1個key改變了,那麼就做一個快照。

下面的就是300秒過後,如果10個key改變了,那就做一個快照。。。

這些就是進行快照動作的觸發條件。

AOF相關

檢索關鍵詞 – APPEND ONLY MODE

############################## APPEND ONLY MODE ###############################    # By default Redis asynchronously dumps the dataset on disk. This mode is  # good enough in many applications, but an issue with the Redis process or  # a power outage may result into a few minutes of writes lost (depending on  # the configured save points).  #  # The Append Only File is an alternative persistence mode that provides  # much better durability. For instance using the default data fsync policy  # (see later in the config file) Redis can lose just one second of writes in a  # dramatic event like a server power outage, or a single write if something  # wrong with the Redis process itself happens, but the operating system is  # still running correctly.  #  # AOF and RDB persistence can be enabled at the same time without problems.  # If the AOF is enabled on startup Redis will load the AOF, that is the file  # with the better durability guarantees.  #  # Please check http://redis.io/topics/persistence for more information.    appendonly no

AOF模式默認是不開啟的,也就是no。如果想開啟,那就改成yes即可。

Docker 使用自定義配置啟動容器

下載前文提到的默認配置文件,按需修改內容。

比如: 修改 快照RDB 條件 開啟 AOF

使用 curl 快速下載 curl -o redis.conf https://raw.githubusercontent.com/antirez/redis/4.0/redis.conf 然後使用 vim 編輯(/appendonly 查找)

然後使用 Docker 的指定 Volume 啟動 redis 容器

docker 刪除容器 先stop 容器,然後使用 rm 刪除容器

使用如下指令來創建一個自定義的 Redis 服務容器

docker run -v /home/ubuntu/redis/redis.conf:/usr/local/etc/redis/redis.conf --name custom-redis -p 6379:6379 redis redis-server /usr/local/etc/redis/redis.conf

說明: -v這部分是指volume,redis.conf在我伺服器里的位置是:/home/ubuntu/redis/redis.conf,所以我把該位文件的位置掛載到了容器里的/usr/local/etc/redis/redis.conf這個地方。然後運行redis這個鏡像,同時運行裡面的redis-server,而redis-server的配置文件就是/usr/local/etc/redis/redis.conf。

運行成功後,重開一個終端連入伺服器,使用 docker ps 查看容器id

$ docker exec -it ebd8 redis  # 這裡的 ebd8 就是我的容器id前四位

此時前面配置的條件如果觸發,監控終端就會輸出提示。