# 1.官网下载redis source code并编译redis Make $ wget https://download.redis.io/releases/redis-6.2.5.tar.gz $ tar xzf redis-6.2.5.tar.gz $ cd redis-6.2.5 $ make $ make test # \o/ All tests passed without errors! # Cleanup: may take some time... OK # make[1]: 离开目录“/opt/databases/redis-6.2.5/src”
#4.验证服务是不是成功 #使用测试客户端程序redis-cli和redis服务交互了 $ redis-cli redis> ping # PONG 测试redis状态 redis> set foo bar redis> get foo # "bar"
From the official Ubuntu PPA
1 2 3 4
You can install the latest stable version of Redis from the redislabs/redis package repository. Add the repository to the apt index, update it and install: $ sudo add-apt-repository ppa:redislabs/redis $ sudo apt-get update $ sudo apt-get install redis
From Snapcraft You can install the latest stable version of Redis from the Snapcraft marketplace: $ sudo snap install redis
0x02 Redis 常用工具命令
redis-server 命令
描述: 它是redis服务启动的命令,提供数据库存储服务。
语法格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Usage: ./redis-server [/path/to/redis.conf] [options] [-] ./redis-server - (read config from stdin) ./redis-server -v or --version ./redis-server -h or --help ./redis-server --test-memory <megabytes>
Examples: ./redis-server (run the server with default conf) ./redis-server /etc/redis/6379.conf ./redis-server --port 7777 ./redis-server --port 7777 --replicaof 127.0.0.1 8888 ./redis-server /etc/myredis.conf --loglevel verbose - ./redis-server /etc/myredis.conf --loglevel verbose
# 用作键空间分析器,它扫描数据集的大键,但也提供有关数据集包含的数据类型的信息。 # 在输出的第一部分中报告了遇到的每个大于先前较大键(相同类型)的新键,摘要部分提供有关 Redis 实例内数据的一般统计信息。 $ redis-cli --bigkeys [00.00%] Biggest string found so far 'key-419' with 3 bytes [05.14%] Biggest list found so far 'mylist' with 100004 items [35.77%] Biggest string found so far 'counter:__rand_int__' with 6 bytes [73.91%] Biggest hash found so far 'myobject' with 3 fields
-------- summary ------- Sampled 506 keys in the keyspace! Total key length in bytes is 3452 (avg len 6.82) Biggest string found 'counter:__rand_int__' has 6 bytes Biggest list found 'mylist' has 100004 items Biggest hash found 'myobject' has 3 fields
# 4.通常在检测到断开连接后,CLI 总是会尝试透明地重新连接:如果尝试失败,则显示错误并进入断开连接状态。 # 以下是断开和重新连接的示例: 127.0.0.1:6379> debug restart Could not connect to Redis at 127.0.0.1:6379: Connection refused not connected> ping # PONG 127.0.0.1:6379> (now we are connected again)
# 5.执行重新连接时,redis-cli自动重新选择上次选择的数据库编号。 $ redis-cli 127.0.0.1:6379> multi OK 127.0.0.1:6379(TX)> ping # QUEUED
# COMMAND 命令相关 redis> COMMAND # 返回所有的Redis命令的详细信息,以数组形式展示 redis> COMMAND COUNT # 返回命令总数 (integer) 200 redis> COMMAND GETKEYS MSET a b c d e f #获取给定命令的所有键 redis> COMMAND INFO get seteval#获取 redis 命令的描述信息
# Note on units: when memory size is needed, it is possible to specify # 单元不区分大小写, 它通常采用1k 5GB 4M等形式: # 1k => 1000 bytes # 1kb => 1024 bytes # 1m => 1000000 bytes # 1mb => 1024*1024 bytes # 1g => 1000000000 bytes # 1gb => 1024*1024*1024 bytes
################################## INCLUDES ################################### # 指定包含其它的配置文件,可以在同一主机上多个Redis实例之间使用同一份配置文件,而同时各个实例又拥有自己的特定配置文件,值得注意是命令“CONFIG REWRITE”不会重写选项“include”。 # include /path/to/local.conf # include /path/to/other.conf
################################## NETWORK ##################################### # 服务绑定的接口支持IPV6 # bind 192.168.1.100 10.0.0.1 # listens on two specific IPv4 addresses # bind 127.0.0.1 ::1 # listens on loopback IPv4 and IPv6 # bind * -::* # like the default, all available interfaces # 如果您确定希望您的实例侦听所有接口,只需注释掉以下行。 bind 127.0.0.1 -::1
# 受保护模式是一层安全保护,以避免访问和利用互联网上打开的Redis实例,当且仅当如下情况需要设置为YES # 1)服务器未使用“bind”指令显式绑定到一组地址。 # 2)未配置密码 protected-mode no
# Accept connections on the specified port, default is 6379 (IANA #815344). # 如果指定端口 0 Redis将不会侦听TCP套接字。 port 6379
################################# TLS/SSL ##################################### # By default, TLS/SSL is disabled. To enable it, the "tls-port" configuration. port 0 tls-port 6379
################################# GENERAL ##################################### # 后台守护进程启动 daemonize yes
# 如果您从upstart或systemd运行Redis,Redis可以与您的监控树交互。选项: # supervised no - no supervision interaction # supervised upstart - signal upstart by putting Redis into SIGSTOP mode requires "expect stop" in your upstart job config # supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET on startup, and updating Redis status on a regular basis. # supervised auto - detect upstart or systemd method based on UPSTART_JOB or NOTIFY_SOCKET environment variables # 默认值为“否”,要在upstart/systemd下运行,只需取消对以下行的注释: supervised auto
# 指定服务器详细级别 # 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
# 自定义Redis交互式终端标题,模板变量在花括号中指定。支持以下变量: # {title} Name of process as executed if parent, or type of child process. # {listen-addr} Bind address or '*' followed by TCP or TLS port listening on, or Unix socket if only that's available. # {server-mode} Special mode, i.e. "[sentinel]" or "[cluster]". # {port} TCP port listening on, or 0. # {tls-port} TLS port listening on, or 0. # {unixsocket} Unix domain socket listening on, or "". # {config-file} Name of configuration file used. proc-title-template "{title} {listen-addr} {server-mode}"
################################ SNAPSHOTTING ################################ # 工作目录,例如DB将写入此目录中,使用上面使用“dbfilename”配置指令指定的文件名。 dir ./
# 转储数据库的文件名 dbfilename dump.rdb
# 将数据库保存到磁盘, 如果给定的秒数和对数据库执行的写入操作数同时发生,Redis将保存数据库。 # 分别表示3600秒(15分钟)内有1个更改,300秒(5分钟)内有10个更改以及60秒内有10000个更改。 save 3600 1 save 300 100 save 60 10000
# 转储.rdb数据库时使用LZF压缩字符串对象(当空间有多余的时候建议以空间换取时间) - 性能考虑可设置为 no # 如果要在保存子项中保存一些CPU,请将其设置为“否”,但如果有可压缩的值或键,则数据集可能会更大。 rdbcompression yes
# 是否进行本地数据库rdb文件校验 - 性能考虑可设置为 no rdbchecksum yes
# 加载RDB或还原负载时,启用或禁用ziplist和listpack等的完全卫生检查,这减少了以后处理命令时断言或崩溃的机会。 # Options: # no - Never perform full sanitation # yes - Always perform full sanitation # clients - Perform full sanitation only for user connections. # Excludes: RDB files, RESTORE commands received from the master # connection, and client connections which have the skip-sanitize-payload ACL flag. # 默认值应为“clients”,但由于它当前会通过MIGRATE影响群集重新存储,因此默认情况下会临时设置为“no”。 sanitize-dump-payload no
# 在未启用持久性的实例中删除复制使用的RDB文件,默认情况下此选项处于禁用状态,请注意此选项仅适用于同时禁用AOF和RDB持久性的实例,否则将完全忽略。 rdb-del-sync-files no
################################# REPLICATION ################################# # 主副本复制,使用Replicatof将Redis实例制作为另一台Redis服务器的副本。 # # +------------------+ +---------------+ # | Master | ---> | Replica | # | (receive writes) | | (exact copy) | # +------------------+ +---------------+ # # 1) Redis replication is asynchronous, but you can configure a master to # stop accepting writes if it appears to be not connected with at least a given number of replicas. # 2) Redis replicas are able to perform a partial resynchronization with the # master if the replication link is lost for a relatively small amount of # time. You may want to configure the replication backlog size (see the next sections of this file) with a sensible value depending on your needs. # 3) Replication is automatic and does not need user intervention. After a # network partition replicas automatically try to reconnect to masters and resynchronize with them. replicaof <masterip> <masterport>
# 复制同步策略:磁盘或套接字,传输可以通过两种不同的方式进行: # 1) Disk-backed: The Redis master creates a new process that writes the RDB file on disk. Later the file is transferred by the parent process to the replicas incrementally. # 2) Diskless: The Redis master creates a new process that directly writes the RDB file to replica sockets, without touching the disk at all. # 使用磁盘备份复制,在生成RDB文件的同时,只要生成RDB文件的当前子级完成其工作,就可以将更多副本排入队列并与RDB文件一起提供服务。 # 使用无盘复制,在传输开始后,到达的新复制副本将排队,并且在当前复制副本终止时,将开始新的传输。 # 对于慢速磁盘和快速(大带宽)网络,无盘复制效果更好。 repl-diskless-sync no
# 复制副本可以直接从套接字加载从复制链接读取的RDB,或者将RDB存储到一个文件中,并在完全从主机接收到该文件后读取该文件。 # "disabled" - Don't use diskless load (store the rdb file to the disk first) # "on-empty-db" - Use diskless load only when it is completely safe. # "swapdb" - Keep a copy of the current db contents in RAM while parsing the data directly from the socket. note that this requires sufficient memory, if you don't have it, you risk an OOM kill. repl-diskless-load disabled
# 以下选项设置的复制超时: # 1) Bulk transfer I/O during SYNC, from the point of view of replica. # 2) Master timeout from the point of view of replicas (data, pings). # 3) Replica timeout from the point of view of masters (REPLCONF ACK pings).
# Redis ACL users are defined in the following format: # user <username> ... acl rules ... # For example: # user worker +@list +@connection ~jobs:* on >ffa9203c493aa99 # # 特殊用户名“default”用于新连接。如果此用户具有“nopass”规则,则新连接将立即作为“默认”用户进行身份验证,而无需通过AUTH命令提供任何密码。否则,如果“默认”用户未标记为“nopass” # 这些连接将在未验证状态下启动,并且需要AUTH(或HELLO命令AUTH选项)才能进行验证和验证 # # The ACL rules that describe what a user can do are the following: # # on Enable the user: it is possible to authenticate as this user. # off Disable the user: it's no longer possible to authenticate # with this user, however the already authenticated connections # will still work. # skip-sanitize-payload RESTORE dump-payload sanitation is skipped. # sanitize-payload RESTORE dump-payload is sanitized (default). # +<command> Allow the execution of that command # -<command> Disallow the execution of that command # +@<category> Allow the execution of all the commands in such category # with valid categories are like @admin, @set, @sortedset, ... # and so forth, see the full list in the server.c file where # the Redis command table is described and defined. # The special category @all means all the commands, but currently # present in the server, and that will be loaded in the future # via modules. # +<command>|subcommand Allow a specific subcommand of an otherwise # disabled command. Note that this form is not # allowed as negative like -DEBUG|SEGFAULT, but only additive starting with "+". # allcommands Alias for +@all. Note that it implies the ability to execute # all the future commands loaded via the modules system. # nocommands Alias for -@all. # ~<pattern> Add a pattern of keys that can be mentioned as part of # commands. For instance ~* allows all the keys. The pattern # is a glob-style pattern like the one of KEYS. # It is possible to specify multiple patterns. # allkeys Alias for ~* # resetkeys Flush the list of allowed keys patterns. # &<pattern> Add a glob-style pattern of Pub/Sub channels that can be # accessed by the user. It is possible to specify multiple channel # patterns. # allchannels Alias for &* # resetchannels Flush the list of allowed channel patterns. # ><password> Add this password to the list of valid password for the user. # For example >mypass will add "mypass" to the list. # This directive clears the "nopass" flag (see later). # <<password> Remove this password from the list of valid passwords. # nopass All the set passwords of the user are removed, and the user # is flagged as requiring no password: it means that every # password will work against this user. If this directive is # used for the default user, every new connection will be # immediately authenticated with the default user without # any explicit AUTH command required. Note that the "resetpass" # directive will clear this condition. # resetpass Flush the list of allowed passwords. Moreover removes the # "nopass" status. After "resetpass" the user has no associated # passwords and there is no way to authenticate without adding # some password (or setting it as "nopass" later). # reset Performs the following actions: resetpass, resetkeys, off, # -@all. The user returns to the same state it has immediately after its creation. #
# ACL规则可以按任何顺序指定:例如,您可以从密码开始,然后是标志或密钥模式。但是请注意,加法和减法规则将根据顺序改变含义。 # 例如,请参见以下示例: # user alice on +@all -DEBUG ~* >somepassword # # 这将允许“alice”使用除DEBUG命令之外的所有命令,因为+@all将所有命令添加到alice可以使用的命令集中,并且随后删除了DEBUG。但是,如果我们颠倒两个ACL规则的顺序,结果将不同: # user alice on -DEBUG +@all ~* >somepassword # the Redis web site at https://redis.io/topics/acl
# ACL LOG: 在下面定义ACL日志的最大条目长度 acllog-max-len 128
# Using an external ACL file, 不在该redis.conf配置acl而是在aclfile指定的路径。 aclfile /etc/redis/users.acl
# MAXMEMORY策略:当到达MAXMEMORY时,Redis将如何选择要删除的内容。您可以从以下行为中选择一种: # volatile-lru -> Evict using approximated LRU, only keys with an expire set. (折中) # allkeys-lru -> Evict any key using approximated LRU. # volatile-lfu -> Evict using approximated LFU, only keys with an expire set. # allkeys-lfu -> Evict any key using approximated LFU. # volatile-random -> Remove a random key having an expire set. # allkeys-random -> Remove a random key, any key. # volatile-ttl -> Remove the key with the nearest expire time (minor TTL) # noeviction -> Don't evict anything, just return an error on write operations. (缺省) # # LRU means Least Recently Used # LFU means Least Frequently Used # # LRU、LFU和volatile ttl都是使用近似随机算法实现的。 # 注意:对于上述任何策略,当没有合适的键进行逐出时,Redis将在需要更多内存的写入操作上返回错误。这些命令通常用于创建新键、添加数据或修改现有键。 # 例如:SET、INCR、HSET、LPUSH、SUNIONSTORE、SORT(由于STORE参数),以及EXEC(如果事务包含任何需要内存的命令)。 maxmemory-policy volatile-lru
# Redis有两个用于删除关键点的原语。一个称为DEL,是对象的块删除。这意味着服务器停止处理新命令,以便以同步方式回收与对象关联的所有内存。如果删除的键与一个小对象关联,则执行DEL命令所需的时间非常短,与Redis中的大多数其他O(1)或O(log_N)命令相当。但是,如果密钥与包含数百万个元素的聚合值相关联,则服务器可以阻塞很长时间(甚至几秒钟)以完成操作。 # 出于上述原因,Redis还提供了非阻塞删除原语,如UNLINK(非阻塞DEL)和FLUSHDB命令的异步选项,以便在后台回收内存。这些命令在固定时间内执行。另一个线程将尽可能快地增量释放背景中的对象。 # FLUSHDB和FLUSHDB的DEL、UNLINK和ASYNC选项由用户控制。这取决于应用程序的设计,以了解何时使用其中一个是一个好主意。然而,作为其他操作的副作用,Redis服务器有时不得不删除密钥或刷新整个数据库。具体来说,Redis在以下场景中独立于用户调用删除对象: # # 1) On eviction, because of the maxmemory and maxmemory policy configurations, # in order to make room for new data, without going over the specified memory limit. # 2) Because of expire: when a key with an associated time to live (see the # EXPIRE command) must be deleted from memory. # 3) Because of a side effect of a command that stores data on a key that may # already exist. For example the RENAME command may delete the old key # content when it is replaced with another one. Similarly SUNIONSTORE # or SORT with STORE option may delete existing keys. The SET command # itself removes any old content of the specified key in order to replace # it with the specified string. # 4) During replication, when a replica performs a full resynchronization with # its master, the content of the whole database is removed in order to load the RDB file just transferred. # # 在上述所有情况下,默认是以阻塞方式删除对象,就像调用 DEL 一样。 但是,您可以使用以下配置指令专门配置每种情况,以便以非阻塞方式释放内存,就像调用 UNLINK 一样。 lazyfree-lazy-eviction no lazyfree-lazy-expire no lazyfree-lazy-server-del no replica-lazy-flush no
# 也可以在用 UNLINK 调用替换用户代码 DEL 调用并不容易的情况下,使用以下配置指令修改 DEL 命令的默认行为以使其行为与 UNLINK 完全相同: lazyfree-lazy-user-del no
############################ KERNEL OOM CONTROL ############################## # 在 Linux 上,可以提示内核 OOM 杀手在内存不足时应该首先杀死哪些进程。 # 启用此功能使Redis 主动控制其所有进程的oom_score_adj 值,具体取决于它们的角色。默认分数将尝试在所有其他进程之前杀死后台子进程,并在主进程之前杀死副本。 # Redis supports three options: # no: Don't make changes to oom-score-adj (default). # yes: Alias to "relative" see below. # absolute: Values in oom-score-adj-values are written as is to the kernel. # relative: Values are used relative to the initial value of oom_score_adj when # the server starts and are then clamped to a range of -1000 to 1000. # Because typically the initial value is 0, they will often match the absolute values. oom-score-adj no
############################# EVENT NOTIFICATION ############################## # Redis 可以将密钥空间中发生的事件通知 Pub/Sub 客户端。documented at https://redis.io/topics/notifications # 例如,如果启用了键空间事件通知,并且客户端对存储在数据库 0 中的键“foo”执行 DEL 操作,则将通过 Pub/Sub 发布两条消息:in the Database 0, two messages will be published via Pub/Sub: # 可以在一组类中选择 Redis 将通知的事件,每个类都由一个字符标识: # PUBLISH __keyspace@0__:foo del # PUBLISH __keyevent@0__:del foo # K Keyspace events, published with __keyspace@<db>__ prefix. # E Keyevent events, published with __keyevent@<db>__ prefix. # g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... # $ String commands # l List commands # s Set commands # h Hash commands # z Sorted set commands # x Expired events (events generated every time a key expires) # e Evicted events (events generated when a key is evicted for maxmemory) # t Stream commands # d Module key type events # m Key-miss events (Note: It is not included in the 'A' class) # A Alias for g$lshzxetd, so that the "AKE" string means all the events # (Except key-miss events which are excluded from 'A' due to their # unique nature).
# 默认情况下所有通知都是禁用的,因为大多数用户不需要此功能并且该功能有一些开销。请注意,如果您没有指定 K 或 E 中的至少一个,则不会传递任何事件。 notify-keyspace-events ""
############################### GOPHER SERVER ################################# # Redis contains an implementation of the Gopher protocol, as specified in the RFC 1436 (https://www.ietf.org/rfc/rfc1436.txt). # Gopher 协议在 90 年代后期非常流行。它是 Web 的替代方案,服务器端和客户端的实现都非常简单,Redis 服务器只有 100 行代码来实现这种支持。 # 你现在用 Gopher 做什么? # 好吧,Gopher 从未真正消亡,最近有一项运动,以便让 Gopher 由纯文本文档组成的更具层次性的内容复活。 有些人想要一个更简单的互联网,其他人则认为主流互联网受到了太多控制,为想要呼吸新鲜空气的人们创造一个替代空间是很酷的。 # # --- HOW IT WORKS? --- # Redis Gopher 支持使用Redis 的内联协议,特别是两种无论如何都是非法的内联请求:空请求或任何以“/”开头的请求(没有Redis 命令以这样的斜杠开头)。 正常的 RESP2/RESP3 请求完全脱离了 Gopher 协议实现的路径,并且也照常提供。 # # 如果您在启用 Gopher 时打开与 Redis 的连接并向其发送一个类似“/foo”的字符串,如果有一个名为“/foo”的键,它将通过 Gopher 协议提供服务。 # # 为了创建一个真正的 Gopher “洞”(Gopher 谈话中 Gopher 站点的名称),您可能需要一个如下所示的脚本 # https://github.com/antirez/gopher2redis # # --- SECURITY WARNING --- # If you plan to put Redis on the internet in a publicly accessible address # to server Gopher pages MAKE SURE TO SET A PASSWORD to the instance. # Once a password is set: # 1. The Gopher server (when enabled, not by default) will still servecontent via Gopher. # 2. However other commands cannot be called before the client willauthenticate. # # 注意:当启用 'io-threads-do-reads' 时不支持 Gopher,并且应该使用'requirepass'选项来保护你的实例。 # gopher-enabled no
# 列表也以特殊方式编码,以节省大量空间。 每个内部列表节点允许的条目数可以指定为固定的最大大小或最大元素数。 对于固定的最大大小,使用 -5 到 -1,意思是: # -5: max size: 64 Kb <-- not recommended for normal workloads # -4: max size: 32 Kb <-- not recommended # -3: max size: 16 Kb <-- probably not recommended # -2: max size: 8 Kb <-- good # -1: max size: 4 Kb <-- good # 正数意味着每个列表节点存储最多 _exactly_ 的元素数。 性能最高的选项通常是 -2(8 Kb 大小)或 -1(4 Kb 大小),但如果您的用例是独一无二的,请根据需要调整设置。 list-max-ziplist-size -2
# 列表也可以被压缩。压缩深度是从列表的*每一*侧到*排除*压缩的quicklist ziplist节点的数量。 对于快速推送/弹出操作,列表的头部和尾部总是未压缩的。 # 0: disable all list compression # 1: depth 1 means "don't start compressing until after 1 node into the list, # going from either the head or tail" # So: [head]->node->node->...->node->[tail] # [head], [tail] will always be uncompressed; inner nodes will compress. # 2: [head]->[next]->node->node->...->node->[prev]->[tail] # 2 here means: don't compress head or head->next or tail->prev or tail, # but compress all nodes between them. # 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] # etc. list-compress-depth 0
########################### ACTIVE DEFRAGMENTATION ####################### # # What is active defragmentation? # 什么是主动碎片整理? # ------------------------------- # 主动(在线)碎片整理允许 Redis 服务器压缩内存中小数据分配和释放之间留下的空间,从而允许回收内存。 # 分片是每个分配器(但幸运的是 Jemalloc 除外)和某些工作负载发生的自然过程。 通常需要重新启动服务器以降低碎片,或者至少清除所有数据并再次创建它。 然而,由于 Oran Agra 为 Redis 4.0 实现的这个功能,这个过程可以在运行时以“热”的方式发生,而服务器正在运行。
# 基本上当碎片超过一定程度时(请参阅下面的配置选项)Redis 将开始通过利用某些特定的 Jemalloc 功能在连续内存区域中创建值的新副本(以便了解分配是否导致碎片并在 一个更好的地方),同时,将释放数据的旧副本。 这个过程,对所有键递增重复,将导致碎片回落到正常值。 # ------------------------------- # 重要事项: # 1. This feature is disabled by default, and only works if you compiled Redis to use the copy of Jemalloc we ship with the source code of Redis. This is the default with Linux builds. # # 2. You never need to enable this feature if you don't have fragmentation issues. # # 3. Once you experience fragmentation, you can enable this feature when needed with the command "CONFIG SET activedefrag yes". # 配置参数能够微调碎片整理过程的行为如果您不确定它们的含义,最好保持默认值不变。
方式1.请访问本博主的B站【WeiyiGeek】首页关注UP主, 将自动随机获取解锁验证码。
Method 2.Please visit 【My Twitter】. There is an article verification code in the homepage.
方式3.扫一扫下方二维码,关注本站官方公众号
回复:验证码
将获取解锁(有效期7天)本站所有技术文章哟!