Redis(REmote DIctionary Server)基礎
html
做者:尹正傑node
版權聲明:原創做品,謝絕轉載!不然將追究法律責任。linux
Redis是一個開放源代碼(BSD許可)的內存數據結構存儲,用做數據庫、緩存和消息代理。它支持字符串、哈希、列表、集合、帶範圍查詢的排序集合、位圖、超日誌、帶半徑查詢和流的地理空間索引等數據結構。Redis具備內置的複製、Lua腳本、LRU收回、事務和不一樣級別的磁盤上持久性,並經過Redis Sentinel和Redis羣集的自動分區提供高可用性。官方地址:https://redis.io/nginx
在生產環境中Redis通常有三種用途,能夠用做數據庫(Database),緩存(Cache),消息隊列(Message Queue)。所以不關你是開發仍是運維人員,學習一下Redis仍是頗有必要的!redis
一.安裝Redis算法
1>.本篇博客操做環境介紹數據庫
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# uname -r 3.10.0-957.el7.x86_64 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# uname -m x86_64 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
2>.安裝epel源後端
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll /etc/yum.repos.d/ #安裝epel源以前 total 4 drwxr-xr-x. 2 root root 30 Mar 23 22:29 back -rw-r--r--. 1 root root 2523 Mar 23 22:26 CentOS-Base.repo drwxr-xr-x. 2 root root 187 Mar 23 22:26 default [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# yum -y install epel-release Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.aliyun.com * extras: mirrors.aliyun.com * updates: mirrors.aliyun.com Resolving Dependencies --> Running transaction check ---> Package epel-release.noarch 0:7-11 will be installed --> Finished Dependency Resolution Dependencies Resolved ============================================================================================================================================== Package Arch Version Repository Size ============================================================================================================================================== Installing: epel-release noarch 7-11 extras 15 k Transaction Summary ============================================================================================================================================== Install 1 Package Total download size: 15 k Installed size: 24 k Downloading packages: Delta RPMs disabled because /usr/bin/applydeltarpm not installed. epel-release-7-11.noarch.rpm | 15 kB 00:00:02 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : epel-release-7-11.noarch 1/1 Verifying : epel-release-7-11.noarch 1/1 Installed: epel-release.noarch 0:7-11 Complete! [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll /etc/yum.repos.d/ #安裝epel源以後,會生成2個文件 total 12 drwxr-xr-x. 2 root root 30 Mar 23 22:29 back -rw-r--r--. 1 root root 2523 Mar 23 22:26 CentOS-Base.repo drwxr-xr-x. 2 root root 187 Mar 23 22:26 default -rw-r--r-- 1 root root 951 Oct 2 2017 epel.repo -rw-r--r-- 1 root root 1050 Oct 2 2017 epel-testing.repo [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
3>.利用epel源安裝Redis服務centos
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# yum info redis Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile epel/x86_64/metalink | 5.8 kB 00:00:00 * base: mirrors.aliyun.com * epel: mirrors.yun-idc.com * extras: mirrors.aliyun.com * updates: mirrors.aliyun.com epel | 4.7 kB 00:00:00 (1/3): epel/x86_64/group_gz | 88 kB 00:00:00 epel/x86_64/updateinfo FAILED https://mirrors.tuna.tsinghua.edu.cn/epel/7/x86_64/repodata/27797f54681404f3261395d766df370206f7d92cd3e1551a698663a6317d5c5a-updateinfo.xml.bz2: [Errno 14] HTTPS Error 404 - Not Found Trying other mirror. To address this issue please refer to the below wiki article https://wiki.centos.org/yum-errors If above article doesn't help to resolve this issue please use https://bugs.centos.org/. (2/3): epel/x86_64/updateinfo | 1.0 MB 00:00:00 (3/3): epel/x86_64/primary_db | 6.6 MB 00:00:06 Available Packages Name : redis Arch : x86_64 Version : 3.2.12 Release : 2.el7 Size : 544 k Repo : epel/x86_64 Summary : A persistent key-value database URL : http://redis.io License : BSD Description : Redis is an advanced key-value store. It is often referred to as a data : structure server since keys can contain strings, hashes, lists, sets and : sorted sets. : : You can run atomic operations on these types, like appending to a string; : incrementing the value in a hash; pushing to a list; computing set : intersection, union and difference; or getting the member with highest : ranking in a sorted set. : : In order to achieve its outstanding performance, Redis works with an : in-memory dataset. Depending on your use case, you can persist it either : by dumping the dataset to disk every once in a while, or by appending : each command to a log. : : Redis also supports trivial-to-setup master-slave replication, with very : fast non-blocking first synchronization, auto-reconnection on net split : and so forth. : : Other features include Transactions, Pub/Sub, Lua scripting, Keys with a : limited time-to-live, and configuration settings to make Redis behave like : a cache. : : You can use Redis from most programming languages also. [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# yum -y install redis Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.aliyun.com * epel: mirrors.yun-idc.com * extras: mirrors.aliyun.com * updates: mirrors.aliyun.com Resolving Dependencies --> Running transaction check ---> Package redis.x86_64 0:3.2.12-2.el7 will be installed --> Processing Dependency: libjemalloc.so.1()(64bit) for package: redis-3.2.12-2.el7.x86_64 --> Running transaction check ---> Package jemalloc.x86_64 0:3.6.0-1.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ============================================================================================================================================== Package Arch Version Repository Size ============================================================================================================================================== Installing: redis x86_64 3.2.12-2.el7 epel 544 k Installing for dependencies: jemalloc x86_64 3.6.0-1.el7 epel 105 k Transaction Summary ============================================================================================================================================== Install 1 Package (+1 Dependent package) Total download size: 648 k Installed size: 1.7 M Downloading packages: warning: /var/cache/yum/x86_64/7/epel/packages/jemalloc-3.6.0-1.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY Public key for jemalloc-3.6.0-1.el7.x86_64.rpm is not installed (1/2): jemalloc-3.6.0-1.el7.x86_64.rpm | 105 kB 00:00:00 (2/2): redis-3.2.12-2.el7.x86_64.rpm | 544 kB 00:00:00 ---------------------------------------------------------------------------------------------------------------------------------------------- Total 3.4 MB/s | 648 kB 00:00:00 Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 Importing GPG key 0x352C64E5: Userid : "Fedora EPEL (7) <epel@fedoraproject.org>" Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5 Package : epel-release-7-11.noarch (@extras) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : jemalloc-3.6.0-1.el7.x86_64 1/2 Installing : redis-3.2.12-2.el7.x86_64 2/2 Verifying : redis-3.2.12-2.el7.x86_64 1/2 Verifying : jemalloc-3.6.0-1.el7.x86_64 2/2 Installed: redis.x86_64 0:3.2.12-2.el7 Dependency Installed: jemalloc.x86_64 0:3.6.0-1.el7 Complete! [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# rpm -ql redis /etc/logrotate.d/redis /etc/redis-sentinel.conf /etc/redis.conf /etc/systemd/system/redis-sentinel.service.d /etc/systemd/system/redis-sentinel.service.d/limit.conf /etc/systemd/system/redis.service.d /etc/systemd/system/redis.service.d/limit.conf /usr/bin/redis-benchmark /usr/bin/redis-check-aof /usr/bin/redis-check-rdb /usr/bin/redis-cli /usr/bin/redis-sentinel /usr/bin/redis-server /usr/lib/systemd/system/redis-sentinel.service /usr/lib/systemd/system/redis.service /usr/libexec/redis-shutdown /usr/share/doc/redis-3.2.12 /usr/share/doc/redis-3.2.12/00-RELEASENOTES /usr/share/doc/redis-3.2.12/BUGS /usr/share/doc/redis-3.2.12/CONTRIBUTING /usr/share/doc/redis-3.2.12/MANIFESTO /usr/share/doc/redis-3.2.12/README.md /usr/share/licenses/redis-3.2.12 /usr/share/licenses/redis-3.2.12/COPYING /usr/share/man/man1/redis-benchmark.1.gz /usr/share/man/man1/redis-check-aof.1.gz /usr/share/man/man1/redis-check-rdb.1.gz /usr/share/man/man1/redis-cli.1.gz /usr/share/man/man1/redis-sentinel.1.gz /usr/share/man/man1/redis-server.1.gz /usr/share/man/man5/redis-sentinel.conf.5.gz /usr/share/man/man5/redis.conf.5.gz /var/lib/redis /var/log/redis /var/run/redis [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
4>.啓動Redis數組
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# systemctl start redis [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# systemctl status redis ● redis.service - Redis persistent key-value database Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled) Drop-In: /etc/systemd/system/redis.service.d └─limit.conf Active: active (running) since Wed 2019-04-03 07:26:16 PDT; 4s ago Main PID: 9491 (redis-server) CGroup: /system.slice/redis.service └─9491 /usr/bin/redis-server 127.0.0.1:6379 Apr 03 07:26:16 node101.yinzhengjie.org.cn systemd[1]: Starting Redis persistent key-value database... Apr 03 07:26:16 node101.yinzhengjie.org.cn systemd[1]: Started Redis persistent key-value database. [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 127.0.0.1:6379 *:* LISTEN 0 128 *:22 *:* LISTEN 0 128 :::22 :::* [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# redis-cli 127.0.0.1:6379> 127.0.0.1:6379> 127.0.0.1:6379> HELP redis-cli 3.2.12 To get help about Redis commands type: "help @<group>" to get a list of commands in <group> "help <command>" for help on <command> "help <tab>" to get a list of possible help topics "quit" to exit To set redis-cli perferences: ":set hints" enable online hints ":set nohints" disable online hints Set your preferences in ~/.redisclirc 127.0.0.1:6379>
127.0.0.1:6379> HELP redis-cli 3.2.12 To get help about Redis commands type: "help @<group>" to get a list of commands in <group> "help <command>" for help on <command> "help <tab>" to get a list of possible help topics "quit" to exit To set redis-cli perferences: ":set hints" enable online hints ":set nohints" disable online hints Set your preferences in ~/.redisclirc 127.0.0.1:6379> 127.0.0.1:6379> HELP @list BLPOP key [key ...] timeout summary: Remove and get the first element in a list, or block until one is available since: 2.0.0 BRPOP key [key ...] timeout summary: Remove and get the last element in a list, or block until one is available since: 2.0.0 BRPOPLPUSH source destination timeout summary: Pop a value from a list, push it to another list and return it; or block until one is available since: 2.2.0 LINDEX key index summary: Get an element from a list by its index since: 1.0.0 LINSERT key BEFORE|AFTER pivot value summary: Insert an element before or after another element in a list since: 2.2.0 LLEN key summary: Get the length of a list since: 1.0.0 LPOP key summary: Remove and get the first element in a list since: 1.0.0 LPUSH key value [value ...] summary: Prepend one or multiple values to a list since: 1.0.0 LPUSHX key value summary: Prepend a value to a list, only if the list exists since: 2.2.0 LRANGE key start stop summary: Get a range of elements from a list since: 1.0.0 LREM key count value summary: Remove elements from a list since: 1.0.0 LSET key index value summary: Set the value of an element in a list by its index since: 1.0.0 LTRIM key start stop summary: Trim a list to the specified range since: 1.0.0 RPOP key summary: Remove and get the last element in a list since: 1.0.0 RPOPLPUSH source destination summary: Remove the last element in a list, prepend it to another list and return it since: 1.2.0 RPUSH key value [value ...] summary: Append one or multiple values to a list since: 1.0.0 RPUSHX key value summary: Append a value to a list, only if the list exists since: 2.2.0 127.0.0.1:6379> 127.0.0.1:6379>
二.Redis數據類型經常使用命令(注意:Redis全部的數據都是鍵值對的性質,只是其對應的值多是字符串,也多是列表,或者是集合等數據類型)
1>.Redis的通用命令介紹
127.0.0.1:6379> 127.0.0.1:6379> HELP @generic DEL key [key ...] summary: Delete a key since: 1.0.0 DUMP key summary: Return a serialized version of the value stored at the specified key. since: 2.6.0 EXISTS key [key ...] summary: Determine if a key exists since: 1.0.0 EXPIRE key seconds summary: Set a key's time to live in seconds since: 1.0.0 EXPIREAT key timestamp summary: Set the expiration for a key as a UNIX timestamp since: 1.2.0 KEYS pattern summary: Find all keys matching the given pattern since: 1.0.0 MIGRATE host port key| destination-db timeout [COPY] [REPLACE] [KEYS key] summary: Atomically transfer a key from a Redis instance to another one. since: 2.6.0 MOVE key db summary: Move a key to another database since: 1.0.0 OBJECT subcommand [arguments [arguments ...]] summary: Inspect the internals of Redis objects since: 2.2.3 PERSIST key summary: Remove the expiration from a key since: 2.2.0 PEXPIRE key milliseconds summary: Set a key's time to live in milliseconds since: 2.6.0 PEXPIREAT key milliseconds-timestamp summary: Set the expiration for a key as a UNIX timestamp specified in milliseconds since: 2.6.0 PTTL key summary: Get the time to live for a key in milliseconds since: 2.6.0 RANDOMKEY - summary: Return a random key from the keyspace since: 1.0.0 RENAME key newkey summary: Rename a key since: 1.0.0 RENAMENX key newkey summary: Rename a key, only if the new key does not exist since: 1.0.0 RESTORE key ttl serialized-value [REPLACE] summary: Create a key using the provided serialized value, previously obtained using DUMP. since: 2.6.0 SCAN cursor [MATCH pattern] [COUNT count] summary: Incrementally iterate the keys space since: 2.8.0 SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination] summary: Sort the elements in a list, set or sorted set since: 1.0.0 TTL key summary: Get the time to live for a key since: 1.0.0 TYPE key summary: Determine the type stored at key since: 1.0.0 WAIT numslaves timeout summary: Wait for the synchronous replication of all the write commands sent in the context of the current connection since: 3.0.0 PSYNC arg arg arg summary: Help not available since: not known HOST: arg ...options... summary: Help not available since: not known GEORADIUSBYMEMBER_RO key arg arg arg arg ...options... summary: Help not available since: not known REPLCONF arg ...options... summary: Help not available since: not known ASKING arg summary: Help not available since: not known RESTORE-ASKING key arg arg arg ...options... summary: Help not available since: not known LATENCY arg arg ...options... summary: Help not available since: not known GEORADIUS_RO key arg arg arg arg arg ...options... summary: Help not available since: not known TOUCH key arg ...options... summary: Help not available since: not known POST arg ...options... summary: Help not available since: not known SUBSTR key arg arg arg summary: Help not available since: not known PFDEBUG arg arg arg ...options... summary: Help not available since: not known PFSELFTEST arg summary: Help not available since: not known 127.0.0.1:6379> 127.0.0.1:6379>
2>.切換數據庫命令
127.0.0.1:6379> 127.0.0.1:6379> HELP select SELECT index summary: Change the selected database for the current connection since: 1.0.0 group: connection 127.0.0.1:6379>
3>.字符串命令介紹
127.0.0.1:6379> 127.0.0.1:6379> HELP @string APPEND key value summary: Append a value to a key since: 2.0.0 BITCOUNT key [start end] summary: Count set bits in a string since: 2.6.0 BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL] summary: Perform arbitrary bitfield integer operations on strings since: 3.2.0 BITOP operation destkey key [key ...] summary: Perform bitwise operations between strings since: 2.6.0 BITPOS key bit [start] [end] summary: Find first bit set or clear in a string since: 2.8.7 DECR key summary: Decrement the integer value of a key by one since: 1.0.0 DECRBY key decrement summary: Decrement the integer value of a key by the given number since: 1.0.0 GET key summary: Get the value of a key since: 1.0.0 GETBIT key offset summary: Returns the bit value at offset in the string value stored at key since: 2.2.0 GETRANGE key start end summary: Get a substring of the string stored at a key since: 2.4.0 GETSET key value summary: Set the string value of a key and return its old value since: 1.0.0 INCR key summary: Increment the integer value of a key by one since: 1.0.0 INCRBY key increment summary: Increment the integer value of a key by the given amount since: 1.0.0 INCRBYFLOAT key increment summary: Increment the float value of a key by the given amount since: 2.6.0 MGET key [key ...] summary: Get the values of all the given keys since: 1.0.0 MSET key value [key value ...] summary: Set multiple keys to multiple values since: 1.0.1 MSETNX key value [key value ...] summary: Set multiple keys to multiple values, only if none of the keys exist since: 1.0.1 PSETEX key milliseconds value summary: Set the value and expiration in milliseconds of a key since: 2.6.0 SET key value [EX seconds] [PX milliseconds] [NX|XX] summary: Set the string value of a key since: 1.0.0 SETBIT key offset value summary: Sets or clears the bit at offset in the string value stored at key since: 2.2.0 SETEX key seconds value summary: Set the value and expiration of a key since: 2.0.0 SETNX key value summary: Set the value of a key, only if the key does not exist since: 1.0.0 SETRANGE key offset value summary: Overwrite part of a string at key starting at the specified offset since: 2.2.0 STRLEN key summary: Get the length of the value stored in a key since: 2.2.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> SET name Jason #建立一個Key爲name,其值爲Jason OK 127.0.0.1:6379> 127.0.0.1:6379> KEYS * #獲取全部的keys 1) "name" 127.0.0.1:6379> 127.0.0.1:6379> GET name #獲取name對應的值 "Jason" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> SET name Yinzhengjie OK 127.0.0.1:6379> 127.0.0.1:6379> 127.0.0.1:6379> GET name "Yinzhengjie" 127.0.0.1:6379> 127.0.0.1:6379> SET name Jason EX 5 #設置一個變量指定過時時間爲5秒鐘 OK 127.0.0.1:6379> 127.0.0.1:6379> GET name #五秒內變量是有效的 "Jason" 127.0.0.1:6379> 127.0.0.1:6379> GET name #五秒後變量是無效的 (nil) 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> SETNX age 18 #SEINX表示一個KEY存在就不作任何操做,若不存在就建立改KEY對應的值 (integer) 1 127.0.0.1:6379> 127.0.0.1:6379> GET age "18" 127.0.0.1:6379> 127.0.0.1:6379> SETNX age 120 (integer) 0 127.0.0.1:6379> 127.0.0.1:6379> GET age "18" 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> SET count 100 OK 127.0.0.1:6379> 127.0.0.1:6379> INCR count #對數值操做的自增命令 (integer) 101 127.0.0.1:6379> 127.0.0.1:6379> INCR count (integer) 102 127.0.0.1:6379> 127.0.0.1:6379> INCR count (integer) 103 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> INCR count (integer) 109 127.0.0.1:6379> 127.0.0.1:6379> DECR count #對數值操做的自減命令 (integer) 108 127.0.0.1:6379> 127.0.0.1:6379> DECR count (integer) 107 127.0.0.1:6379> 127.0.0.1:6379> DECR count (integer) 106 127.0.0.1:6379> 127.0.0.1:6379> DECR count (integer) 105 127.0.0.1:6379> 127.0.0.1:6379> DECR count (integer) 104 127.0.0.1:6379> 127.0.0.1:6379> DECR count (integer) 103 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> MSET name Jason age 18 OK 127.0.0.1:6379> 127.0.0.1:6379> 127.0.0.1:6379> get name "Jason" 127.0.0.1:6379> 127.0.0.1:6379> get age "18" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> MSET name Jason age 18 OK 127.0.0.1:6379> 127.0.0.1:6379> MGET name age 1) "Jason" 2) "18" 127.0.0.1:6379> 127.0.0.1:6379>
4>.列表相關命令介紹
127.0.0.1:6379> HELP @list BLPOP key [key ...] timeout summary: Remove and get the first element in a list, or block until one is available since: 2.0.0 BRPOP key [key ...] timeout summary: Remove and get the last element in a list, or block until one is available since: 2.0.0 BRPOPLPUSH source destination timeout summary: Pop a value from a list, push it to another list and return it; or block until one is available since: 2.2.0 LINDEX key index summary: Get an element from a list by its index since: 1.0.0 LINSERT key BEFORE|AFTER pivot value summary: Insert an element before or after another element in a list since: 2.2.0 LLEN key summary: Get the length of a list since: 1.0.0 LPOP key summary: Remove and get the first element in a list since: 1.0.0 LPUSH key value [value ...] summary: Prepend one or multiple values to a list since: 1.0.0 LPUSHX key value summary: Prepend a value to a list, only if the list exists since: 2.2.0 LRANGE key start stop summary: Get a range of elements from a list since: 1.0.0 LREM key count value summary: Remove elements from a list since: 1.0.0 LSET key index value summary: Set the value of an element in a list by its index since: 1.0.0 LTRIM key start stop summary: Trim a list to the specified range since: 1.0.0 RPOP key summary: Remove and get the last element in a list since: 1.0.0 RPOPLPUSH source destination summary: Remove the last element in a list, prepend it to another list and return it since: 1.2.0 RPUSH key value [value ...] summary: Append one or multiple values to a list since: 1.0.0 RPUSHX key value summary: Append a value to a list, only if the list exists since: 2.2.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun #定義一個列表 (integer) 7 127.0.0.1:6379> 127.0.0.1:6379> LINDEX weekdays 0 #獲取第0個元素 "Sun" 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun (integer) 7 127.0.0.1:6379> 127.0.0.1:6379> LINDEX weekdays 0 "Sun" 127.0.0.1:6379> 127.0.0.1:6379> 127.0.0.1:6379> LPOP weekdays #彈棧操做,先進後出,因而咱們把最右側的數據給刪除啦! "Sun" 127.0.0.1:6379> 127.0.0.1:6379> LINDEX weekdays 0 "Mon" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> LLEN weekdays #獲取當前列表的長度 (integer) 6 127.0.0.1:6379> 127.0.0.1:6379> RPUSHX weekdays Sun #在列表的最右側添加一個值 (integer) 7 127.0.0.1:6379> 127.0.0.1:6379> LLEN weekdays (integer) 7 127.0.0.1:6379> 127.0.0.1:6379> LINDEX weekdays 6 "Sun" 127.0.0.1:6379>
5>.關聯數組命令介紹
127.0.0.1:6379> HELP @hash HDEL key field [field ...] summary: Delete one or more hash fields since: 2.0.0 HEXISTS key field summary: Determine if a hash field exists since: 2.0.0 HGET key field summary: Get the value of a hash field since: 2.0.0 HGETALL key summary: Get all the fields and values in a hash since: 2.0.0 HINCRBY key field increment summary: Increment the integer value of a hash field by the given number since: 2.0.0 HINCRBYFLOAT key field increment summary: Increment the float value of a hash field by the given amount since: 2.6.0 HKEYS key summary: Get all the fields in a hash since: 2.0.0 HLEN key summary: Get the number of fields in a hash since: 2.0.0 HMGET key field [field ...] summary: Get the values of all the given hash fields since: 2.0.0 HMSET key field value [field value ...] summary: Set multiple hash fields to multiple values since: 2.0.0 HSCAN key cursor [MATCH pattern] [COUNT count] summary: Incrementally iterate hash fields and associated values since: 2.8.0 HSET key field value summary: Set the string value of a hash field since: 2.0.0 HSETNX key field value summary: Set the value of a hash field, only if the field does not exist since: 2.0.0 HSTRLEN key field summary: Get the length of the value of a hash field since: 3.2.0 HVALS key summary: Get all the values in a hash since: 2.0.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> HMSET stu1 id 1 name tom age 18 course "linux" #給關聯數組設置多個值 OK 127.0.0.1:6379> 127.0.0.1:6379> HGET stu1 course #獲取stu1的 course信息,下面的獲取方式都是在獲取stu1的相關信息! "linux" 127.0.0.1:6379> 127.0.0.1:6379> HGET stu1 name "tom" 127.0.0.1:6379> 127.0.0.1:6379> HGET stu1 age "18" 127.0.0.1:6379> 127.0.0.1:6379> 127.0.0.1:6379> HGET stu1 id "1" 127.0.0.1:6379>
127.0.0.1:6379> HVALS stu1 #查看stu1的相關信息 1) "1" 2) "tom" 3) "18" 4) "linux" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> HGETALL stu1 1) "id" 2) "1" 3) "name" 4) "tom" 5) "age" 6) "18" 7) "course" 8) "linux" 127.0.0.1:6379> 127.0.0.1:6379>
6>.集合命令介紹
127.0.0.1:6379> 127.0.0.1:6379> HELP @set SADD key member [member ...] summary: Add one or more members to a set since: 1.0.0 SCARD key summary: Get the number of members in a set since: 1.0.0 SDIFF key [key ...] summary: Subtract multiple sets since: 1.0.0 SDIFFSTORE destination key [key ...] summary: Subtract multiple sets and store the resulting set in a key since: 1.0.0 SINTER key [key ...] summary: Intersect multiple sets since: 1.0.0 SINTERSTORE destination key [key ...] summary: Intersect multiple sets and store the resulting set in a key since: 1.0.0 SISMEMBER key member summary: Determine if a given value is a member of a set since: 1.0.0 SMEMBERS key summary: Get all the members in a set since: 1.0.0 SMOVE source destination member summary: Move a member from one set to another since: 1.0.0 SPOP key [count] summary: Remove and return one or multiple random members from a set since: 1.0.0 SRANDMEMBER key [count] summary: Get one or multiple random members from a set since: 1.0.0 SREM key member [member ...] summary: Remove one or more members from a set since: 1.0.0 SSCAN key cursor [MATCH pattern] [COUNT count] summary: Incrementally iterate Set elements since: 2.8.0 SUNION key [key ...] summary: Add multiple sets since: 1.0.0 SUNIONSTORE destination key [key ...] summary: Add multiple sets and store the resulting set in a key since: 1.0.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> SADD colors1 red green gray puple (integer) 4 127.0.0.1:6379> 127.0.0.1:6379> SADD colors2 gree yellow bule pink gray (integer) 5 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> SADD colors1 red green gray puple (integer) 4 127.0.0.1:6379> 127.0.0.1:6379> SADD colors2 gree yellow bule pink gray (integer) 5 127.0.0.1:6379> 127.0.0.1:6379> SINTER colors1 colors2 1) "gray" 127.0.0.1:6379>
127.0.0.1:6379> SADD colors1 red green gray puple (integer) 4 127.0.0.1:6379> 127.0.0.1:6379> SADD colors2 gree yellow bule pink gray (integer) 5 127.0.0.1:6379> 127.0.0.1:6379> SUNION colors1 colors2 1) "puple" 2) "gray" 3) "green" 4) "pink" 5) "gree" 6) "bule" 7) "yellow" 8) "red" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> SADD colors1 red green gray puple (integer) 4 127.0.0.1:6379> 127.0.0.1:6379> SADD colors2 gree yellow bule pink gray (integer) 5 127.0.0.1:6379> 127.0.0.1:6379> SDIFF colors1 colors2 1) "red" 2) "green" 3) "puple" 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> SADD colors1 red green gray puple (integer) 4 127.0.0.1:6379> 127.0.0.1:6379> SISMEMBER colors1 red #成員關係斷定,判斷是clors1中是否包含紅色,若是返回值爲1表示包含,若是返回值爲0表示不包含! (integer) 1 127.0.0.1:6379> SISMEMBER colors1 blue (integer) 0 127.0.0.1:6379>
7>.有序集合命令介紹
127.0.0.1:6379> HELP @sorted_set ZADD key [NX|XX] [CH] [INCR] score member [score member ...] summary: Add one or more members to a sorted set, or update its score if it already exists since: 1.2.0 ZCARD key summary: Get the number of members in a sorted set since: 1.2.0 ZCOUNT key min max summary: Count the members in a sorted set with scores within the given values since: 2.0.0 ZINCRBY key increment member summary: Increment the score of a member in a sorted set since: 1.2.0 ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX] summary: Intersect multiple sorted sets and store the resulting sorted set in a new key since: 2.0.0 ZLEXCOUNT key min max summary: Count the number of members in a sorted set between a given lexicographical range since: 2.8.9 ZRANGE key start stop [WITHSCORES] summary: Return a range of members in a sorted set, by index since: 1.2.0 ZRANGEBYLEX key min max [LIMIT offset count] summary: Return a range of members in a sorted set, by lexicographical range since: 2.8.9 ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] summary: Return a range of members in a sorted set, by score since: 1.0.5 ZRANK key member summary: Determine the index of a member in a sorted set since: 2.0.0 ZREM key member [member ...] summary: Remove one or more members from a sorted set since: 1.2.0 ZREMRANGEBYLEX key min max summary: Remove all members in a sorted set between the given lexicographical range since: 2.8.9 ZREMRANGEBYRANK key start stop summary: Remove all members in a sorted set within the given indexes since: 2.0.0 ZREMRANGEBYSCORE key min max summary: Remove all members in a sorted set within the given scores since: 1.2.0 ZREVRANGE key start stop [WITHSCORES] summary: Return a range of members in a sorted set, by index, with scores ordered from high to low since: 1.2.0 ZREVRANGEBYLEX key max min [LIMIT offset count] summary: Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings. since: 2.8.9 ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] summary: Return a range of members in a sorted set, by score, with scores ordered from high to low since: 2.2.0 ZREVRANK key member summary: Determine the index of a member in a sorted set, with scores ordered from high to low since: 2.0.0 ZSCAN key cursor [MATCH pattern] [COUNT count] summary: Incrementally iterate sorted sets elements and associated scores since: 2.8.0 ZSCORE key member summary: Get the score associated with the given member in a sorted set since: 1.2.0 ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX] summary: Add multiple sorted sets and store the resulting sorted set in a new key since: 2.0.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> ZADD liangshan 108 Songjiang 107 Wuyong 106 Chaogai (integer) 3 127.0.0.1:6379>
127.0.0.1:6379> ZSCORE liangshan Wuyong "107" 127.0.0.1:6379>
127.0.0.1:6379> ZCOUNT liangshan 106 120 (integer) 3 127.0.0.1:6379>
127.0.0.1:6379> ZRANK liangshan Wuyong (integer) 1 127.0.0.1:6379> 127.0.0.1:6379> ZRANK liangshan Songjiang (integer) 2 127.0.0.1:6379> 127.0.0.1:6379> ZRANK liangshan Chaogai (integer) 0 127.0.0.1:6379> 127.0.0.1:6379>
8>.發佈(Publish)訂閱(Subscribe)相關命令
127.0.0.1:6379> HELP @pubsub PSUBSCRIBE pattern [pattern ...] summary: Listen for messages published to channels matching the given patterns since: 2.0.0 PUBLISH channel message summary: Post a message to a channel since: 2.0.0 PUBSUB subcommand [argument [argument ...]] summary: Inspect the state of the Pub/Sub subsystem since: 2.8.0 PUNSUBSCRIBE [pattern [pattern ...]] summary: Stop listening for messages posted to channels matching the given patterns since: 2.0.0 SUBSCRIBE channel [channel ...] summary: Listen for messages published to the given channels since: 2.0.0 UNSUBSCRIBE [channel [channel ...]] summary: Stop listening for messages posted to the given channels since: 2.0.0 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> 127.0.0.1:6379> PUBLISH yinzhengjie-redis "redis not is kafka" (integer) 2 127.0.0.1:6379> 127.0.0.1:6379>
127.0.0.1:6379> SUBSCRIBE yinzhengjie-redis Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "yinzhengjie-redis" 3) (integer) 1 1) "message" 2) "yinzhengjie-redis" 3) "redis not is kafka"
9>.與連接相關的命令
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn -a yinzhengjie node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> HELP @connection AUTH password summary: Authenticate to the server since: 1.0.0 ECHO message summary: Echo the given string since: 1.0.0 PING [message] summary: Ping the server since: 1.0.0 QUIT - summary: Close the connection since: 1.0.0 SELECT index summary: Change the selected database for the current connection since: 1.0.0 node101.yinzhengjie.org.cn:6379>
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> KEYS * (error) NOAUTH Authentication required. node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> AUTH yinzhengjie #使用AUTH關鍵字進行認證,後面跟的字符串表示認證的密碼,這個字符串必須和Redis服務器中配置文件的requirepass關鍵字設置一致!方可認證成功! OK node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> KEYS * 1) "stu1" 2) "name" 3) "weekdays" 4) "liangshan" 5) "color" 6) "count" 7) "colors2" 8) "colors1" 9) "age" node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> quit [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn -a yinzhengjie node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> KEYS * 1) "stu1" 2) "name" 3) "weekdays" 4) "liangshan" 5) "color" 6) "count" 7) "colors2" 8) "colors1" 9) "age" node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> exit [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
node101.yinzhengjie.org.cn:6379> PING #若是節點存錯,就會相應PONG字符串 PONG node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379>
node101.yinzhengjie.org.cn:6379> ECHO "My name is Jason Yin" "My name is Jason Yin" node101.yinzhengjie.org.cn:6379>
三.Redis服務經常使用配置介紹
1>.開啓遠程鏈接並重啓Redis服務
[root@node101.yinzhengjie.org.cn ~]# cp /etc/redis.conf /etc/redis.conf-`date +%F` [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# grep yinzhengjie /etc/redis.conf bind node101.yinzhengjie.org.cn [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# systemctl restart redis [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 172.30.1.101:6379 *:* LISTEN 0 128 *:22 *:* LISTEN 0 128 :::22 :::* [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
2>.redis-cli腳本的使用
[root@node101.yinzhengjie.org.cn ~]# redis-cli --help redis-cli 3.2.12 Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]] -h <hostname> Server hostname (default: 127.0.0.1). -p <port> Server port (default: 6379). -s <socket> Server socket (overrides hostname and port). -a <password> Password to use when connecting to the server. -r <repeat> Execute specified command N times. -i <interval> When -r is used, waits <interval> seconds per command. It is possible to specify sub-second times like -i 0.1. -n <db> Database number. -x Read last argument from STDIN. -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \n). -c Enable cluster mode (follow -ASK and -MOVED redirections). --raw Use raw formatting for replies (default when STDOUT is not a tty). --no-raw Force formatted output even when STDOUT is not a tty. --csv Output in CSV format. --stat Print rolling stats about server: mem, clients, ... --latency Enter a special mode continuously sampling latency. --latency-history Like --latency but tracking latency changes over time. Default time interval is 15 sec. Change it using -i. --latency-dist Shows latency as a spectrum, requires xterm 256 colors. Default time interval is 1 sec. Change it using -i. --lru-test <keys> Simulate a cache workload with an 80-20 distribution. --slave Simulate a slave showing commands received from the master. --rdb <filename> Transfer an RDB dump from remote server to local file. --pipe Transfer raw Redis protocol from stdin to server. --pipe-timeout <n> In --pipe mode, abort with error if after sending all data. no reply is received within <n> seconds. Default timeout: 30. Use 0 to wait forever. --bigkeys Sample Redis keys looking for big keys. --scan List all keys using the SCAN command. --pattern <pat> Useful with --scan to specify a SCAN pattern. --intrinsic-latency <sec> Run a test to measure intrinsic system latency. The test will run for the specified amount of seconds. --eval <file> Send an EVAL command using the Lua script at <file>. --ldb Used with --eval enable the Redis Lua debugger. --ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, in this mode the server is blocked and script changes are are not rolled back from the server memory. --help Output this help and exit. --version Output version and exit. Examples: cat /etc/passwd | redis-cli -x set mypasswd redis-cli get mypasswd redis-cli -r 100 lpush mylist x redis-cli -r 100 -i 1 info | grep used_memory_human: redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3 redis-cli --scan --pattern '*:12345*' (Note: when using --eval the comma separates KEYS[] from ARGV[] items) When no command is given, redis-cli starts in interactive mode. Type "help" in interactive mode for information on available commands and settings. [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn -p 6379 node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379> exit [root@node101.yinzhengjie.org.cn ~]#
3>.配置和使用Redis
[root@node101.yinzhengjie.org.cn ~]# grep "^##" /etc/redis.conf ################################## INCLUDES ################################### ------> 基本配置,用來模塊化配置文件,和nginx很類似經過include關鍵字加載配置文件 ################################## NETWORK ##################################### -----> 網絡配置項 ################################# GENERAL ##################################### -----> 通常行選項 ################################ SNAPSHOTTING ################################ -----> 快照持久化相關配置項 ################################# REPLICATION ################################# -----> 複製相關配置項 ################################## SECURITY ################################### -----> 安全相關配置項 ################################### LIMITS #################################### -----> Limit相關的配置 ############################## APPEND ONLY MODE ############################### -----> 簡稱AOM持久化 ################################ LUA SCRIPTING ############################### -----> LUA腳本先關 ################################ REDIS CLUSTER ############################### ----> Redis集羣相關 ################################## SLOW LOG ################################### -----> 慢日誌SlowLog相關的配置 ################################ LATENCY MONITOR ############################## -----> 延遲監控 ############################# EVENT NOTIFICATION ############################## -----> 事件通知 ############################### ADVANCED CONFIG ############################### -----> 高級配置 [root@node101.yinzhengjie.org.cn ~]#
4>.INClUDES配置端文件說明
用來把整個配置文件模塊化的,你們知道把配置文件模塊化也是一個趨勢。把一個大配置文件切割成不少段,咱們找一箇中心配置文件,而後使用include的方式把其餘以「*.conf」的文件統統包含進來。好比nginx和http都是這樣乾的!這樣的方式的好處就是未來咱們可使用腳本或者運維工具來生成或者刪除配置文件達到去配置應用程序的目的
所以咱們能夠說INCLUDES是便於咱們達到標準化,工具化一種有效的支撐機制。
5>.NETWORK 配置端文件說明
bind參數:
顧名思義,用來指定綁定的地址,相似於Kafka服務中的LISTEN,即指定監聽的地址,咱們一般使用"0.0.0.0"來通配當前主機的全部地址
protected-mode參數:
默認是啓用保護模式的(即默認值爲yes),啓動保護默認須要兩個必要條件:
第一:沒有使用 bind 參數
第二:沒有使用 pasword 配置
port參數:
設置監聽的端口,Redis默認監聽的端口爲6379。
tcp-backlog參數:
和Tomcat相似,它是設置後援隊列長度的,即當併發量達到上限時,咱們打算在後端啓用承載多長的隊列。
unixsocket參數:
若是Redis只是本地鏈接,建議使用更高性能的鏈接方式。也就是說本地鏈接時建議啓用該參數,由於它會更高效,咱們知道MySQL也支持類型的功能。
unixsocketperm參數:
設置本地鏈接文件的權限。
timeout參數:
表示咱們關閉鏈接時,客戶端運行空閒多長時間。若是設置爲0表示禁用該功能,默認就是禁用狀態!也就是說只要客戶端鏈接進來,無論他是否作增刪改查,服務端都不會主動去端口鏈接的。若是高併發鏈接的生產環境,建議開啓該功能,好比能夠設置爲5分鐘(300s)!
tcp-keepalive參數:
和timeout的功能相似,只不過該參數控制的是tcp的鏈接超時時間,默認時間爲300s。
6>.GENERAL 配置端文件說明
daemonize參數: 表示是否設置爲守護進程,默認值爲no。因爲CenOS5,CentOS6以及CentOS7管理服務的方式是不一樣的。在CentOS7操做系統時,全部的服務都交給systemd服務去管理的,全部的服務都得在systemd總線中註冊。在CentOS6能夠設置爲yes,可是在CentOS7的話建議使用默認值,即設置爲no。 supervised參數: 能夠經過upstart和systemd管理Redis守護進程,選項以下: supervised no - 沒有監督互動 supervised upstart - 經過將Redis置於SIGSTOP模式來啓動信號 supervised systemd - signal systemd將READY = 1寫入$ NOTIFY_SOCKET supervised auto - 檢測upstart或systemd方法基於 UPSTART_JOB或NOTIFY_SOCKET環境變量 pidfile參數: 配置PID文件路徑,當redis做爲守護進程運行的時候,它會把 pid 默認寫到 /var/redis/run/redis_6379.pid 文件裏面。 loglevel參數: 定義日誌級別。能夠是下面的這些值: debug(記錄大量日誌信息,適用於開發、測試階段) verbose(較多日誌信息) notice(適量日誌信息,使用於生產環境) warning(僅有部分重要、關鍵信息纔會被記錄)
logfile 參數:
日誌文件的位置,當指定爲空字符串時,爲標準輸出,若是redis已守護進程模式運行,那麼日誌將會輸出到/dev/null
syslog-enabled參數:
默認值爲yes,要想把日誌記錄到系統日誌,就把它改爲 yes,也能夠可選擇性的更新其餘的syslog 參數以達到你的要求。
syslog-ident參數:
設置系統日誌的ID
syslog-facility參數:
指定系統日誌設置,必須是 USER 或者是 LOCAL[0-7] 之間的值
databases 參數:
設置數據庫的數目。默認的數據庫是DB 0 ,能夠在每一個鏈接上使用select <dbid> 命令選擇一個不一樣的數據庫。咱們知道Redis默認的數據庫只有16個,若是你想不想限制Redis的數據庫數量的話,能夠將其的值設置爲-1。
7>.SECURITY 配置端文件說明
requirepass 參數:
表示客戶端鏈接時必須輸入密碼才能鏈接,Redis默認是禁用該功能的。咱們能夠指定鏈接時的密碼,好比咱們設置鏈接密碼爲 yinzhengjie,那麼咱們配置時就能夠設置爲:「requirepass yinzhengjie」
rename-command參數:
表示命令重命名,Redis有幾個很是危險的命令,執行後能夠瞬間把Redis中的數據刪除掉,所以咱們能夠設置成一個複雜的字符串,當執行一些危險的命令時須要使用咱們自定義的字符串去操做!從而達到運維人員手抖誤操做作的尷尬場景,但改參數咱們在生產環境中也不多使用!
8>.LIMITS 配置端文件說明
maxclients參數: 設置客戶端最大併發鏈接數,默認是1萬,這個默認值是比較合理的,咱們基本上能夠不用去修改,畢竟Redis通常狀況下並非面向互聯網客戶端的,而是面臨應用系統內的各類應用程序服務器的。 maxmemeory參數: 指定Redis最大內存限制,Redis在啓動時會把數據加載到內存中,達到最大內存後,Redis會先嚐試清除已到期或即將到期的Key。生產環境中建議設置爲物理機的一半內存。由於設置過大有可能會出現OOM(Out Of Memory)。
注意,內存泄露是致使OOM發生的可能性因素之一,當發生OOM時,內核爲了自救(由於內核的運行也是須要內存空間的),內核將自動殺死最「吃」內存資源的進程,從而保證操做系統運行正常。它內部有一個oom_score用來記錄每一個進程佔用內存的分數,咱們能夠經過oom_adj來調整內核去殺死進程的機制!
maxmemory-policy參數: 當內存使用達到最大值時,redis使用的清楚策略。有如下幾種能夠選擇: 1>.volatile-lru 利用LRU算法移除設置過過時時間的key (LRU:最近使用 Least Recently Used ) 2>.allkeys-lru 利用LRU算法移除任何key 3>.volatile-random 移除設置過過時時間的隨機key 4>.allkeys-random 移除隨機ke 5>.volatile-ttl 移除即將過時的key(minor TTL) 6>.noeviction noeviction 不移除任何key,只是返回一個寫錯誤 ,默認選項 maxmemory-samples參數: LRU 和 minimal TTL 算法都不是精準的算法,可是相對精確的算法(爲了節省內存)。隨意你能夠選擇樣本大小進行檢,redis默認選擇5個樣本進行檢測,你能夠經過maxmemory-samples進行設置樣本數
9>.SLOW LOG 配置端文件說明
slowlog-log-slower-than參數: slog log是用來記錄redis運行中執行比較慢的命令耗時。當命令的執行超過了指定時間,就記錄在slow log中,slog log保存在內存中,因此沒有IO操做。執行時間比slowlog-log-slower-than大的請求記錄到slowlog裏面,單位是微秒,默認是10毫秒。 注意,負數時間會禁用慢查詢日誌,而0則會強制記錄全部命令。 slowlog-max-len參數: 慢查詢日誌長度。當一個新的命令被寫進日誌的時候,最老的那個記錄會被刪掉,這個長度沒有限制。只要有足夠的內存就行,你能夠經過 SLOWLOG RESET 來釋放內存。
10>.ADVANCED CONFIG 配置端文件說明
hash-max-ziplist-entries參數: hash類型的數據結構在編碼上可使用ziplist和hashtable。ziplist的特色就是文件存儲(以及內存存儲)所需的空間較小,在內容較小時,性能和hashtable幾乎同樣。所以redis對hash類型默認採起ziplist。若是hash中條目的條目個數或者value長度達到閥值,將會被重構爲hashtable。這個參數指的是ziplist中容許存儲的最大條目個數,,默認爲512,建議爲128 hash-max-ziplist-value參數: ziplist中容許條目value值最大字節數,默認爲64,建議爲1024。 list-max-ziplist-size參數: 當取正值的時候,表示按照數據項個數來限定每一個quicklist節點上的ziplist長度。好比,當這個參數配置成5的時候,表示每一個quicklist節點的ziplist最多包含5個數據項。當取負值的時候,表示按照佔用字節數來限定每一個quicklist節點上的ziplist長度。這時,它只能取-1到-5這五個值,每一個值含義以下: -5: 每一個quicklist節點上的ziplist大小不能超過64 Kb。(注:1kb => 1024 bytes) -4: 每一個quicklist節點上的ziplist大小不能超過32 Kb。 -3: 每一個quicklist節點上的ziplist大小不能超過16 Kb。 -2: 每一個quicklist節點上的ziplist大小不能超過8 Kb。(-2是Redis給出的默認值) -1: 每一個quicklist節點上的ziplist大小不能超過4 Kb。 list-compress-depth參數: 這個參數表示一個quicklist兩端不被壓縮的節點個數。注:這裏的節點個數是指quicklist雙向鏈表的節點個數,而不是指ziplist裏面的數據項個數。實際上,一個quicklist節點上的ziplist,若是被壓縮,就是總體被壓縮的。參數list-compress-depth的取值含義以下: 0: 是個特殊值,表示都不壓縮。這是Redis的默認值。 1: 表示quicklist兩端各有1個節點不壓縮,中間的節點壓縮。 2: 表示quicklist兩端各有2個節點不壓縮,中間的節點壓縮。 3: 表示quicklist兩端各有3個節點不壓縮,中間的節點壓縮。 依此類推… 因爲0是個特殊值,很容易看出quicklist的頭節點和尾節點老是不被壓縮的,以便於在表的兩端進行快速存取。 set-max-intset-entries參數: 數據量小於等於set-max-intset-entries用intset,大於set-max-intset-entries用set。 zset-max-ziplist-entries和zset-max-ziplist-value參數: 數據量小於等於zset-max-ziplist-entries用ziplist,大於zset-max-ziplist-entries用zset hll-sparse-max-bytes參數: value大小小於等於hll-sparse-max-bytes使用稀疏數據結構(sparse)大於hll-sparse-max-bytes使用稠密的數據結構(dense),一個比16000大的value是幾乎沒用的,建議的value大概爲3000。若是對CPU要求不高,對空間要求較高的,建議設置到10000左右 activerehashing參數: Redis將在每100毫秒時使用1毫秒的CPU時間來對redis的hash表進行從新hash,能夠下降內存的使用。當你的使用場景中,有很是嚴格的實時性須要,不可以接受Redis時不時的對請求有2毫秒的延遲的話,把這項配置爲no。若是沒有這麼嚴格的實時性要求,能夠設置爲yes,以便可以儘量快的釋放內存 client-output-buffer-limit normal 0 0 0參數: (通常指正常客戶端)對客戶端輸出緩衝進行限制能夠強迫那些不從服務器讀取數據的客戶端斷開鏈接,用來強制關閉傳輸緩慢的客戶端。對於normal client,第一個0表示取消hard limit,第二個0和第三個0表示取消soft limit,normal client默認取消限制,由於若是沒有尋問,他們是不會接收數據的。 client-output-buffer-limit slave 256mb 64mb 60參數: (通常指主從複製的客戶端)對於slave client和MONITER client,若是client-output-buffer一旦超過256mb,又或者超過64mb持續60秒,那麼服務器就會當即斷開客戶端鏈接。 client-output-buffer-limit pubsub 32mb 8mb 60參數: (訂閱發佈模式)對於pubsub client,若是client-output-buffer一旦超過32mb,又或者超過8mb持續60秒,那麼服務器就會當即斷開客戶端鏈接。 hz參數: redis執行任務的頻率爲1s除以hz。
aof-rewrite-incremental-fsync參數: 在aof重寫的時候,若是打開了aof-rewrite-incremental-fsync開關,系統會每32MB執行一次fsync。這對於把文件寫入磁盤是有幫助的,能夠避免過大的延遲峯值
參考連接:https://www.cnblogs.com/pqchao/p/6558688.html。
四.Redis持久化
咱們以前說過,Redis不只能夠當緩存(Cache)使用,還能夠當數據庫(Database)使用,而任何數據庫系統就必須能持久存儲數據的,這樣就意味着數據庫崩潰了,在重啓起來,數據依然是有效的(除非硬盤壞了,不然咱們要確保數據盤是依然可用的)。Redis是支持兩種持久化的,兩種持久化機制各有優勢,通常而言,咱們只須要啓用一種便可,不建議同時使用!(若是你非要啓用兩種方式的話,建議存儲在不一樣的文件系統中,恢復數據時首推AOF)
RDB:(延遲較大,且存在丟失數據的風險)
snapshotting,二進制格式;按事先定製的策略,週期性地將數據從內存同步至磁盤;數據文件默認爲dump.rdb;客戶端顯示使用SAVE或BGSAVE命令來手動啓動快照保護機制。
SAVE:同步,即正在主線程中保護快照,此時會阻塞全部客戶端請求(這種方式不推薦使用,由於會影響到客戶端寫入操做);
BGSAVE:異步,background(這種方式相對來時比較推薦使用)。
AOF:(IO量較大,啓動時較慢,數據完整性更強!)
Append Only File,fsync,記錄每次寫操做至指定的文件尾部實現的持久化;當Redis重啓時,可經過從新執行文件中的命令在內存中重建出數據庫;
BGREWRITEAOF,AOF文件重寫:不會讀取正在使用的AOF文件,而是經過將內存中的數據以命令的方式保存至臨時文件中,完成以後替換原來的AOF文件。
save 900 1 save 300 10 save 60 10000 存 DB 到磁盤: 格式:save <間隔時間(秒)> <寫入次數> 根據給定的時間間隔和寫入次數將數據保存到磁盤 下面的例子的意思是: 900 秒內若是至少有 1 個 key 的值變化,則保存 300 秒內若是至少有 10 個 key 的值變化,則保存 60 秒內若是至少有 10000 個 key 的值變化,則保存 注意:你能夠註釋掉全部的 save 行來停用保存功能。 也能夠直接一個空字符串來實現停用: save "" stop-writes-on-bgsave-error yes 若是用戶開啓了RDB快照功能,那麼在redis持久化數據到磁盤時若是出現失敗,默認狀況下,redis會中止接受全部的寫請求。 這樣作的好處在於可讓用戶很明確的知道內存中的數據和磁盤上的數據已經存在不一致了。 若是redis不顧這種不一致,獨斷獨行的繼續接收寫請求,就可能會引發一些災難性的後果。 若是下一次RDB持久化成功,redis會自動恢復接受寫請求。 若是不在意這種數據不一致或者有其餘的手段發現和控制這種不一致的話,能夠關閉這個功能, 以便在快照寫入失敗時,也能確保redis繼續接受新的寫請求。 rdbcompression yes 對於存儲到磁盤中的快照,能夠設置是否進行壓縮存儲。 若是是的話,redis會採用LZF算法進行壓縮。若是你不想消耗CPU來進行壓縮的話, 能夠設置爲關閉此功能,可是存儲在磁盤上的快照會比較大。 rdbchecksum yes 在存儲快照後,咱們還可讓redis使用CRC64算法來進行數據校驗,可是這樣作會增長大約10%的性能消耗, 若是但願獲取到最大的性能提高,能夠關閉此功能。 dbfilename dump.rdb 設置快照的文件名 dir /home/yinzhengjie/softwares/redis/data 設置快照文件的存放路徑,這個配置項必定是個目錄,而不能是文件名。建議生成環境系統盤和數據盤要分開,當操做系統出現故障時,不會影響到數據的存儲!
appendonly no 默認redis使用的是rdb方式持久化,這種方式在許多應用中已經足夠用了。可是redis若是中途宕機, 會致使可能有幾分鐘的數據丟失,根據save來策略進行持久化,Append Only File是另外一種持久化方式, 能夠提供更好的持久化特性。Redis會把每次寫入的數據在接收後都寫入appendonly.aof文件, 每次啓動時Redis都會先把這個文件的數據讀入內存裏,先忽略RDB文件。 appendfilename "appendonly.aof" aof文件名 appendfsync always appendfsync everysec appendfsync no aof持久化策略的配置 no表示不執行fsync,由操做系統保證數據同步到磁盤,速度最快。 always表示每次寫入都執行fsync,以保證數據同步到磁盤。 everysec表示每秒執行一次fsync,可能會致使丟失這1s數據 no-appendfsync-on-rewrite no 在aof重寫或者寫入rdb文件的時候,會執行大量IO,此時對於everysec和always的aof模式來講, 執行fsync會形成阻塞過長時間,no-appendfsync-on-rewrite字段設置爲默認設置爲no。 若是對延遲要求很高的應用,這個字段能夠設置爲yes,不然仍是設置爲no,這樣對持久化特性來講這是更安全的選擇。 設置爲yes表示rewrite期間對新寫操做不fsync,暫時存在內存中,等rewrite完成後再寫入,默認爲no,建議yes。 Linux的默認fsync策略是30秒。可能丟失30秒數據。 auto-aof-rewrite-percentage 100 aof自動重寫配置,當目前aof文件大小超過上一次重寫的aof文件大小的百分之多少進行重寫, 即當aof文件增加到必定大小的時候,Redis可以調用bgrewriteaof對日誌文件進行重寫。 當前AOF文件大小是上第二天志重寫獲得AOF文件大小的二倍(設置爲100)時,自動啓動新的日誌重寫過程。 auto-aof-rewrite-min-size 64mb 設置容許重寫的最小aof文件大小,避免了達到約定百分比但尺寸仍然很小的狀況還要重寫 aof-load-truncated yes aof文件可能在尾部是不完整的,當redis啓動的時候,aof文件的數據被載入內存。 重啓可能發生在redis所在的主機操做系統宕機後,尤爲在ext4文件系統沒有加上data=ordered選項,出現這種現象 redis宕機或者異常終止不會形成尾部不完整現象,能夠選擇讓redis退出,或者導入儘量多的數據。 若是選擇的是yes,當截斷的aof文件被導入的時候,會自動發佈一個log給客戶端而後load。 若是是no,用戶必須手動redis-check-aof修復AOF文件才能夠。
舒適提示,咱們將Redis的數據持久化後,咱們還須要備份嗎?其實在分佈式存儲系統中,有副本這個概念。單機備份顯得並非那麼重要了~