Redis(REmote DIctionary Server)基础

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

  Redis是一个开放源代码(BSD许可)的内存数据结构存储,用作数据库、缓存和消息代理。它支持字符串、哈希、列表、集合、带范围查询的排序集合、位图、超日志、带半径查询和流的地理空间索引等数据结构。Redis具有内置的复制、Lua脚本、LRU收回、事务和不同级别的磁盘上持久性,并通过Redis Sentinel和Redis群集的自动分区提供高可用性。官方地址:https://redis.io/

  在生产环境中Redis一般有三种用途,可以用作数据库(Database),缓存(Cache),消息队列(Message Queue)。因此不关你是开发还是运维人员,学习一下Redis还是很有必要的!

一.安装Redis

1>.本篇博客操作环境介绍

[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat /etc/redhat-release
CentOS Linux release 7.6. (Core)
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# uname -r
3.10.-.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
drwxr-xr-x. root root Mar : back
-rw-r--r--. root root Mar : CentOS-Base.repo
drwxr-xr-x. root root Mar : 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 :- will be installed
--> Finished Dependency Resolution Dependencies Resolved ==============================================================================================================================================
Package Arch Version Repository Size
==============================================================================================================================================
Installing:
epel-release noarch - extras k Transaction Summary
==============================================================================================================================================
Install Package Total download size: k
Installed size: k
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
epel-release--.noarch.rpm | kB ::
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : epel-release--.noarch /
Verifying : epel-release--.noarch / Installed:
epel-release.noarch :- 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
drwxr-xr-x. root root Mar : back
-rw-r--r--. root root Mar : CentOS-Base.repo
drwxr-xr-x. root root Mar : default
-rw-r--r-- root root Oct epel.repo
-rw-r--r-- root root Oct 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服务

[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 ::
* base: mirrors.aliyun.com
* epel: mirrors.yun-idc.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
epel | 4.7 kB ::
(/): epel/x86_64/group_gz | kB ::
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/. (/): epel/x86_64/updateinfo | 1.0 MB ::
(/): epel/x86_64/primary_db | 6.6 MB ::
Available Packages
Name : redis
Arch : x86_64
Version : 3.2.
Release : .el7
Size : 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 :3.2.-.el7 will be installed
--> Processing Dependency: libjemalloc.so.()(64bit) for package: redis-3.2.-.el7.x86_64
--> Running transaction check
---> Package jemalloc.x86_64 :3.6.-.el7 will be installed
--> Finished Dependency Resolution Dependencies Resolved ==============================================================================================================================================
Package Arch Version Repository Size
==============================================================================================================================================
Installing:
redis x86_64 3.2.-.el7 epel k
Installing for dependencies:
jemalloc x86_64 3.6.-.el7 epel k Transaction Summary
==============================================================================================================================================
Install Package (+ Dependent package) Total download size: k
Installed size: 1.7 M
Downloading packages:
warning: /var/cache/yum/x86_64//epel/packages/jemalloc-3.6.-.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
Public key for jemalloc-3.6.-.el7.x86_64.rpm is not installed
(/): jemalloc-3.6.-.el7.x86_64.rpm | kB ::
(/): redis-3.2.-.el7.x86_64.rpm | kB ::
----------------------------------------------------------------------------------------------------------------------------------------------
Total 3.4 MB/s | kB ::
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--.noarch (@extras)
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : jemalloc-3.6.-.el7.x86_64 /
Installing : redis-3.2.-.el7.x86_64 /
Verifying : redis-3.2.-.el7.x86_64 /
Verifying : jemalloc-3.6.-.el7.x86_64 / Installed:
redis.x86_64 :3.2.-.el7 Dependency Installed:
jemalloc.x86_64 :3.6.-.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.
/usr/share/doc/redis-3.2./-RELEASENOTES
/usr/share/doc/redis-3.2./BUGS
/usr/share/doc/redis-3.2./CONTRIBUTING
/usr/share/doc/redis-3.2./MANIFESTO
/usr/share/doc/redis-3.2./README.md
/usr/share/licenses/redis-3.2.
/usr/share/licenses/redis-3.2./COPYING
/usr/share/man/man1/redis-benchmark..gz
/usr/share/man/man1/redis-check-aof..gz
/usr/share/man/man1/redis-check-rdb..gz
/usr/share/man/man1/redis-cli..gz
/usr/share/man/man1/redis-sentinel..gz
/usr/share/man/man1/redis-server..gz
/usr/share/man/man5/redis-sentinel.conf..gz
/usr/share/man/man5/redis.conf..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 -- :: PDT; 4s ago
Main PID: (redis-server)
CGroup: /system.slice/redis.service
└─ /usr/bin/redis-server 127.0.0.1: Apr :: node101.yinzhengjie.org.cn systemd[]: Starting Redis persistent key-value database...
Apr :: node101.yinzhengjie.org.cn systemd[]: 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 127.0.0.1: *:*
LISTEN *: *:*
LISTEN ::: :::*
[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:>
127.0.0.1:>
127.0.0.1:> HELP
redis-cli 3.2.
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:>

[root@node101.yinzhengjie.org.cn ~]# redis-cli            #连接Redis

 127.0.0.1:> HELP
redis-cli 3.2.
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:>
127.0.0.1:> 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. BRPOP key [key ...] timeout
summary: Remove and get the last element in a list, or block until one is available
since: 2.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. LINDEX key index
summary: Get an element from a list by its index
since: 1.0. LINSERT key BEFORE|AFTER pivot value
summary: Insert an element before or after another element in a list
since: 2.2. LLEN key
summary: Get the length of a list
since: 1.0. LPOP key
summary: Remove and get the first element in a list
since: 1.0. LPUSH key value [value ...]
summary: Prepend one or multiple values to a list
since: 1.0. LPUSHX key value
summary: Prepend a value to a list, only if the list exists
since: 2.2. LRANGE key start stop
summary: Get a range of elements from a list
since: 1.0. LREM key count value
summary: Remove elements from a list
since: 1.0. LSET key index value
summary: Set the value of an element in a list by its index
since: 1.0. LTRIM key start stop
summary: Trim a list to the specified range
since: 1.0. RPOP key
summary: Remove and get the last element in a list
since: 1.0. RPOPLPUSH source destination
summary: Remove the last element in a list, prepend it to another list and return it
since: 1.2. RPUSH key value [value ...]
summary: Append one or multiple values to a list
since: 1.0. RPUSHX key value
summary: Append a value to a list, only if the list exists
since: 2.2. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @list                        #查看list的帮助信息

二.Redis数据类型常用命令(注意:Redis所有的数据都是键值对的性质,只是其对应的值可能是字符串,也可能是列表,或者是集合等数据类型)

1>.Redis的通用命令介绍

127.0.0.1:>
127.0.0.1:> HELP @generic DEL key [key ...]
summary: Delete a key
since: 1.0. DUMP key
summary: Return a serialized version of the value stored at the specified key.
since: 2.6. EXISTS key [key ...]
summary: Determine if a key exists
since: 1.0. EXPIRE key seconds
summary: Set a key's time to live in seconds
since: 1.0. EXPIREAT key timestamp
summary: Set the expiration for a key as a UNIX timestamp
since: 1.2. KEYS pattern
summary: Find all keys matching the given pattern
since: 1.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. MOVE key db
summary: Move a key to another database
since: 1.0. OBJECT subcommand [arguments [arguments ...]]
summary: Inspect the internals of Redis objects
since: 2.2. PERSIST key
summary: Remove the expiration from a key
since: 2.2. PEXPIRE key milliseconds
summary: Set a key's time to live in milliseconds
since: 2.6. PEXPIREAT key milliseconds-timestamp
summary: Set the expiration for a key as a UNIX timestamp specified in milliseconds
since: 2.6. PTTL key
summary: Get the time to live for a key in milliseconds
since: 2.6. RANDOMKEY -
summary: Return a random key from the keyspace
since: 1.0. RENAME key newkey
summary: Rename a key
since: 1.0. RENAMENX key newkey
summary: Rename a key, only if the new key does not exist
since: 1.0. RESTORE key ttl serialized-value [REPLACE]
summary: Create a key using the provided serialized value, previously obtained using DUMP.
since: 2.6. SCAN cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate the keys space
since: 2.8. 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. TTL key
summary: Get the time to live for a key
since: 1.0. TYPE key
summary: Determine the type stored at key
since: 1.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. 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:>
127.0.0.1:>

127.0.0.1:6379> HELP @generic

2>.切换数据库命令

127.0.0.1:>
127.0.0.1:> HELP select SELECT index
summary: Change the selected database for the current connection
since: 1.0.
group: connection 127.0.0.1:>

127.0.0.1:6379> HELP select

3>.字符串命令介绍

127.0.0.1:>
127.0.0.1:> HELP @string APPEND key value
summary: Append a value to a key
since: 2.0. BITCOUNT key [start end]
summary: Count set bits in a string
since: 2.6. 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. BITOP operation destkey key [key ...]
summary: Perform bitwise operations between strings
since: 2.6. BITPOS key bit [start] [end]
summary: Find first bit set or clear in a string
since: 2.8. DECR key
summary: Decrement the integer value of a key by one
since: 1.0. DECRBY key decrement
summary: Decrement the integer value of a key by the given number
since: 1.0. GET key
summary: Get the value of a key
since: 1.0. GETBIT key offset
summary: Returns the bit value at offset in the string value stored at key
since: 2.2. GETRANGE key start end
summary: Get a substring of the string stored at a key
since: 2.4. GETSET key value
summary: Set the string value of a key and return its old value
since: 1.0. INCR key
summary: Increment the integer value of a key by one
since: 1.0. INCRBY key increment
summary: Increment the integer value of a key by the given amount
since: 1.0. INCRBYFLOAT key increment
summary: Increment the float value of a key by the given amount
since: 2.6. MGET key [key ...]
summary: Get the values of all the given keys
since: 1.0. MSET key value [key value ...]
summary: Set multiple keys to multiple values
since: 1.0. MSETNX key value [key value ...]
summary: Set multiple keys to multiple values, only if none of the keys exist
since: 1.0. PSETEX key milliseconds value
summary: Set the value and expiration in milliseconds of a key
since: 2.6. SET key value [EX seconds] [PX milliseconds] [NX|XX]
summary: Set the string value of a key
since: 1.0. SETBIT key offset value
summary: Sets or clears the bit at offset in the string value stored at key
since: 2.2. SETEX key seconds value
summary: Set the value and expiration of a key
since: 2.0. SETNX key value
summary: Set the value of a key, only if the key does not exist
since: 1.0. SETRANGE key offset value
summary: Overwrite part of a string at key starting at the specified offset
since: 2.2. STRLEN key
summary: Get the length of the value stored in a key
since: 2.2. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @string

127.0.0.1:>
127.0.0.1:> SET name Jason          #创建一个Key为name,其值为Jason
OK
127.0.0.1:>
127.0.0.1:> KEYS *               #获取所有的keys
) "name"
127.0.0.1:>
127.0.0.1:> GET name              #获取name对应的值
"Jason"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> SET name Jason              #创建一个Key为name,其值为Jason

127.0.0.1:> SET name Yinzhengjie       
OK
127.0.0.1:>
127.0.0.1:>
127.0.0.1:> GET name
"Yinzhengjie"
127.0.0.1:>
127.0.0.1:> SET name Jason EX         #设置一个变量指定过期时间为5秒钟
OK
127.0.0.1:>
127.0.0.1:> GET name               #五秒内变量是有效的
"Jason"
127.0.0.1:>
127.0.0.1:> GET name                #五秒后变量是无效的
(nil)
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> SET name Jason EX 5            #设置一个变量指定过期时间为5秒钟

127.0.0.1:>
127.0.0.1:> SETNX age           #SEINX表示一个KEY存在就不做任何操作,若不存在就创建改KEY对应的值
(integer)
127.0.0.1:>
127.0.0.1:> GET age
""
127.0.0.1:>
127.0.0.1:> SETNX age
(integer)
127.0.0.1:>
127.0.0.1:> GET age
""
127.0.0.1:>

127.0.0.1:6379> SETNX age 18                #SEINX表示一个KEY存在就不做任何操作,若不存在就创建改KEY对应的值

127.0.0.1:>
127.0.0.1:> SET count
OK
127.0.0.1:>
127.0.0.1:> INCR count            #对数值操作的自增命令
(integer)
127.0.0.1:>
127.0.0.1:> INCR count
(integer)
127.0.0.1:>
127.0.0.1:> INCR count
(integer)
127.0.0.1:>

127.0.0.1:6379> INCR count                #对数值操作的自增命令

127.0.0.1:>
127.0.0.1:> INCR count
(integer)
127.0.0.1:>
127.0.0.1:> DECR count                #对数值操作的自减命令
(integer)
127.0.0.1:>
127.0.0.1:> DECR count
(integer)
127.0.0.1:>
127.0.0.1:> DECR count
(integer)
127.0.0.1:>
127.0.0.1:> DECR count
(integer)
127.0.0.1:>
127.0.0.1:> DECR count
(integer)
127.0.0.1:>
127.0.0.1:> DECR count
(integer)
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> DECR count                #对数值操作的自减命令

127.0.0.1:>
127.0.0.1:> MSET name Jason age
OK
127.0.0.1:>
127.0.0.1:>
127.0.0.1:> get name
"Jason"
127.0.0.1:>
127.0.0.1:> get age
""
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> MSET name Jason age 18         #一次性设置多个键值对

127.0.0.1:>
127.0.0.1:> MSET name Jason age
OK
127.0.0.1:>
127.0.0.1:> MGET name age
) "Jason"
) ""
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> MGET name age              #一次性获取多个键值对

4>.列表相关命令介绍

127.0.0.1:> 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. BRPOP key [key ...] timeout
summary: Remove and get the last element in a list, or block until one is available
since: 2.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. LINDEX key index
summary: Get an element from a list by its index
since: 1.0. LINSERT key BEFORE|AFTER pivot value
summary: Insert an element before or after another element in a list
since: 2.2. LLEN key
summary: Get the length of a list
since: 1.0. LPOP key
summary: Remove and get the first element in a list
since: 1.0. LPUSH key value [value ...]
summary: Prepend one or multiple values to a list
since: 1.0. LPUSHX key value
summary: Prepend a value to a list, only if the list exists
since: 2.2. LRANGE key start stop
summary: Get a range of elements from a list
since: 1.0. LREM key count value
summary: Remove elements from a list
since: 1.0. LSET key index value
summary: Set the value of an element in a list by its index
since: 1.0. LTRIM key start stop
summary: Trim a list to the specified range
since: 1.0. RPOP key
summary: Remove and get the last element in a list
since: 1.0. RPOPLPUSH source destination
summary: Remove the last element in a list, prepend it to another list and return it
since: 1.2. RPUSH key value [value ...]
summary: Append one or multiple values to a list
since: 1.0. RPUSHX key value
summary: Append a value to a list, only if the list exists
since: 2.2. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @list

127.0.0.1:>
127.0.0.1:> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun        #定义一个列表
(integer)
127.0.0.1:>
127.0.0.1:> LINDEX weekdays                         #获取第0个元素
"Sun"
127.0.0.1:>

127.0.0.1:6379> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun        #定义一个列表

127.0.0.1:>
127.0.0.1:> LPUSH weekdays Sat Fri Thu Wed Tue Mon Sun
(integer)
127.0.0.1:>
127.0.0.1:> LINDEX weekdays
"Sun"
127.0.0.1:>
127.0.0.1:>
127.0.0.1:> LPOP weekdays        #弹栈操作,先进后出,于是我们把最右侧的数据给删除啦!
"Sun"
127.0.0.1:>
127.0.0.1:> LINDEX weekdays
"Mon"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> LPOP weekdays                          #弹栈操作,先进后出,于是我们把最右侧的数据给删除啦!

127.0.0.1:>
127.0.0.1:> LLEN weekdays                          #获取当前列表的长度
(integer)
127.0.0.1:>
127.0.0.1:> RPUSHX weekdays Sun                      #在列表的最右侧添加一个值
(integer)
127.0.0.1:>
127.0.0.1:> LLEN weekdays
(integer)
127.0.0.1:>
127.0.0.1:> LINDEX weekdays
"Sun"
127.0.0.1:>

127.0.0.1:6379> RPUSHX weekdays Sun                      #在列表的最右侧添加一个值

5>.关联数组命令介绍

127.0.0.1:> HELP @hash

  HDEL key field [field ...]
summary: Delete one or more hash fields
since: 2.0. HEXISTS key field
summary: Determine if a hash field exists
since: 2.0. HGET key field
summary: Get the value of a hash field
since: 2.0. HGETALL key
summary: Get all the fields and values in a hash
since: 2.0. HINCRBY key field increment
summary: Increment the integer value of a hash field by the given number
since: 2.0. HINCRBYFLOAT key field increment
summary: Increment the float value of a hash field by the given amount
since: 2.6. HKEYS key
summary: Get all the fields in a hash
since: 2.0. HLEN key
summary: Get the number of fields in a hash
since: 2.0. HMGET key field [field ...]
summary: Get the values of all the given hash fields
since: 2.0. HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values
since: 2.0. HSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate hash fields and associated values
since: 2.8. HSET key field value
summary: Set the string value of a hash field
since: 2.0. HSETNX key field value
summary: Set the value of a hash field, only if the field does not exist
since: 2.0. HSTRLEN key field
summary: Get the length of the value of a hash field
since: 3.2. HVALS key
summary: Get all the values in a hash
since: 2.0. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @hash

127.0.0.1:> HMSET stu1 id  name tom age  course "linux"          #给关联数组设置多个值
OK
127.0.0.1:>
127.0.0.1:> HGET stu1 course                            #获取stu1的 course信息,下面的获取方式都是在获取stu1的相关信息!
"linux"
127.0.0.1:>
127.0.0.1:> HGET stu1 name                              
"tom"
127.0.0.1:>
127.0.0.1:> HGET stu1 age                              
""
127.0.0.1:>
127.0.0.1:>
127.0.0.1:> HGET stu1 id
""
127.0.0.1:>

127.0.0.1:6379> HMSET stu1 id 1 name tom age 18 course "linux"          #给关联数组设置多个值

127.0.0.1:> HVALS stu1                                   #查看stu1的相关信息
) ""
) "tom"
) ""
) "linux"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HVALS stu1                               #查看stu1的相关信息,只包括值

127.0.0.1:> HGETALL stu1
) "id"
) ""
) "name"
) "tom"
) "age"
) ""
) "course"
) "linux"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HGETALL stu1                             #获取stu1的相关信息,会将字段名称也会显示出来!比上面那条指令显示的更详细,包括键值对

6>.集合命令介绍

127.0.0.1:>
127.0.0.1:> HELP @set SADD key member [member ...]
summary: Add one or more members to a set
since: 1.0. SCARD key
summary: Get the number of members in a set
since: 1.0. SDIFF key [key ...]
summary: Subtract multiple sets
since: 1.0. SDIFFSTORE destination key [key ...]
summary: Subtract multiple sets and store the resulting set in a key
since: 1.0. SINTER key [key ...]
summary: Intersect multiple sets
since: 1.0. SINTERSTORE destination key [key ...]
summary: Intersect multiple sets and store the resulting set in a key
since: 1.0. SISMEMBER key member
summary: Determine if a given value is a member of a set
since: 1.0. SMEMBERS key
summary: Get all the members in a set
since: 1.0. SMOVE source destination member
summary: Move a member from one set to another
since: 1.0. SPOP key [count]
summary: Remove and return one or multiple random members from a set
since: 1.0. SRANDMEMBER key [count]
summary: Get one or multiple random members from a set
since: 1.0. SREM key member [member ...]
summary: Remove one or more members from a set
since: 1.0. SSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate Set elements
since: 2.8. SUNION key [key ...]
summary: Add multiple sets
since: 1.0. SUNIONSTORE destination key [key ...]
summary: Add multiple sets and store the resulting set in a key
since: 1.0. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @set

127.0.0.1:> SADD colors1 red green gray puple
(integer)
127.0.0.1:>
127.0.0.1:> SADD colors2 gree yellow bule pink gray
(integer)
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> SADD colors1 red green gray puple                #定义集合

127.0.0.1:>
127.0.0.1:> SADD colors1 red green gray puple
(integer)
127.0.0.1:>
127.0.0.1:> SADD colors2 gree yellow bule pink gray
(integer)
127.0.0.1:>
127.0.0.1:> SINTER colors1 colors2
) "gray"
127.0.0.1:>

127.0.0.1:6379> SINTER colors1 colors2                       #获取交集

127.0.0.1:> SADD colors1 red green gray puple
(integer)
127.0.0.1:>
127.0.0.1:> SADD colors2 gree yellow bule pink gray
(integer)
127.0.0.1:>
127.0.0.1:> SUNION colors1 colors2
) "puple"
) "gray"
) "green"
) "pink"
) "gree"
) "bule"
) "yellow"
) "red"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> SUNION colors1 colors2                       #获取并集

127.0.0.1:> SADD colors1 red green gray puple
(integer)
127.0.0.1:>
127.0.0.1:> SADD colors2 gree yellow bule pink gray
(integer)
127.0.0.1:>
127.0.0.1:> SDIFF colors1 colors2
) "red"
) "green"
) "puple"
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> SDIFF colors1 colors2                        #获取差集

127.0.0.1:> SADD colors1 red green gray puple
(integer)
127.0.0.1:>
127.0.0.1:> SISMEMBER colors1 red                #成员关系判定,判断是clors1中是否包含红色,如果返回值为1表示包含,如果返回值为0表示不包含!
(integer)
127.0.0.1:> SISMEMBER colors1 blue
(integer)
127.0.0.1:>

127.0.0.1:6379> SISMEMBER colors1 red                        #成员关系判定,判断是clors1中是否包含红色,如果返回值为1表示包含,如果返回值为0表示不包含!

7>.有序集合命令介绍

127.0.0.1:> 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. ZCARD key
summary: Get the number of members in a sorted set
since: 1.2. ZCOUNT key min max
summary: Count the members in a sorted set with scores within the given values
since: 2.0. ZINCRBY key increment member
summary: Increment the score of a member in a sorted set
since: 1.2. 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. ZLEXCOUNT key min max
summary: Count the number of members in a sorted set between a given lexicographical range
since: 2.8. ZRANGE key start stop [WITHSCORES]
summary: Return a range of members in a sorted set, by index
since: 1.2. ZRANGEBYLEX key min max [LIMIT offset count]
summary: Return a range of members in a sorted set, by lexicographical range
since: 2.8. ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
summary: Return a range of members in a sorted set, by score
since: 1.0. ZRANK key member
summary: Determine the index of a member in a sorted set
since: 2.0. ZREM key member [member ...]
summary: Remove one or more members from a sorted set
since: 1.2. ZREMRANGEBYLEX key min max
summary: Remove all members in a sorted set between the given lexicographical range
since: 2.8. ZREMRANGEBYRANK key start stop
summary: Remove all members in a sorted set within the given indexes
since: 2.0. ZREMRANGEBYSCORE key min max
summary: Remove all members in a sorted set within the given scores
since: 1.2. 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. 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. 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. ZREVRANK key member
summary: Determine the index of a member in a sorted set, with scores ordered from high to low
since: 2.0. ZSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate sorted sets elements and associated scores
since: 2.8. ZSCORE key member
summary: Get the score associated with the given member in a sorted set
since: 1.2. 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. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @sorted_set

127.0.0.1:> ZADD liangshan  Songjiang  Wuyong  Chaogai
(integer)
127.0.0.1:>

127.0.0.1:6379> ZADD liangshan 108 Songjiang 107 Wuyong 106 Chaogai        #定义一个有序的集合

127.0.0.1:> ZSCORE liangshan Wuyong
""
127.0.0.1:>

127.0.0.1:6379> ZSCORE liangshan Wuyong                         #获取某个成员对应的分数

127.0.0.1:> ZCOUNT liangshan
(integer)
127.0.0.1:>

127.0.0.1:6379> ZCOUNT liangshan 106 120                        #统计分数在106~120之间成员个数

127.0.0.1:> ZRANK liangshan Wuyong
(integer)
127.0.0.1:>
127.0.0.1:> ZRANK liangshan Songjiang
(integer)
127.0.0.1:>
127.0.0.1:> ZRANK liangshan Chaogai
(integer)
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> ZRANK liangshan Wuyong                          #排名

8>.发布(Publish)订阅(Subscribe)相关命令

127.0.0.1:> HELP @pubsub

  PSUBSCRIBE pattern [pattern ...]
summary: Listen for messages published to channels matching the given patterns
since: 2.0. PUBLISH channel message
summary: Post a message to a channel
since: 2.0. PUBSUB subcommand [argument [argument ...]]
summary: Inspect the state of the Pub/Sub subsystem
since: 2.8. PUNSUBSCRIBE [pattern [pattern ...]]
summary: Stop listening for messages posted to channels matching the given patterns
since: 2.0. SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0. UNSUBSCRIBE [channel [channel ...]]
summary: Stop listening for messages posted to the given channels
since: 2.0. 127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> HELP @pubsub

127.0.0.1:>
127.0.0.1:> PUBLISH yinzhengjie-redis "redis not is kafka"
(integer)
127.0.0.1:>
127.0.0.1:>

127.0.0.1:6379> PUBLISH yinzhengjie-redis "redis not is kafka"          #(发布)往yinzhengjie-redis队列发送消息

127.0.0.1:> SUBSCRIBE yinzhengjie-redis
Reading messages... (press Ctrl-C to quit)
) "subscribe"
) "yinzhengjie-redis"
) (integer)
) "message"
) "yinzhengjie-redis"
) "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:>
node101.yinzhengjie.org.cn:> HELP @connection AUTH password
summary: Authenticate to the server
since: 1.0. ECHO message
summary: Echo the given string
since: 1.0. PING [message]
summary: Ping the server
since: 1.0. QUIT -
summary: Close the connection
since: 1.0. SELECT index
summary: Change the selected database for the current connection
since: 1.0. node101.yinzhengjie.org.cn:>

node101.yinzhengjie.org.cn:6379> HELP @connection 

[root@node101.yinzhengjie.org.cn ~]# redis-cli -h node101.yinzhengjie.org.cn
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> KEYS *
(error) NOAUTH Authentication required.
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> AUTH yinzhengjie          #使用AUTH关键字进行认证,后面跟的字符串表示认证的密码,这个字符串必须和Redis服务器中配置文件的requirepass关键字设置一致!方可认证成功!
OK
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> KEYS *
) "stu1"
) "name"
) "weekdays"
) "liangshan"
) "color"
) "count"
) "colors2"
) "colors1"
) "age"
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> 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:>
node101.yinzhengjie.org.cn:> KEYS *
) "stu1"
) "name"
) "weekdays"
) "liangshan"
) "color"
) "count"
) "colors2"
) "colors1"
) "age"
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> 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:> PING                                      #如果节点存错,就会相应PONG字符串
PONG
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:>

node101.yinzhengjie.org.cn:6379> PING                                      #如果节点存错,就会相应PONG字符串

node101.yinzhengjie.org.cn:> ECHO "My name is Jason Yin"
"My name is Jason Yin"
node101.yinzhengjie.org.cn:>

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 172.30.1.101: *:*
LISTEN *: *:*
LISTEN ::: :::*
[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. Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
-h <hostname> Server hostname (default: 127.0.0.1).
-p <port> Server port (default: ).
-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 sec. Change it using -i.
--latency-dist Shows latency as a spectrum, requires xterm colors.
Default time interval is sec. Change it using -i.
--lru-test <keys> Simulate a cache workload with an - 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: . Use 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 lpush mylist x
redis-cli -r -i 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
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:>
node101.yinzhengjie.org.cn:> 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使用的清楚策略。有以下几种可以选择:
  >.volatile-lru
      利用LRU算法移除设置过过期时间的key (LRU:最近使用 Least Recently Used )
  >.allkeys-lru
      利用LRU算法移除任何key
  >.volatile-random
      移除设置过过期时间的随机key
  >.allkeys-random
      移除随机ke
  >.volatile-ttl
      移除即将过期的key(minor TTL)
  >.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这五个值,每个值含义如下:
  -: 每个quicklist节点上的ziplist大小不能超过64 Kb。(注:1kb => bytes)
  -: 每个quicklist节点上的ziplist大小不能超过32 Kb。
  -: 每个quicklist节点上的ziplist大小不能超过16 Kb。
  -: 每个quicklist节点上的ziplist大小不能超过8 Kb。(-2是Redis给出的默认值)
  -: 每个quicklist节点上的ziplist大小不能超过4 Kb。 list-compress-depth参数:
  这个参数表示一个quicklist两端不被压缩的节点个数。注:这里的节点个数是指quicklist双向链表的节点个数,而不是指ziplist里面的数据项个数。实际上,一个quicklist节点上的ziplist,如果被压缩,就是整体被压缩的。参数list-compress-depth的取值含义如下:
  : 是个特殊值,表示都不压缩。这是Redis的默认值。
  : 表示quicklist两端各有1个节点不压缩,中间的节点压缩。
  : 表示quicklist两端各有2个节点不压缩,中间的节点压缩。
  : 表示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参数:
  (一般指正常客户端)对客户端输出缓冲进行限制可以强迫那些不从服务器读取数据的客户端断开连接,用来强制关闭传输缓慢的客户端。对于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 参数:
  (订阅发布模式)对于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
save
save
存 DB 到磁盘:
格式:save <间隔时间(秒)> <写入次数>
根据给定的时间间隔和写入次数将数据保存到磁盘
下面的例子的意思是:
秒内如果至少有 个 key 的值变化,则保存
秒内如果至少有 个 key 的值变化,则保存
秒内如果至少有 个 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
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的数据持久化后,我们还需要备份吗?其实在分布式存储系统中,有副本这个概念。单机备份显得并不是那么重要了~

Redis(REmote DIctionary Server)基础的更多相关文章

  1. [CDH] Redis: Remote Dictionary Server

    基本概念 一.安装 Redis: Remote Dictionary Server 远程字典服务 使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种 ...

  2. Redis : REmote DIctionary Server

    REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...

  3. Redis教程(REmote DIctionary Server)——一个高性能的key-value数据库

    redis(REmote DIctionary Server)是什么? Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言 ...

  4. redis(Remote Dictionary Server)

    redis的简介和使用   简介 redis(Remote Dictionary Server)是一种Nosql技术,它是一个开源的高级kv存储和数据结构存储系统,它经常被拿来和Memcached相比 ...

  5. redis基础-Remote Dictionary Server

    Redis支持多个数据库,并且每个数据库的数据是隔离的不能共享,并且基于单机才有,如果是集群就没有数据库的概念. Redis默认支持16个数据库(可以通过配置文件支持更多,无上限),可以通过配置dat ...

  6. Redis(Remote Dictionary Server)入门

    说说特性 存储结构:键值对支持多种数据类型,包括字符串类型,散列类型,列表类型,集合类型,有序集合类型. 内存存储与持久化:支持将内存中的数据异步写入磁盘中. 丰富的功能:支持为每个键值对设置生存时间 ...

  7. 二:Redis:(REmote DIctionary Server)远程字典服务器

    Redis是完全开源免费的,用C语言编写的,遵循BSD协议,是一个高性能的(key-value)分布式内存数据库,基于内存运行,并支持持久化的NOSQL数据库,是当前最热门的NOSQL数据库之一,也被 ...

  8. Redis基本认识和基础学习-基本命令

    Redis 基本介绍 REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANS ...

  9. Step by step Install a Local Report Server and Remote Report Server Database

    原创地址:http://www.cnblogs.com/jfzhu/p/4012097.html 转载请注明出处 前面的文章<Step by step SQL Server 2012的安装 &g ...

随机推荐

  1. 基础学习14天 MD5加密

    private static string GetMD5(string str) { //创建MD5对象 MD5 md5 = MD5.Create(); //字符串类型转换Wie字节 byte[] b ...

  2. sql判断字段是否为空

    sql语句条件查询时,有时会判断某个字段是否为空. 字段内容为空有两种情况 1.为null 2.为字符串的空'' 语句如下: select * from table where column is n ...

  3. topjui中datagrid增删改查

    1.掌握datagrid的创建方式在html中直接定义与在js中定义 可参考easyui的官方文档:http://www.jeasyui.net/plugins/183.html 2.实现代码如下:重 ...

  4. duilib

    https://www.cnblogs.com/lin1270/p/4109305.html

  5. Linux查询进程和结束进程

    1.  ps -ef |grep redis ps:将某个进程显示出来-A 显示所有程序. -e 此参数的效果和指定"A"参数相同.-f 显示UID,PPIP,C与STIME栏位. ...

  6. 贷款资讯类APP、贷款资讯网站廉价卖,需要的进来看看

    [app介绍]卡贷资讯app为您提供信用卡申请攻略及借款资讯以及贷款口子,让你借钱借款路上不再愁.[功能特点]1.资讯:聚合各种贷款资讯知识,掌握核心信用卡申请攻略,借款借钱不亏,亦不被骗:2.工具: ...

  7. (十三)Batch Processing

    In addition to being able to index, update, and delete individual documents, Elasticsearch also prov ...

  8. leetcode 224. Basic Calculator 、227. Basic Calculator II

    这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...

  9. AI 生成式对抗网络(GAN)

    生成式对抗网络(Generative Adversarial Network,简称GAN),主要由两部分构成:生成模型G和判别模型D.训练GAN就是两种模型的对抗过程. 生成模型:利用任意噪音(ran ...

  10. webpack4配置详解之常用插件分享

    前言 继上一次webpack的基础配置分享之后,本次将分享一些工作中项目常用的配置插件.也会包含一些自己了解过觉得不错的插件,如有分析不到位的,欢迎纠错,嗯,这些东西文档都有,大佬可绕过. Wepac ...