Redis基礎知識詳解(非原創)

文章大綱

1、Redis介紹
2、Redis安裝並設置開機自動啓動
3、Redis文件結構
4、Redis啓動方式
5、Redis持久化
6、Redis配置文件詳解
7、Redis圖形化工具
8、Java之Jedis鏈接Redis單機
9、項目源碼與資料下載
10、參考文章php

 

1、Redis介紹

1. 什麼是Redis

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

2. Redis特徵

 

(1)Redis是把數據存在內存中,因此速度纔會快。Redis是用C語言寫的開源項目。
(2)Redis全部數據保存在內存中,對數據的更新將異步地保存到磁盤上,這樣能夠作到斷電不丟失數據。
(3)Redis主從複製能夠實現高可用和分佈式java

 

3. Redis數據結構

3.1 字符串node

 

3.2 Hashlinux

 
 

3.3 listgit

 
 

3.4 setgithub

 

3.5 zsetredis

 

4. Redis的應用場景

(1)緩存(數據查詢、短鏈接、新聞內容、商品內容等等)(最多使用)算法

 

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

 

(5)應用排行榜

 

(6)網站訪問統計

 

(7)數據過時處理(能夠精確到毫秒)

舒適提示:在使用場景中,不用考慮數據混亂因素,由於redis的增刪查改是單線程執行的。

2、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綁定。

3、Redis文件結構

 

4、Redis啓動方式

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

 
 

5、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,具體可看下圖:

 

6、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. # # 設置認證密碼 # requirepass foobared # Command renaming. # # It is possible to change the name of dangerous commands in a shared # environment. For instance the CONFIG command may be renamed into something # hard to guess so that it will still be available for internal-use tools # but not available for general clients. # # Example: # # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 # # It is also possible to completely kill a command by renaming it into # an empty string: # # rename-command CONFIG "" # # Please note that changing the name of commands that are logged into the # AOF file or transmitted to slaves may cause problems. ################################### 限制 #################################### # Set the max number of connected clients at the same time. By default # this limit is set to 10000 clients, however if the Redis server is not # able to configure the process file limit to allow for the specified limit # the max number of allowed clients is set to the current file limit # minus 32 (as Redis reserves a few file descriptors for internal uses). # # 一旦達到最大限制,redis 將關閉全部的新鏈接 # 併發送一個‘max number of clients reached’的錯誤。 # # maxclients 10000 # 若是你設置了這個值,當緩存的數據容量達到這個值, redis 將根據你選擇的 # eviction 策略來移除一些 keys。 # # 若是 redis 不能根據策略移除 keys ,或者是策略被設置爲 ‘noeviction’, # redis 將開始響應錯誤給命令,如 set,lpush 等等, # 並繼續響應只讀的命令,如 get # # This option is usually useful when using Redis as an LRU cache, or to set # a hard memory limit for an instance (using the 'noeviction' policy). # # WARNING: If you have slaves attached to an instance with maxmemory on, # the size of the output buffers needed to feed the slaves are subtracted # from the used memory count, so that network problems / resyncs will # not trigger a loop where keys are evicted, and in turn the output # buffer of slaves is full with DELs of keys evicted triggering the deletion # of more keys, and so forth until the database is completely emptied. # # In short... if you have slaves attached it is suggested that you set a lower # limit for maxmemory so that there is some free RAM on the system for slave # output buffers (but this is not needed if the policy is 'noeviction'). # # 最大使用內存 # maxmemory <bytes> # 最大內存策略,你有 5 個選擇。 # # volatile-lru -> remove the key with an expire set using an LRU algorithm # volatile-lru -> 使用 LRU 算法移除包含過時設置的 key 。 # allkeys-lru -> remove any key accordingly to the LRU algorithm # allkeys-lru -> 根據 LRU 算法移除全部的 key 。 # volatile-random -> remove a random key with an expire set # allkeys-random -> remove a random key, any key # volatile-ttl -> remove the key with the nearest expire time (minor TTL) # noeviction -> don't expire at all, just return an error on write operations # noeviction -> 不讓任何 key 過時,只是給寫入操做返回一個錯誤 # # Note: with any of the above policies, Redis will return an error on write # operations, when there are not suitable keys for eviction. # # At the date of writing this commands are: set setnx setex append # incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd # sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby # zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby # getset mset msetnx exec sort # # The default is: # # maxmemory-policy noeviction # LRU and minimal TTL algorithms are not precise algorithms but approximated # algorithms (in order to save memory), so you can tune it for speed or # accuracy. For default Redis will check five keys and pick the one that was # used less recently, you can change the sample size using the following # configuration directive. # # The default of 5 produces good enough results. 10 Approximates very closely # true LRU but costs a bit more CPU. 3 is very fast but not very accurate. # # maxmemory-samples 5 ############################## 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 # The name of the append only file (default: "appendonly.aof") appendfilename "appendonly.aof" # The fsync() call tells the Operating System to actually write data on disk # instead to wait for more data in the output buffer. Some OS will really flush # data on disk, some other OS will just try to do it ASAP. # # Redis supports three different modes: # # no: don't fsync, just let the OS flush the data when it wants. Faster. # always: fsync after every write to the append only log . Slow, Safest. # everysec: fsync only one time every second. Compromise. # # The default is "everysec", as that's usually the right compromise between # speed and data safety. It's up to you to understand if you can relax this to # "no" that will let the operating system flush the output buffer when # it wants, for better performances (but if you can live with the idea of # some data loss consider the default persistence mode that's snapshotting), # or on the contrary, use "always" that's very slow but a bit safer than # everysec. # # More details please check the following article: # http://antirez.com/post/redis-persistence-demystified.html # # If unsure, use "everysec". # appendfsync always appendfsync everysec # appendfsync no # When the AOF fsync policy is set to always or everysec, and a background # saving process (a background save or AOF log background rewriting) is # performing a lot of I/O against the disk, in some Linux configurations # Redis may block too long on the fsync() call. Note that there is no fix for # this currently, as even performing fsync in a different thread will block # our synchronous write(2) call. # # In order to mitigate this problem it's possible to use the following option # that will prevent fsync() from being called in the main process while a # BGSAVE or BGREWRITEAOF is in progress. # # This means that while another child is saving, the durability of Redis is # the same as "appendfsync none". In practical terms, this means that it is # possible to lose up to 30 seconds of log in the worst scenario (with the # default Linux settings). # # If you have latency problems turn this to "yes". Otherwise leave it as # "no" that is the safest pick from the point of view of durability. no-appendfsync-on-rewrite no 

7、Redis圖形化工具

1. Redis Desktop Manager

一款基於Qt5的跨平臺Redis桌面管理軟件

 

支持: Windows 7+, Mac OS X 10.10+, Ubuntu 14+
特色: C++ 編寫,響應迅速,性能好。但不支持數據庫備份與恢復。
項目地址: https://github.com/uglide/RedisDesktopManager

2. Redis Client

 

項目簡介: 使用Java編寫,功能豐富,缺點是性能稍差,網絡很差時,會不時斷線。
項目地址: https://github.com/caoxinyu/RedisClient

3. Redis Studio

 

項目簡介: 又一個C++編寫的redis管理工具,僅支持windows平臺,支持xp操做系統。
項目地址: https://github.com/cinience/RedisStudio

8、Java之Jedis鏈接Redis單機

  鏈接Redis的Java客戶端可使用Jedis,Jedis 是 Redis 官方首選的 Java 客戶端開發包。在這裏咱們是進行Redis基礎講解,因此先測試Redis單機,在下一篇文章中,咱們將進行集羣搭建與鏈接測試。

1. 鏈接前準備

確保Redis的服務已經開啓

 

確保在Reids的配置文件中添加訪問客戶端的IP

 

2. 使用idea新建maven項目

 
 
 
 

建立後的項目結構以下:

 

3. pom.xml文件添加jar包依賴

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wxc</groupId> <artifactId>com-redis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--添加測試依賴--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--添加redis依賴--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> 

4. 新建TestRedis.java類進行Redis鏈接與增刪改查

 
package com.wxc.redis;

import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class TestRedis { private Jedis jedis; @Before public void setJedis() { //鏈接redis服務器(在這裏是鏈接本地的) jedis = new Jedis("192.168.101.6", 6379); //權限認證,當開啓密碼了就須要 jedis.auth("147258qq"); System.out.println("鏈接服務成功"); } /** * Redis操做字符串 */ @Test public void testString() { //添加數據 jedis.set("name", "chx"); //key爲name放入value值爲chx System.out.println("拼接前:" + jedis.get("name"));//讀取key爲name的值 //向key爲name的值後面加上數據 ---拼接 jedis.append("name", " is my name;"); System.out.println("拼接後:" + jedis.get("name")); //刪除某個鍵值對 jedis.del("name"); System.out.println("刪除後:" + jedis.get("name")); //s設置多個鍵值對 jedis.mset("name", "chenhaoxiang", "age", "20", "email", "chxpostbox@outlook.com"); jedis.incr("age");//用於將鍵的整數值遞增1。若是鍵不存在,則在執行操做以前將其設置爲0。 若是鍵包含錯誤類型的值或包含沒法表示爲整數的字符串,則會返回錯誤。此操做限於64位有符號整數。 System.out.println(jedis.get("name") + " " + jedis.get("age") + " " + jedis.get("email")); } @Test public void testMap() { //添加數據 Map<String, String> map = new HashMap<String, String>(); map.put("name", "chx"); map.put("age", "100"); map.put("email", "***@outlook.com"); jedis.hmset("user", map); //取出user中的name,結果是一個泛型的List //第一個參數是存入redis中map對象的key,後面跟的是放入map中的對象的key,後面的key是可變參數 List<String> list = jedis.hmget("user", "name", "age", "email"); System.out.println(list); //刪除map中的某個鍵值 jedis.hdel("user", "age"); System.out.println("age:" + jedis.hmget("user", "age")); //由於刪除了,因此返回的是null System.out.println("user的鍵中存放的值的個數:" + jedis.hlen("user")); //返回key爲user的鍵中存放的值的個數2 System.out.println("是否存在key爲user的記錄:" + jedis.exists("user"));//是否存在key爲user的記錄 返回true System.out.println("user對象中的全部key:" + jedis.hkeys("user"));//返回user對象中的全部key System.out.println("user對象中的全部value:" + jedis.hvals("user"));//返回map對象中的全部value //拿到key,再經過迭代器獲得值 Iterator<String> iterator = jedis.hkeys("user").iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println(key + ":" + jedis.hmget("user", key)); } jedis.del("user"); System.out.println("刪除後是否存在key爲user的記錄:" + jedis.exists("user"));//是否存在key爲user的記錄 } /** * jedis操做List */ @Test public void testList(){ //移除javaFramwork所全部內容 jedis.del("javaFramwork"); //存放數據 jedis.lpush("javaFramework","spring"); jedis.lpush("javaFramework","springMVC"); jedis.lpush("javaFramework","mybatis"); //取出全部數據,jedis.lrange是按範圍取出 //第一個是key,第二個是起始位置,第三個是結束位置 System.out.println("長度:"+jedis.llen("javaFramework")); //jedis.llen獲取長度,-1表示取得全部 System.out.println("javaFramework:"+jedis.lrange("javaFramework",0,-1)); jedis.del("javaFramework"); System.out.println("刪除後長度:"+jedis.llen("javaFramework")); System.out.println(jedis.lrange("javaFramework",0,-1)); } /** * jedis操做Set */ @Test public void testSet(){ //添加 jedis.sadd("user","chenhaoxiang"); jedis.sadd("user","hu"); jedis.sadd("user","chen"); jedis.sadd("user","xiyu"); jedis.sadd("user","chx"); jedis.sadd("user","are"); //移除user集合中的元素are jedis.srem("user","are"); System.out.println("user中的value:"+jedis.smembers("user"));//獲取全部加入user的value System.out.println("chx是不是user中的元素:"+jedis.sismember("user","chx"));//判斷chx是不是user集合中的元素 System.out.println("集合中的一個隨機元素:"+jedis.srandmember("user"));//返回集合中的一個隨機元素 System.out.println("user中元素的個數:"+jedis.scard("user")); } /** * 排序 */ @Test public void test(){ jedis.del("number");//先刪除數據,再進行測試 jedis.rpush("number","4");//將一個或多個值插入到列表的尾部(最右邊) jedis.rpush("number","5"); jedis.rpush("number","3"); jedis.lpush("number","9");//將一個或多個值插入到列表頭部 jedis.lpush("number","1"); jedis.lpush("number","2"); System.out.println(jedis.lrange("number",0,jedis.llen("number"))); System.out.println("排序:"+jedis.sort("number")); System.out.println(jedis.lrange("number",0,-1));//不改變原來的排序 jedis.del("number");//測試完刪除數據 } } 

5. 運行項目

 

9、項目源碼與資料下載

連接:https://pan.baidu.com/s/1ckd7J1JamotpQAxUQ05Ueg
提取碼:lpa3

10、參考文章

  1. https://www.cnblogs.com/wangfajun/p/5787077.html
  2. https://www.cnblogs.com/kreo/p/4423362.html
  3. https://blog.csdn.net/wdeng2011/article/details/78149719
  4. https://www.2cto.com/database/201807/762681.html
  5. https://blog.csdn.net/mhshencaobo/article/details/86136910
  6. https://www.cnblogs.com/zxtceq/p/7676862.html
  7. https://www.cnblogs.com/jaign/articles/7920588.html
相關文章
相關標籤/搜索