# 在 Debian 9 中安裝 Redis 並使其成為 Service

# 好好使用暫存,可以讓你發現新天地

Redis 是一個將資料暫存於 memoryNoSQL Database

其以 key : value 儲存資料的方式以及易讀易寫的特性,能夠減輕 MySQL Database 的負擔。

以下就來介紹,Redis 的安裝方式與基本使用方法。

# 下載、解壓縮、編譯 Redis

$ wget http://download.redis.io/redis-stable.tar.gz
$ tar xvzf redis-stable.tar.gz
$ cd redis-stable
$ make

在編譯完成後,你可以使用 make test 嘗試看看是否安裝正確。

$ make test

接下來使用 make install 安裝 Redis 相關的指令於 /usr/local/bin

$ make install

# 安裝 Redis Service

在 make redis 之後, util 裡面應該會多出一個 install_server.sh 的檔案。

執行 install_server.sh

$ > ./redis-stable/utils/install_server.sh

此時系統會開始詢問你:

設定使用的 port (預設 6379)

Please select the redis port for this instance: [6379]

設定使用的 config 位置 (預設 /etc/redis/6379.conf)

Please select the redis config file name [/etc/redis/6379.conf]

設定 log 位置 (預設 /var/log/redis_6379.log)

Please select the redis log file name [/var/log/redis_6379.log]

設定資料儲存目錄 (預設 /var/lib/redis/6379)

Please select the data directory for this instance [/var/lib/redis/6379]

設定 redis 執行檔位置 (預設 /usr/local/bin/redis-server)

Please select the redis executable path [/usr/local/bin/redis-server]

確認設定是否正確

Selected config:
Port           : 6379
Config file    : /etc/6379.conf
Log file       : /var/log/redis_6379.log
Data dir       : /var/lib/redis/6379
Executable     : /usr/local/bin/redis-server
Cli Executable : /usr/local/bin/redis-cli
Is this ok? Then press ENTER to go on or Ctrl-C to abort.

安裝成功

Copied /tmp/6379.conf => /etc/init.d/redis_6379
Installing service...
Successfully added to chkconfig!
Successfully added to runlevels 345!
Starting Redis server...
Installation successful!

接下來只要重新啟動即可讓 redis 在背景運作了。

$ sudo reboot

# 確認 Redis Server 有正確使用。

可以使用 redis-cli 來與 redis server 互動

輸入 redis-cli

$ redis-cli

會進入 redis server 的環境,此時輸入 pingredis server 應該要能回應 pong

redis> ping
PONG

如此。就算成功了!

以下一些 Redis 常用的指令:

最基礎的用法就是塞值、取值

塞入 “test_value” 到 key

redis> set key 'test_value'
OK

讀取 key 中的 "test_value"

redis> get key
"test_value"

你也可以塞入 JSON

redis> set testJson '{"a": 1, "b": "string"}'
OK

取出方式一樣

redis> get testJson
"{\"a\": 1, \"b\": \"string\"}"

刪除 key

redis> del key # 刪除 key
(integer) 1

查看 redis 中所有的 key

redis> KEYS *
1) "testJson"

KEYS 還可以使用模糊搜尋

  • ? : 匹配一個不為空的字符
  • * : 匹配 0~ 多個所有字符
  • [aeiou] : 匹配 a , e , i , o , u
  • [^s] : 匹配 不為 s 的字符
  • [a-z] : 匹配 a 到 z 的字符 Ex.
# ? : 匹配一個不為空的字符
$ redis> keys test?son
1) "testJson"
2) "testason"
# * : 匹配0~多個所有字符
redis> keys *son
1) "testJson"
2) "testson"
3) "testason"
redis> keys *s*
1) "testJson"
2) "casheTest"
3) "testson"
4) "testason"
redis> keys so*
1) "testJson"
2) "casheTest"
3) "testson"
4) "testason"
redis> keys so*
(empty list or set)
redis> keys testJso*
1) "testJson"
# [aeiou] : 匹配 a, e, i, o, u
redis> keys test[aeiou]son
1) "testason"
# [^J] : 匹配 不為 J 的字符
redis> keys test[^J]son
1) "testason"

清除所有內容

redis> flushall
OK

Like z20240z's work