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


文章大綱

一、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. # # 設置認證密碼 # 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 

七、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

八、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. 運行項目

 

九、項目源碼與資料下載

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

十、參考文章

  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
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM