文章大綱
一、Redis介紹
二、Redis安裝並設置開機自動啟動
三、Redis文件結構
四、Redis啟動方式
五、Redis持久化
六、Redis配置文件詳解
七、Redis圖形化工具
八、Java之Jedis連接Redis單機
九、項目源碼與資料下載
十、參考文章

一、Redis介紹
1. 什么是Redis
Redis是用C語言開發的一個開源的高性能鍵值對(key-value)數據庫。建議在linux上運行,它通過提供多種鍵值數據類型來適應不同場景下的存儲需求,數據存儲在內存中,也可持久化到磁盤中,目前為止Redis支持的鍵值數據類型如下:
(1)字符串類型
(2)散列類型
(3)列表類型
(4)集合類型
(5)有序集合類型
2. Redis特征

(1)Redis是把數據存在內存中,所以速度才會快。Redis是用C語言寫的開源項目。
(2)Redis所有數據保存在內存中,對數據的更新將異步地保存到磁盤上,這樣可以做到斷電不丟失數據。
(3)Redis主從復制可以實現高可用和分布式

3. Redis數據結構
3.1 字符串

3.2 Hash


3.3 list


3.4 set

3.5 zset

4. Redis的應用場景
(1)緩存(數據查詢、短連接、新聞內容、商品內容等等)(最多使用)

(2)分布式集群架構中的session分離
(3)聊天室的在線好友列表
(4)任務隊列。(秒殺、搶購、12306等等)

(5)應用排行榜

(6)網站訪問統計

(7)數據過期處理(可以精確到毫秒)
溫馨提示:在使用場景中,不用考慮數據混亂因素,因為redis的增刪查改是單線程執行的。
二、Redis安裝並設置開機自動啟動
Redis的使用在Linux中效果會更佳,該文章主要體現教程,因此我以windows作為例子進行安裝。
1. 安裝
要安裝Redis,首先要獲取安裝包。Windows的Redis安裝包需要到以下GitHub鏈接找到。鏈接:https://github.com/MSOpenTech/redis。打開網站后,找到Release,點擊前往下載頁面。

在下載網頁中,找到最后發行的版本(此處是3.2.100)。找到Redis-x64-3.2.100.msi和Redis-x64-3.2.100.zip,點擊下載。這里說明一下,第一個是msi微軟格式的安裝包,第二個是壓縮包

雙擊剛下載好的msi格式的安裝包(Redis-x64-3.2.100.msi)開始安裝。

選擇“同意協議”,點擊下一步繼續。

選擇“添加Redis目錄到環境變量PATH中”,這樣方便系統自動識別Redis執行文件在哪里。

端口號可保持默認的6379,並選擇防火牆例外,從而保證外部可以正常訪問Redis服務。

設定最大值為100M。作為實驗和學習,100M足夠了。

安裝完畢后,需要先做一些設定工作,以便服務啟動后能正常運行。使用文本編輯器,這里使用Notepad++,打開Redis服務配置文件。注意:不要找錯了,通常為redis.windows-service.conf,而不是redis.windows.conf。后者是以非系統服務方式啟動程序使用的配置文件。

找到含有requirepass字樣的地方,追加一行,輸入requirepass 147258qq。這是訪問Redis時所需的密碼,一般測試情況下可以不用設定密碼。不過,即使是作為本地訪問,也建議設定一個密碼。此處以簡單的147258qq來演示。

點擊“開始”>右擊“計算機”>選擇“管理”。在左側欄中依次找到並點擊“計算機管理(本地)”>服務和應用程序>服務。再在右側找到Redis名稱的服務,查看啟動情況。如未啟動,則手動啟動之。正常情況下,服務應該正常啟動並運行了。

最后來測試一下Redis是否正常提供服務。進入Redis的目錄,cd C:\Program Files\Redis。輸入redis-cli並回車。(redis-cli是客戶端程序)如圖正常提示進入,並顯示正確端口號,則表示服務已經啟動。

使用服務前需要先通過密碼驗證。輸入“auth 147258qq”並回車(12345是之前設定的密碼)。返回提示OK表示驗證通過。

實際測試一下讀寫。輸入set mykey1 "I love you all!”並回車,用來保存一個鍵值。再輸入get mykey1,獲取剛才保存的鍵值。


2. 設置開機自動啟動
設置服務命令:redis-server --service-install redis.windows-service.conf --loglevel verbose

輸入命令之后沒有報錯,表示成功了,刷新服務,會看到多了一個redis服務。

右鍵Redis並選擇屬性

設置啟動類型為自動

常用的redis服務命令。
卸載服務:redis-server --service-uninstall
開啟服務:redis-server --service-start
停止服務:redis-server --service-stop
溫馨提示
(1)Windows使用的這個Redis是64位版本的,32位操作系統的同學就不要折騰了。
(2)作為服務運行的Redis配置文件,通常為redis.windows-service.conf,而不是redis.windows.conf。小心不要選錯了。如果修改了redis.windows.conf(非redis.windows-service.conf)文件上的配置,從服務自啟動,配置的信息是不生效的,如密碼配置和ip綁定。
三、Redis文件結構

四、Redis啟動方式
Redis有三種啟動方式,具體如下:
(1)使用redis-server命令,會以默認的redis配置進行啟動
(2)使用redis-server –port6379就可以使用動態參數配置進行啟動
(3)使用redis-server configPath就可以使用配置文件方式進行啟動
(4)當直接運行redis-service.exe時候,是沒有使用配置文件的,而且會提示以下內容:


五、Redis持久化
1. 持久化作用

2. 持久化方式

3. RDB
3.1 什么是RDB

3.2 RDB文件生成方式

save方式

bgsave方式

Save與bgsave比較

自動生成RDB

3.3 RDB總結

4. AOF
4.1 RDB問題

因為RDB需要將全部數據生成RDB文件,所以這個過程比較耗時,如果用fork(bgsave)過程,則太消耗內容。如果RDB文件非常大,還會影響IO性能。
在T3-T4之間就會出現數據丟失。

4.2 AOF文件創建和恢復
創建時:

恢復時:

4.3 AOF三種策略

Always策略

Everysec策略
每秒寫入一次數據,如果機器突然有問題,可能丟失一秒數據

No策略
根據操作系統策略自行選擇

三種策略比較

4.4 AOF重寫
把過期的,重復的,可優化命令進行化解。

重寫作用

重寫方式

Bgrewriteaof命令

AOF重寫配置

AOF重寫流程

5. RDB與AOF選擇

6. Redis默認的持久化
Redis默認的持久化方式是RDB,具體可看下圖:

六、Redis配置文件詳解
Redis常用的配置文件在redis.windows-service.conf,具體配置包括設置登錄密碼、設置持久化方式、持久化路徑、最大的內存空間、數據庫數量、日志的等級、日志的路徑、設置允許客戶端連接的IP等,主從復制、高可用、集群、緩存等相關的功能將在下一篇進行講解。

# redis 配置文件示例 # 當你需要為某個配置項指定內存大小的時候,必須要帶上單位, # 通常的格式就是 1k 5gb 4m 等醬紫: # # 1k => 1000 bytes # 1kb => 1024 bytes # 1m => 1000000 bytes # 1mb => 1024*1024 bytes # 1g => 1000000000 bytes # 1gb => 1024*1024*1024 bytes # # 單位是不區分大小寫的,你寫 1K 5GB 4M 也行 ################################## INCLUDES ################################### # 假如說你有一個可用於所有的 redis server 的標准配置模板, # 但針對某些 server 又需要一些個性化的設置, # 你可以使用 include 來包含一些其他的配置文件,這對你來說是非常有用的。 # # 但是要注意哦,include 是不能被 config rewrite 命令改寫的 # 由於 redis 總是以最后的加工線作為一個配置指令值,所以你最好是把 include 放在這個文件的最前面, # 以避免在運行時覆蓋配置的改變,相反,你就把它放在后面(外國人真啰嗦)。 # # include /path/to/local.conf # include /path/to/other.conf ################################ 常用 ##################################### # 默認情況下 redis 不是作為守護進程運行的,如果你想讓它在后台運行,你就把它改成 yes。 # 當redis作為守護進程運行的時候,它會寫一個 pid 到 /var/run/redis.pid 文件里面。 daemonize no # 當redis作為守護進程運行的時候,它會把 pid 默認寫到 /var/run/redis.pid 文件里面, # 但是你可以在這里自己制定它的文件位置。 pidfile /var/run/redis.pid # 監聽端口號,默認為 6379,如果你設為 0 ,redis 將不在 socket 上監聽任何客戶端連接。 port 6379 # TCP 監聽的最大容納數量 # # 在高並發的環境下,你需要把這個值調高以避免客戶端連接緩慢的問題。 # Linux 內核會一聲不響的把這個值縮小成 /proc/sys/net/core/somaxconn 對應的值, # 所以你要修改這兩個值才能達到你的預期。 tcp-backlog 511 # 默認情況下,redis 在 server 上所有有效的網絡接口上監聽客戶端連接。 # 你如果只想讓它在一個網絡接口上監聽,那你就綁定一個IP或者多個IP。 # # 示例,多個IP用空格隔開: # # bind 192.168.1.100 10.0.0.1 # bind 127.0.0.1 # 指定 unix socket 的路徑。 # # unixsocket /tmp/redis.sock # unixsocketperm 755 # 指定在一個 client 空閑多少秒之后關閉連接(0 就是不管它) timeout 0 # tcp 心跳包。 # # 如果設置為非零,則在與客戶端缺乏通訊的時候使用 SO_KEEPALIVE 發送 tcp acks 給客戶端。 # 這個之所有有用,主要由兩個原因: # # 1) 防止死的 peers # 2) Take the connection alive from the point of view of network # equipment in the middle. # # On Linux, the specified value (in seconds) is the period used to send ACKs. # Note that to close the connection the double of the time is needed. # On other kernels the period depends on the kernel configuration. # # A reasonable value for this option is 60 seconds. # 推薦一個合理的值就是60秒 tcp-keepalive 0 # 定義日志級別。 # 可以是下面的這些值: # debug (適用於開發或測試階段) # verbose (many rarely useful info, but not a mess like the debug level) # notice (適用於生產環境) # warning (僅僅一些重要的消息被記錄) loglevel notice # 指定日志文件的位置 logfile "" # 要想把日志記錄到系統日志,就把它改成 yes, # 也可以可選擇性的更新其他的syslog 參數以達到你的要求 # syslog-enabled no # 設置 syslog 的 identity。 # syslog-ident redis # 設置 syslog 的 facility,必須是 USER 或者是 LOCAL0-LOCAL7 之間的值。 # syslog-facility local0 # 設置數據庫的數目。 # 默認數據庫是 DB 0,你可以在每個連接上使用 select <dbid> 命令選擇一個不同的數據庫, # 但是 dbid 必須是一個介於 0 到 databasees - 1 之間的值 databases 16 ################################ 快照 ################################ # # 存 DB 到磁盤: # # 格式:save <間隔時間(秒)> <寫入次數> # # 根據給定的時間間隔和寫入次數將數據保存到磁盤 # # 下面的例子的意思是: # 900 秒內如果至少有 1 個 key 的值變化,則保存 # 300 秒內如果至少有 10 個 key 的值變化,則保存 # 60 秒內如果至少有 10000 個 key 的值變化,則保存 # # 注意:你可以注釋掉所有的 save 行來停用保存功能。 # 也可以直接一個空字符串來實現停用: # save "" save 900 1 save 300 10 save 60 10000 # 默認情況下,如果 redis 最后一次的后台保存失敗,redis 將停止接受寫操作, # 這樣以一種強硬的方式讓用戶知道數據不能正確的持久化到磁盤, # 否則就會沒人注意到災難的發生。 # # 如果后台保存進程重新啟動工作了,redis 也將自動的允許寫操作。 # # 然而你要是安裝了靠譜的監控,你可能不希望 redis 這樣做,那你就改成 no 好了。 stop-writes-on-bgsave-error yes # 是否在 dump .rdb 數據庫的時候使用 LZF 壓縮字符串 # 默認都設為 yes # 如果你希望保存子進程節省點 cpu ,你就設置它為 no , # 不過這個數據集可能就會比較大 rdbcompression yes # 是否校驗rdb文件 rdbchecksum yes # 設置 dump 的文件位置 dbfilename dump.rdb # 工作目錄 # 例如上面的 dbfilename 只指定了文件名, # 但是它會寫入到這個目錄下。這個配置項一定是個目錄,而不能是文件名。 dir ./ ################################# 主從復制 ################################# # 主從復制。使用 slaveof 來讓一個 redis 實例成為另一個reids 實例的副本。 # 注意這個只需要在 slave 上配置。 # # slaveof <masterip> <masterport> # 如果 master 需要密碼認證,就在這里設置 # masterauth <master-password> # 當一個 slave 與 master 失去聯系,或者復制正在進行的時候, # slave 可能會有兩種表現: # # 1) 如果為 yes ,slave 仍然會應答客戶端請求,但返回的數據可能是過時, # 或者數據可能是空的在第一次同步的時候 # # 2) 如果為 no ,在你執行除了 info he salveof 之外的其他命令時, # slave 都將返回一個 "SYNC with master in progress" 的錯誤, # slave-serve-stale-data yes # 你可以配置一個 slave 實體是否接受寫入操作。 # 通過寫入操作來存儲一些短暫的數據對於一個 slave 實例來說可能是有用的, # 因為相對從 master 重新同步數而言,據數據寫入到 slave 會更容易被刪除。 # 但是如果客戶端因為一個錯誤的配置寫入,也可能會導致一些問題。 # # 從 redis 2.6 版起,默認 slaves 都是只讀的。 # # Note: read only slaves are not designed to be exposed to untrusted clients # on the internet. It's just a protection layer against misuse of the instance. # Still a read only slave exports by default all the administrative commands # such as CONFIG, DEBUG, and so forth. To a limited extent you can improve # security of read only slaves using 'rename-command' to shadow all the # administrative / dangerous commands. # 注意:只讀的 slaves 沒有被設計成在 internet 上暴露給不受信任的客戶端。 # 它僅僅是一個針對誤用實例的一個保護層。 slave-read-only yes # Slaves 在一個預定義的時間間隔內發送 ping 命令到 server 。 # 你可以改變這個時間間隔。默認為 10 秒。 # # repl-ping-slave-period 10 # The following option sets the replication timeout for: # 設置主從復制過期時間 # # 1) Bulk transfer I/O during SYNC, from the point of view of slave. # 2) Master timeout from the point of view of slaves (data, pings). # 3) Slave timeout from the point of view of masters (REPLCONF ACK pings). # # It is important to make sure that this value is greater than the value # specified for repl-ping-slave-period otherwise a timeout will be detected # every time there is low traffic between the master and the slave. # 這個值一定要比 repl-ping-slave-period 大 # # repl-timeout 60 # Disable TCP_NODELAY on the slave socket after SYNC? # # If you select "yes" Redis will use a smaller number of TCP packets and # less bandwidth to send data to slaves. But this can add a delay for # the data to appear on the slave side, up to 40 milliseconds with # Linux kernels using a default configuration. # # If you select "no" the delay for data to appear on the slave side will # be reduced but more bandwidth will be used for replication. # # By default we optimize for low latency, but in very high traffic conditions # or when the master and slaves are many hops away, turning this to "yes" may # be a good idea. repl-disable-tcp-nodelay no # 設置主從復制容量大小。這個 backlog 是一個用來在 slaves 被斷開連接時 # 存放 slave 數據的 buffer,所以當一個 slave 想要重新連接,通常不希望全部重新同步, # 只是部分同步就夠了,僅僅傳遞 slave 在斷開連接時丟失的這部分數據。 # # The biggest the replication backlog, the longer the time the slave can be # disconnected and later be able to perform a partial resynchronization. # 這個值越大,salve 可以斷開連接的時間就越長。 # # The backlog is only allocated once there is at least a slave connected. # # repl-backlog-size 1mb # After a master has no longer connected slaves for some time, the backlog # will be freed. The following option configures the amount of seconds that # need to elapse, starting from the time the last slave disconnected, for # the backlog buffer to be freed. # 在某些時候,master 不再連接 slaves,backlog 將被釋放。 # # A value of 0 means to never release the backlog. # 如果設置為 0 ,意味着絕不釋放 backlog 。 # # repl-backlog-ttl 3600 # 當 master 不能正常工作的時候,Redis Sentinel 會從 slaves 中選出一個新的 master, # 這個值越小,就越會被優先選中,但是如果是 0 , 那是意味着這個 slave 不可能被選中。 # # 默認優先級為 100。 slave-priority 100 # It is possible for a master to stop accepting writes if there are less than # N slaves connected, having a lag less or equal than M seconds. # # The N slaves need to be in "online" state. # # The lag in seconds, that must be <= the specified value, is calculated from # the last ping received from the slave, that is usually sent every second. # # This option does not GUARANTEES that N replicas will accept the write, but # will limit the window of exposure for lost writes in case not enough slaves # are available, to the specified number of seconds. # # For example to require at least 3 slaves with a lag <= 10 seconds use: # # min-slaves-to-write 3 # min-slaves-max-lag 10 # # Setting one or the other to 0 disables the feature. # # By default min-slaves-to-write is set to 0 (feature disabled) and # min-slaves-max-lag is set to 10. ################################## 安全 ################################### # Require clients to issue AUTH <PASSWORD> before processing any other # commands. This might be useful in environments in which you do not trust # others with access to the host running redis-server. # # This should stay commented out for backward compatibility and because most # people do not need auth (e.g. they run their own servers). # # Warning: since Redis is pretty fast an outside user can try up to # 150k passwords per second against a good box. This means that you should # use a very strong password otherwise it will be very easy to break. # # 設置認證密碼