Redis常用命令

1、Redis基础命令

1.1、对key操作

  • keys *: 查看当前库所有的key
  • exists <key>:判断某个key是否存在
  • type <key>:查看key的类型
  • del <key>:删除指定key的数据
  • unlink <key>:根据value选择非阻塞删除,异步删除
  • expire <key> 10:给key设置过期时间,单位秒
  • ttl <key>:查看还有多少秒过期,-1表示不过期,-2表示已经过期

1.2、其他命令

  • select 1:切换到1号库
  • dbsize:查看当前数据库的key数量
  • flushdb:清空当前库
  • flushall:通杀全部库

2、字符串(String)

2.1、简介

  • String是Redis最基本的类型,key-value结构
  • String类型是二进制安全的。意味着Redis的string可以包含任何数据。比如jpg图片或者序列化的对象。
  • String类型是Redis最基本的数据类型,一个Redis中字符串value最多可以是512M。

2.2、常用命令

  • set <key> <value>:添加键值对(若key已经存在,会覆盖值)
  • get <key>:根据key取对应value值
  • append <key> <value>:在key对应的值后面追加value值
  • strlen <key>:获取值的长度
  • setnx <key> <value>:添加键值对(区别于set命令,只有key不存在才能设置成功)
  • incr <key>:将key中存储的数字值增1(只能对数字值操作,如果为空,新增值为1)
  • decr <key>:将key中存储的数字值减1(只能对数字值操作,如果为空,新增值为-1)
  • incrby/decrby <key> <步长>:将key中储存的数字值增减。自定义步长。
  • mset <key1> <value1> <key2> <value2> ...:同时设置一个或多个键值对
  • mget <key1> <key2> ...:同时获取多个键的value
  • msetnx <key1> <value1> <key2> <value2> ...:同时设置一个或多个键值对,当且仅当所有给定 key 都不存在。
  • getrange <key> <起始位置> <结束位置>:获得值的范围,类似于Java的substring。
  • setrange <key> <起始位置> <value>:用value覆写key所储存的字符串值,从起始位置开始
  • setex <key> <过期时间> <value>:设置键值对,同时设置过期时间
  • getset <key> <value> :设置新值,同时获取旧值

2.3、数据结构

  • String的数据结构为简单动态字符串(Simple Dynamic String,缩写SDS)。是可以修改的字符串,内部结构实现上类似于Java的ArrayList,采用预分配冗余空间的方式来减少内存的频繁分配。
  • 内部为当前字符串实际分配的空间一般要高于实际字符串长度。当字符串长度小于1M时,扩容都是加倍现有的空间,如果超过1M,扩容时一次只会多扩1M的空间。需要注意的是字符串最大长度为512M。

3、列表(List)

3.1、简介

  • 单键多值结构
  • Redis 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)。
  • 它的底层实际是个双向链表,对两端的操作性能很高,通过索引下标的操作中间的节点性能会较差。

3.2、常用命令

  • lpush/rpush <key> <value1> <value2> <value3> ...:从左边/右边插入一个或多个值。
  • lpop/rpop <key>:从左边/右边吐出一个值。吐出后值就不存在了,相当于删除,值全都吐出,键就会自动删除
  • rpoplpush <key1><key2>:从key1列表右边吐出一个值,插到key2列表左边。
  • lrange <key> <start> <stop>:按照索引下标获得元素(从左到右),例如lrange mylist 0 -1:0左边第一个,-1右边第一个,也就是获取所有值
  • lindex <key> <index>:按照索引下标获得元素(从左到右)
  • llen <key>:获得列表长度
  • linsert <key> before <value> <newvalue>:在value的后面插入newvalue插入值
  • lrem <key> <n> <value>:从左边删除n个value(从左到右)
  • lset <key> <index> <value>:将列表key下标为index的值替换成value

3.3、数据结构

  • List的数据结构为快速链表quickList。

  • 首先在列表元素较少的情况下会使用一块连续的内存存储,这个结构是ziplist,也即是压缩列表。它将所有的元素紧挨着一起存储,分配的是一块连续的内存。当数据量比较多的时候才会改成quicklist。

  • 因为普通的链表需要的附加指针空间太大,会比较浪费空间。比如这个列表里存的只是int类型的数据,结构上还需要两个额外的指针prev和next。

  • Redis将链表和ziplist结合起来组成了quicklist。也就是将多个ziplist使用双向指针串起来使用。这样既满足了快速的插入删除性能,又不会出现太大的空间冗余。

4、集合(Set)

4.1、简介

  • Redis set对外提供的功能与list类似是一个列表的功能,特殊之处在于set是可以自动排重的,当你需要存储一个列表数据,又不希望出现重复数据时,set是一个很好的选择,并且set提供了判断某个成员是否在一个set集合内的重要接口,这个也是list所不能提供的。
  • Redis的Set是string类型的无序集合。它底层其实是一个value为null的hash表,所以添加,删除,查找的**复杂度都是O(1)**。
  • 一个算法,随着数据的增加,执行时间的长短,如果是O(1),数据增加,查找数据的时间不变。

4.2、常用命令

  • sadd <key> <value1> <value2> ...:将一个或多个元素加入到集合 key 中,已经存在的元素将被忽略。
  • smembers <key>:取出该集合的所有值。
  • sismember <key> <value>:判断集合key是否为含有该value值,有为1,没有为0
  • scard<key>:返回该集合的元素个数。
  • srem <key> <value1> <value2> ...:删除集合中的某个元素。
  • spop <key>:随机从该集合中吐出(删除)一个值,删完了,key就不存在了。
  • srandmember <key> <n>:随机从该集合中取出n个值。不会从集合中删除。
  • smove <key1> <key2> <value>:把k1集合中一个value值移动到另一个k2集合
  • sinter <key1> <key2>:返回两个集合的交集元素。
  • sunion <key1> <key2>:返回两个集合的并集元素。
  • sdiff <key1> <key2>:返回两个集合的差集元素(包含key1中的元素,不包含key2中的)

4.3、数据结构

  • Set数据结构是dict字典,字典是用哈希表实现的。
  • Java中HashSet的内部实现使用的是HashMap,只不过所有的value都指向同一个对象。Redis的set结构也是一样,它的内部也使用hash结构,所有的value都指向同一个内部值。

5、哈希(Hash)

5.1、简介

  • Redis hash 是一个键值对集合。
  • Redis hash是一个string类型的field和value的映射表,hash特别适合用于存储对象。
  • 类似Java里面的Map<String,Object>

5.2、常用命令

  • hset <key> <field> <value>:给key集合中的 field键赋值value
  • hget <key> <field>:从key集合field取出 value
  • hmset <key> <field1> <value1> <field2> <value2> ...:批量设置hash的值。
  • hexists <key> <field>:查看哈希表 key 中,给定域 field 是否存在。
  • hkeys <key>:列出该hash集合的所有field
  • hvals <key>:列出该hash集合的所有value
  • hincrby <key> <field> <increment>:为哈希表 key 中的域 field 的值加上增量increment。
  • hsetnx <key> <field> <value>:将哈希表 key 中的域 field 的值设置为 value ,当且仅当域 field 不存在 。

5.3、数据结构

  • Hash类型对应的数据结构是两种:ziplist(压缩列表),hashtable(哈希表)。当field-value长度较短且个数较少时,使用ziplist,否则使用hashtable。

6、有序集合(Zset)

6.1、简介

  • Redis有序集合zset与普通集合set非常相似,是一个没有重复元素的字符串集合。
  • 不同之处是有序集合的每个成员都关联了一个评分(score),这个评分(score)被用来按照从最低分到最高分的方式排序集合中的成员。集合的成员是唯一的,但是评分可以是重复的
  • 因为元素是有序的, 所以你也可以很快的根据评分(score)或者次序(position)来获取一个范围的元素。
  • 访问有序集合的中间元素也是非常快的,因此你能够使用有序集合作为一个没有重复成员的智能列表。

6.2、常用命令

  • zadd <key> <score1> <value1> <score2> <value2>…:将一个或多个元素及其score值加入到有序集合key当中。
  • zrange <key> <start> <stop> [withscores] :返回有序集 key 中,下标在start到stop之间的元素(带withscores,可以让分数一起和值返回到结果集)
  • zrangebyscore <key> <min> <max> [withscores]:返回有序集 key 中,所有score值介于min和max之间(包括等于min或max)的成员。有序集成员按score值递增(从小到大)次序排列。
  • zrevrangebyscore <key> <max> <min> [withscores]:同上,改为从大到小排列。
  • zincrby <key> <increment> <value>:为元素的score加上增量increment
  • zrem <key> <value>:删除该集合下,指定值的元素。
  • zcount <key> <min> <max>:统计该集合,分数区间内的元素个数。
  • zrank <key> <value>:返回该值在集合中的排名,从0开始。

6.3、数据结构

  • SortedSet(zset)是Redis提供的一个非常特别的数据结构,一方面它等价于Java的数据结构Map<String, Double>,可以给每一个元素value赋予一个权重score,另一方面它又类似于TreeSet,内部的元素会按照权重score进行排序,可以得到每个元素的名次,还可以通过score的范围来获取元素的列表。

  • zset底层使用了两个数据结构

    1. hash,hash的作用就是关联元素value和权重score,保障元素value的唯一性,可以通过元素value找到相应的score值。
    2. 跳跃表,跳跃表的目的在于给元素value排序,根据score的范围获取元素列表。

7、配置文件介绍

Redis配置文件在redis目录下的redis.conf。

① Units单位

配置大小单位,开头定义了一些基本的度量单位,只支持bytes,不支持bit。大小写不敏感

1
2
3
4
5
6
7
8
9
10
11
# Note on units: when memory size is needed, it is possible to specify
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.

② INCLUDES包含

类似jsp中的include,多实例的情况可以把公用的配置文件提取出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
################################## INCLUDES ###################################

# Include one or more other config files here. This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings. Include files can include
# other files, so use this wisely.
#
# Notice option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include .\path\to\local.conf
# include c:\path\to\other.conf

③ 网络相关配置

bind:默认情况bind=127.0.0.1只能接受本机的访问请求。

不写的情况下,无限制接受任何ip地址的访问

生产环境肯定要写你应用服务器的地址;服务器是需要远程访问的,所以需要将其注释掉

如果开启了protected-mode,那么在没有设定bind ip且没有设密码的情况下,Redis只允许接受本机的响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind 127.0.0.1

protected-mode:将本机访问保护模式设置,默认yes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Protected mode is a layer of security protection, in order to avoid that
# Redis instances left open on the internet are accessed and exploited.
#
# When protected mode is on and if:
#
# 1) The server is not binding explicitly to a set of addresses using the
# "bind" directive.
# 2) No password is configured.
#
# The server only accepts connections from clients connecting from the
# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
# sockets.
#
# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode yes

port:端口号,默认6379

1
2
3
# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

tcp-backlog:是一个连接队列,默认值511

设置tcp的backlog,backlog其实是一个连接队列,backlog队列总和=未完成三次握手队列 + 已经完成三次握手队列。

在高并发环境下你需要一个高backlog值来避免慢客户端连接问题。

注意Linux内核会将这个值减小到/proc/sys/net/core/somaxconn的值(128),所以需要确认增大/proc/sys/net/core/somaxconn和/proc/sys/net/ipv4/tcp_max_syn_backlog(128)两个值来达到想要的效果

1
2
3
4
5
6
7
8
# TCP listen() backlog.
#
# In high requests-per-second environments you need an high backlog in order
# to avoid slow clients connections issues. Note that the Linux kernel
# will silently truncate it to the value of /proc/sys/net/core/somaxconn so
# make sure to raise both the value of somaxconn and tcp_max_syn_backlog
# in order to get the desired effect.
tcp-backlog 511

timeout:一个空闲的客户端维持多少秒会关闭,0表示关闭该功能。即永不关闭。

1
2
3
4
5
6
7
8
9
10
11
# Unix socket.
#
# Specify the path for the Unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /tmp/redis.sock
# unixsocketperm 700

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0

tcp-keepalive:对访问客户端的一种心跳检测,每个n秒检测一次。单位为秒,如果设置为0,则不会进行Keepalive检测,建议设置成60

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 300 seconds, which is the new
# Redis default starting with Redis 3.2.1.
tcp-keepalive 300

④ GENERAL通用

daemonize:是否为后台进程,设置为yes,守护进程,后台启动

1
2
3
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes

pidfile:存放pid文件的位置,每个实例会产生一个不同的pid文件

1
2
3
4
5
6
7
8
9
10
# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
# Creating a pid file is best effort: if Redis is not able to create it
# nothing bad happens, the server will start and run normally.
pidfile /var/run/redis_6379.pid

loglevel:指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为notice

四个级别根据使用阶段来选择,生产环境选择notice 或者warning

1
2
3
4
5
6
7
# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice

logfile:日志文件名称

1
2
3
# Specify the log file name. Also 'stdout' can be used to force
# Redis to log on the standard output.
logfile ""

databases:设定库的数量 默认16,默认数据库为0,可以使用SELECT <dbid>命令在连接上指定数据库id

1
2
3
4
# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT <dbid> where
# dbid is a number between 0 and 'databases'-1
databases 16

⑤ SECURITY安全

requirepass:访问密码的查看、设置和取消。在命令中设置密码,只是临时的。重启redis服务器,密码就还原了。永久设置,需要再配置文件中进行设置。

1
2
3
4
5
6
7
8
9
10
11
12
# Require clients to issue AUTH <PASSWORD> before processing any other
# commands. This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
# requirepass foobared

⑥ LIMITS限制

maxclients:设置redis同时可以与多少个客户端进行连接。默认情况下为10000个客户端。

如果达到了此限制,redis则会拒绝新的连接请求,并且向这些连接请求方发出“max number of clients reached”以作回应。

1
2
3
4
5
6
7
8
9
10
# Set the max number of connected clients at the same time. By default
# this limit is set to 10000 clients, however if the Redis server is not
# able to configure the process file limit to allow for the specified limit
# the max number of allowed clients is set to the current file limit
# minus 32 (as Redis reserves a few file descriptors for internal uses).
#
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 10000

maxmemory:建议必须设置,否则,将内存占满,造成服务器宕机

1
2
3
4
5
6
7
8
9
10
11
12
13
# NOTE: since Redis uses the system paging file to allocate the heap memory,
# the Working Set memory usage showed by the Windows Task Manager or by other
# tools such as ProcessExplorer will not always be accurate. For example, right
# after a background save of the RDB or the AOF files, the working set value
# may drop significantly. In order to check the correct amount of memory used
# by the redis-server to store the data, use the INFO client command. The INFO
# command shows only the memory used to store the redis data, not the extra
# memory used by the Windows process for its own requirements. Th3 extra amount
# of memory not reported by the INFO command can be calculated subtracting the
# Peak Working Set reported by the Windows Task Manager and the used_memory_peak
# reported by the INFO command.
#
# maxmemory <bytes>

1.1.1. maxmemory-policy

  • volatile-lru:使用LRU算法移除key,只对设置了过期时间的键;(最近最少使用)
  • allkeys-lru:在所有集合key中,使用LRU算法移除key
  • volatile-random:在过期集合中移除随机的key,只对设置了过期时间的键
  • allkeys-random:在所有集合key中,移除随机的key
  • volatile-ttl:移除那些TTL值最小的key,即那些最近要过期的key
  • noeviction:不进行移除。针对写操作,只是返回错误信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
# operations, when there are no suitable keys for eviction.
#
# At the date of writing these commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction