Redis(REmote DIctionary Server)基础

                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 ~]# ll /etc/yum.repos.d/        #安装epel源以前
[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 ~]# yum -y install epel-release
[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 ~]#
[root@node101.yinzhengjie.org.cn ~]# ll /etc/yum.repos.d/        #安装epel源以后,会生成2个文件

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 ~]# yum info redis            #查看Redis安装包的相应信息
[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 ~]# yum -y install redis        #安装Redis服务
[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 ~]#
[root@node101.yinzhengjie.org.cn ~]# rpm -ql redis            #查看Redis的相关安装软件

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 ~]# systemctl start redis
[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>
[root@node101.yinzhengjie.org.cn ~]# redis-cli            #链接Redis
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>
127.0.0.1:6379> HELP @list                        #查看list的帮助信息

 

二.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>
127.0.0.1:6379> HELP @generic

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>
127.0.0.1:6379> HELP select

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> HELP @string
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 Jason              #建立一个Key为name,其值为Jason
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> SET name Jason EX 5            #设置一个变量指定过时时间为5秒钟
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> SETNX age 18                #SEINX表示一个KEY存在就不作任何操做,若不存在就建立改KEY对应的值
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> INCR count                #对数值操做的自增命令
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> DECR count                #对数值操做的自减命令
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> MSET name Jason age 18         #一次性设置多个键值对
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>
127.0.0.1:6379> MGET name age              #一次性获取多个键值对

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> HELP @list
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> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun        #定义一个列表
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> LPOP weekdays                          #弹栈操做,先进后出,因而咱们把最右侧的数据给删除啦!
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>
127.0.0.1:6379> RPUSHX weekdays Sun                      #在列表的最右侧添加一个值

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> HELP @hash
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> HMSET stu1 id 1 name tom age 18 course "linux"          #给关联数组设置多个值
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> HVALS stu1                               #查看stu1的相关信息,只包括值
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>
127.0.0.1:6379> HGETALL stu1                             #获取stu1的相关信息,会将字段名称也会显示出来!比上面那条指令显示的更详细,包括键值对

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> HELP @set
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> SADD colors1 red green gray puple                #定义集合
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> SINTER colors1 colors2                       #获取交集
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> SUNION colors1 colors2                       #获取并集
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> SDIFF colors1 colors2                        #获取差集
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>
127.0.0.1:6379> SISMEMBER colors1 red                        #成员关系断定,判断是clors1中是否包含红色,若是返回值为1表示包含,若是返回值为0表示不包含!

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> HELP @sorted_set
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> ZADD liangshan 108 Songjiang 107 Wuyong 106 Chaogai        #定义一个有序的集合
127.0.0.1:6379> ZSCORE liangshan Wuyong "107"
127.0.0.1:6379>
127.0.0.1:6379> ZSCORE liangshan Wuyong                         #获取某个成员对应的分数
127.0.0.1:6379> ZCOUNT liangshan 106 120 (integer) 3
127.0.0.1:6379>
127.0.0.1:6379> ZCOUNT liangshan 106 120                        #统计分数在106~120之间成员个数
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>
127.0.0.1:6379> ZRANK liangshan Wuyong                          #排名

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> HELP @pubsub
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> PUBLISH yinzhengjie-redis "redis not is kafka"          #(发布)往yinzhengjie-redis队列发送消息
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"
127.0.0.1:6379> SUBSCRIBE yinzhengjie-redis                     #(订阅)启动消费者接受yinzhengjie-redis队列中的消息

 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>
node101.yinzhengjie.org.cn:6379> HELP @connection 
[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 ~]#
node101.yinzhengjie.org.cn:6379> AUTH yinzhengjie                             #使用AUTH关键字进行认证,后面跟的字符串表示认证的密码,这个字符串必须和Redis服务器中配置文件的requirepass关键字设置一致!方可认证成功!
[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 ~]#
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn -a yinzhengjie    #除了上面提到的登陆Redis后进行认证,咱们也能够在命令行中认证,风险就是咱们能够经过history命令查看到认证密码!这一点你们要注意哟!
node101.yinzhengjie.org.cn:6379> PING                                      #若是节点存错,就会相应PONG字符串 PONG node101.yinzhengjie.org.cn:6379> node101.yinzhengjie.org.cn:6379>
node101.yinzhengjie.org.cn:6379> PING                                      #若是节点存错,就会相应PONG字符串
node101.yinzhengjie.org.cn:6379> ECHO "My name is Jason Yin"
"My name is Jason Yin" node101.yinzhengjie.org.cn:6379>
node101.yinzhengjie.org.cn:6379> ECHO "My name is Jason Yin"

 

三.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 ~]#
[root@node101.yinzhengjie.org.cn ~]# systemctl restart redis

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 --help          #查看Redis的帮助信息
[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 ~]#
[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn -p 6379

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 设置快照文件的存放路径,这个配置项必定是个目录,而不能是文件名。建议生成环境系统盘和数据盘要分开,当操做系统出现故障时,不会影响到数据的存储!
RDB相关配置(SNAPSHOTTING)
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文件才能够。
AOF相关配置(APPEND ONLY MODE)

   舒适提示,咱们将Redis的数据持久化后,咱们还须要备份吗?其实在分布式存储系统中,有副本这个概念。单机备份显得并非那么重要了~

相关文章
相关标签/搜索