Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of getting started with redis4.0

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Preface

Redis, as a very popular member of the nosql family, is also favored by large Internet companies. Whether you are a developer, tester or operator, learning to master it will always add color to your career.

Of course, you already know redis more or less, but whether you know some details, this article will introduce the basics of redis in detail, and then we will introduce its advanced parts such as persistence, replication, clustering and so on. I hope it will be helpful to you.

It has been 3 years since the release of redis3.0. The stable version of redis officially provided by redis is 4.0. the following examples are carried out on version 4.0.

A brief introduction to redis

Overview

Redis (REmote DIctionary Server) is a key-value storage system written by Salvatore Sanfilippo. It is written by C language, complies with BSD protocol, supports network, memory-based and persistent log-type, Key-Value-type database, and provides API in multiple languages. Similar to Memcached, it supports relatively more value types, including string (string), list (linked list), set (collection), zset (sorted set-ordered collection), and hash (hash type). These data types support push/pop, add/remove, and take intersection union and difference sets, and richer operations, and these operations are atomic. On this basis, redis supports a variety of different sorting methods. Like memcached, data is cached in memory for efficiency. The difference is that redis will periodically write updated data to disk or modify operations to additional record files, and on this basis to achieve master-slave (master-slave) synchronization, redis introduced cluster mode in version 3.0.

Characteristics and advantages

K, v key value storage and data structure storage (such as lists, dictionaries) all data (including data storage) operations are completed in memory single-threaded service (which means there will be more blocking), using epoll model for request response, compared with nginx to support master-slave replication mode, but also provides rich programming interface support for highly available master-slave replication mode (sentry) decentralized distributed cluster For example, Python, Golang, Java, php, Ruby, Lua, Node.js are rich in functions. Besides supporting multiple data structures, they also support transaction, publish / subscribe, message queuing and other functions to support data persistence (AOF, RDB).

Contrast memcache

Memcache is a distributed in-memory object caching system that does not provide persistent storage, while redis has persistence. Memcache data storage is based on LRU (to put it simply: recently, at least key will be removed), while redis can be permanently saved (when the service is running all the time) memcache is multithreaded (which is one of the advantages of memcache), which means less blocking, while redis is single-threaded. Memcache only supports simple k and v data storage, while redis supports multiple data formats. Memcache is a multithreaded, non-blocking IO multiplexing network model, while redis is a single-threaded IO multiplexing model.

2. Start

Source deployment

Yum install gcc-y # installation C relies on wget http://download.redis.io/redis-stable.tar.gz # download stable version tar zxvf redis-stable.tar.gz # extract cd redis-stablemake PREFIX=/opt/app/redis install # specified directory compilation You can also create a configuration directory cp redis.conf / etc/redis/6379.conf # copy the configuration file cp utils/redis_init_script / etc/init.d/redis # copy the init startup script without specifying make installmkdir / etc/redis # add execution permissions vi / etc/redis/6379.conf # for 6.x system vi / etc/redis/6379.conf # modify the configuration file: bind 0.0.0.0 # listening address Maxmemory 4294967296 # limit maximum memory (4G): daemonize yes # background running # start and stop / etc/init.d/redis start/etc/init.d/redis stop

Check to see if the installation was successful

# execute client tool redis-cli # enter the command info127.0.0.1:6379 > info# Serverredis_version:4.0.10redis_git_sha1:00000000redis_git_dirty:0redis_build_id:cf83e9c690dbed33redis_mode:standaloneos:Linux 2.6.32-642.el6.x86_64 x86_64arch_bits:64multiplexing_api:epoll

Binary file description

After the redis installation is completed, the following executable files (exe files under window) will be generated. Here is the function of each file.

Redis-server # Redis server and Sentinel server can be started using-- sentinel designated as Sentinel redis-cli # Redis command line client redis-benchmark # Redis performance test tool redis-check-aof # AOF file repair tool redis-check-dump # RDB file detection tool redis-sentinel # Sentinel server, version 4.0 has made a soft link to redis-server III, configuration details

All configuration parameters of redis can be obtained from the client through the "CONFIG GET parameter name". The parameter name supports wildcards, such as * for all. The results are grouped sequentially. The first result is the parameter name, and the second result is the corresponding value of the parameter.

In addition to viewing the configuration, you can also use CONFIG SET to modify the configuration, and write to the configuration file using CONFIG REWRITE. When using it, you need to pay attention to the careful modification of some service configuration parameters, such as bind.

Configuration parameters and explanation, it should be noted that some configurations are added in 4.0.10, some configurations have been abolished, such as vm-related configurations, and cluster-related configurations are supplemented in the cluster chapter.

Logfile# log file location and file name bind 0.0.0.The listening address can be multiple, such as bind 0.0.0.0 127.0.0.1daemonize yes#yes startup daemon, that is, running in the background. No means that pidfile / var/run/redis.pid is not enabled. When redis is running in the background, Redis will put the pid file in / var/run/redis.pid by default, or you can configure it to other places. # when running multiple redis services, you need to specify different pid files and ports port 637ports to specify the port on which redis is running. The default is 6379unixsocket # sock file location unixsocketperm#sock file permissions timeout "to set the timeout period for client connection (in seconds). When the client does not issue any instructions during this period, then close the connection. 0 is to turn off this setting loglevel debug# specified logging level. Redis supports a total of four levels: debug, verbose, notice, and warning. The default is verboselogfile "" # log file configuration, default is stdout, and standard output. If the background mode outputs to / dev/nullsyslog-enabled# whether to log in syslog mode, yes enables no to disable. Configuration related to this configuration: syslog-ident and syslog-facility local0 indicate the number of databases available for syslog's ident and facilitydatabases configurations, respectively. The default value is 16, the default database is 0, and the database range is 0-(database-1). Always-show-logo yes # add configuration after 4. 0 whether to configure the log to display the redis logo Yes display no does not display # # Snapshot related configuration # # save 900 1save 300 10save 60 1000 snapshot configuration snapshot (rdb) facilitation rules Format: save # save 9001,900 seconds if at least one key is changed, take a snapshot # save 300 10300 seconds at least 300 key is changed, take a snapshot # save 60 10000 at least 10000 key is changed within 60 seconds, make a snapshot dbfilename dump.rdb#rdb persistent storage database file name, the default is dump.rdbstop-write-on-bgsave-error yes # yes means to stop writing RDB snapshot files when using the bgsave command persistence error No means to continue writing rdbchecksum yes# to open rdb file verification dir "/ etc" # data file storage directory Both rdb snapshot files and aof files are stored in this directory # # replication-related configuration parameters # # slaveof # set the database to be the slave database of other databases, when the local machine is a slave service Set the IP address and port of the master service. When Redis starts, it will automatically synchronize data from master. In masterauth # Master-Slave replication, set the password to connect to the master server (if master enables authentication) slave-serve-stale-data yes# when the slave library loses connection with the host or replication is in progress, the slave library can operate in two ways: # 1) if slave-serve-stale-data is set to yes (default) The slave library will continue the request from the corresponding client # 2) if slave-serve-stale-data means no, any request other than the INFO and SLAVOF commands will return an error "SYNC with master in progress" repl-ping-slave-period 1. The slave library will send a PING command to the master database at an interval to determine whether the master server is online. The default is 10 seconds repl-timeout 6 seconds to set the master database batch data transfer time or the ping reply interval timeout, and the default is 60 seconds # make sure that the repl-timeout is greater than the repl-ping-slave-periodrepl-backlog-size 1mb# setting replication backlog. It will be released only if at least one slave database is connected. Slave-priority 10 when the master library goes down, the sentry will choose the one with the highest priority to be called the master library, and the slave priority configuration defaults to 100. the lower the value, the higher the priority, the higher the min-slaves-to-write 3min-slaves-max-lag priority setting. If the number of slave libraries is less than this value, the host is not allowed to write within a certain value. The above parameters indicate that if the slave nodes of the master library are less than 3 within 10 seconds The main library does not accept write requests, and min-slaves-to-write 0 means to turn off this feature. # # Security-related configuration # # password for requirepass# client connection authentication. Default is empty, that is, no password is required. If configured, the command line uses AUTH to authenticate maxclients 1000 connections to set the maximum number of client connections at the same time. By default, the number of client connections that can be opened at the same time is the maximum number of file descriptors that can be opened by the Redis process. # if you set maxclients 0, there is no limit. # when the number of client connections reaches the limit Redis closes the new connection and returns the max number of clients reached error message to the client. Maxmemory 4gb# sets the maximum used memory size maxmemory-policy noeviction# setting reaches the maximum memory policy: # volatile-lru-> use the LRU algorithm to remove the key that sets the expiration time (LRU: recently used Least Recently Used) # allkeys-lru-> remove any key# volatile-random using the LRU algorithm-> remove the setting when it expires Random key# allkeys- > random-> remove a random key between Any key# volatile-ttl-> remove key that is about to expire (minor TTL) # 4.0 default noeviction means no key is deleted An error is returned only when writing. Algorithm sample settings such as maxmemory-samples 5 key## AOF LRU LFU, default 5 key## AOF related configurations # # appendonly no# setting AOF persistence, yes enabled, no disabled When enabled, redis will append every write request received to the appendonly.aof file, and when redis restarts, it will restore the previous state from the file. # but this will cause the appendonly.aof file to be too large, so redis also supports the BGREWRITEAOF directive to rewrite appendonly.aof. Appendfilename "appendonly.aof" # sets the AOF file name appendfsync everysec# AOF file write policy. Redis supports three strategies for synchronizing AOF files: # no: do not synchronize and leave it to the operating system to execute. Faster # always: always means that every write operation calls the fsync method to force the kernel to write the write operation to the file, which is slow but safe. Because each write operation is in the AOF file. # everysec: indicates that the write operation is accumulated and synchronized every second, and the compromise is "everysec" by default, which is the best compromise in terms of speed and security. When the no-appendfsync-on-rewrite no# AOF policy is set to always or everysec, the background process (background save or AOF log rewrite) will perform a large number of fsync O operations # will block overly long fsync () requests in some Linux configurations. Note that there is no fix now, even if fsync is processed in another thread. To alleviate this problem, you can set the following parameter no-appendfsync-on-rewriteauto-aof-rewrite-percentage 100auto-aof-rewrite-min-size 64mb#. When the AOF file grows to a certain size, Redis can call BGREWRITEAOF to rewrite the log file. Here's how it works: Redis remembers the size of the file after the last log (if it hasn't been rewritten since boot, the day size is determined at boot time). # the base size will be compared with the current size. If the current size is larger than the percentage set by the base size, the rewrite function will be enabled # and a minimum size needs to be specified for AOF rewriting, which is used to prevent rewriting AOF files even if the file is very small but growing a lot. # setting percentage to 0 turns off this feature # auto-aof-rewrite-percentage represents the file size per rewrite of the AOF file (as a percentage), 100% represents 100% That is, when the file is doubled, the AOF file # auto-aof-rewrite-min-size sets the minimum rewrite file size to avoid overwriting the file too many times when the file is small. When the redis suddenly crashes, the aof file will be truncated. Redis can exit and load errors when this occurs. The following options control this behavior. # if aof-load-truncated is set to yes, the truncated AOF file is loaded and the Redis server starts to issue a log to notify the user of the event. # otherwise, if this option is set to no, the server will abort with an error and stop starting. When this option is set to no Users need to use the "redis-check-aof" utility to repair the AOF file before restarting # # slow query configuration # # slowlog-log-slower-than 10000 # Redis Slow Log Record commands that exceed a specific execution time. The execution time does not include the slowlog O calculation, such as connecting the client, returning the result, etc., but the command execution time. You can set the slowlog through two parameters: one is the parameter slowlog-log-slower-than that tells the Redis how long it takes to be recorded (microseconds, so 1000000 represents one minute # the other is the length of the command. When a new command is recorded, the earliest command is removed from the queue. The slowlog-max-len 12 slow query command records the queue length setting, which takes up memory. Queue # # Advanced configuration # # hash-max-zipmap-entries 512hash-max-zipmap-value 6 can be cleared using SLOWLOG RESET when the hash contains more than a specified number of elements and the largest element does not exceed the threshold Hash will be stored in a special encoding mode (greatly reducing memory usage). Here you can set these two critical values: # Redis Hash corresponds to the fact that the internal Value is actually a HashMap. In fact, there are two different implementations. When the members of # this Hash are relatively small, Redis will use a compact storage method similar to an one-dimensional array in order to save memory, instead of using the real HashMap structure. The encoding of the corresponding value redisObject is zipmap, which is automatically converted to the real HashMap when the number of members increases, and encoding is ht. List-max-ziplist-size-2#Lists is also encoded in a special way to save a lot of space. # you can specify the number of entries allowed per internal list node # as the fixed maximum size or maximum number of elements. # for a fixed maximum size, use-5 to-1 to indicate: #-5: maximum size: 64 Kb

< - 不建议用于正常工作负载#-4:最大尺寸:32 Kb < - 不推荐#-3:最大尺寸:16 Kb < - 可能不推荐#-2:最大尺寸:8 Kb < - 好#-1:最大尺寸:4 Kb < - 良好#正数意味着存储_exactly_元素数量#每个列表节点。#性能最高的选项通常为-2(8 Kb大小)或-1(4 Kb大小)zset-max-ziplist-entries 128zset-max-ziplist-value 64# list数据类型多少节点以下会采用去指针的紧凑存储格式。# list数据类型节点值大小小于多少字节会采用紧凑存储格式。activerehashing yes# Redis将在每100毫秒时使用1毫秒的CPU时间来对redis的hash表进行重新hash,可以降低内存的使用# 当你的使用场景中,有非常严格的实时性需要,不能够接受Redis时不时的对请求有2毫秒的延迟的话,把这项配置为no。# 如果没有这么严格的实时性要求,可以设置为yes,以便能够尽可能快的释放内存client-output-buffer-limit normal 0 0 0client-output-buffer-limit slave 256mb 64mb 60client-output-buffer-limit pubsub 32mb 8mb 60#客户端输出缓冲区限制可用于强制断开客户端,由于某种原因,没有足够快地从服务器读取数据,常见的原因是Pub / Sub客户端不能像很快的消费一条消息,可以为三种不同类型的客户端设置不同的限制:#normal - >

Ordinary clients, including MONITOR client # subve-> from server client # pubsub-> client subscribed to at least one pubsub channel or mode # setting method: client-output-buffer-limit soft limit size hard limit size number of seconds # disconnect immediately when the client reaches the hard limit size, when the client reaches the soft limit and the number of seconds buffer size set still exceeds Then disconnect after the set number of seconds. 4. Data types and related operations.

Usually using redis is nothing more than using its commonly used 5 data types: string, list, hash, set, sorted_set. After version 3.2, geo longitude and latitude support has been added. The following will explain the common operations of its types.

Command to use the preface

Like most databases, all redis commands provide help. You can use the help + command name to see how to use it. The help information includes not only command usage, but also commands starting with version information, grouping, and so on.

For friendly use, redis also groups all commands and uses the help+@+ group name to view all commands in each group. Here is all the grouping information.

The above also describes how to view the use of commands, so when operating the following data types, only give examples of commonly used commands, and refer to https://redis.io/commands for more commands

Note: the geo data type has been added to redis in version 3.2.

Generic # general command group, string # string type command group for most types Use all string types list # list type command group set # collection type command group sorted_set # ordered collection command group hash # hash operation command group pubsub # issue command group transactions # transaction operation command group connection # connection related command group server # server related command group scripting # lua script command group hyperloglog # hyperloglog type command group Redis added HyperLogLog structure cluster # cluster related command group geo # longitude and latitude related command group in version 2.8.9, which is applicable to versions after 3.2.0.

Example: view all commands of transaction operation

Key operation

Commonly used:

DEL key # Delete a keyKEYS pattern # View all regular keyEXISTS key [key...] # determine whether a key exists, support multiple, return the number of key # refresh a key expiration time MOVE key db # move key to a database

Example:

String operation

It is important to note that integers in redis are also treated as strings.

Commonly used:

SET key value [EX seconds] [PX milliseconds] [NX | XX] # sets key to the specified string value. # Parameter: # EX seconds-sets the expiration time of the key key (in seconds) # PX milliseconds-sets the expiration time of the key key (in milliseconds # NX)-sets the value of key only if the key key does not exist # XX-sets the value of key only if the key key exists APPEND key value # if the key already exists and the value is a string, then this command appends the value to the end of the original value (value). If key does not exist, it will first create a key of an empty string and then perform an append operation, in which case the APPEND will be similar to the SET operation. GET key # gets the key value. If it does not exist, return nilGETRANGE key start end # to get the value corresponding to the start and end position of the index of the specified key value. The index starts at 0, GETSET key value # sets the new key value, and gets the value before the setting. If key does not exist, set it. And return nilMGET key [key...] # batch get the value of key MSET key value [key value...] # batch set the value of key DECR key # numeric type key self-subtract operation, if the key type is not a number, report an error INCR key # numeric type key self-add operation, contrary to DECR, DECRBY key decrement # numeric type key specifies decreasing numeric INCRBY key increment # numeric type key specifies increment value, as opposed to DECRBY STRLEN key # gets key length

Example:

List operation

The element index in the list starts at 0, and the reciprocal element can be represented by the "-" + reciprocal position, such as-2, which represents the penultimate element, and-1, which represents the last element.

The Redis list is a simple list of strings sorted in the order in which they are inserted. You can add an element to the head (left) or tail (right) of the list.

A list can contain up to 232-1 elements (4294967295, each list has more than 4 billion elements).

Commonly used:

LPUSH key value [value...] # put one or more elements from the left side of the list LPUSHX key value # when the list exists, put an element RPUSH key value [value.] # from the right side of the list, put one or more elements RPUSHX key value # when the list exists Put an element LSET key index value # from the right to set the value of the element in the list according to the index. When list does not exist, an error is reported. LINDEX key index # gets the element value according to the list index, and the index starts at 0 | AFTER pivot value # inserts the value based on a base point in the list, and pivot represents the base point LLEN key # get the list length LRANGE key start stop # get the elements in the list according to the index The last one in the list index can use-1LREM key count value # to remove the element # count > 0 with the previous count occurrence value of value from the list stored in key: remove the element # count with the value value from beginning to tail

< 0: 从尾往头移除值为 value 的元素#count = 0: 移除所有值为 value 的元素LPOP key #从列表左边删除一个元素RPOP key #从列表右边删除一个元素RPOPLPUSH source destination #删除source列表中的删除最后一个元素将其追加到destination列表LTRIM key start stop #根据索引start和stop保留列表元素 示例: hash操作 hash操作所有命令都以H开头。 Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。 Redis 中每个 hash 可以存储 232- 1 键值对(40多亿)。 常用: HDEL key field [field ...] #删除hash表中一个或多个字段HEXISTS key field #判断hash表中字段是否存在HGET key field #获取hash表中字段的值HGETALL key #获取hash表中所有字段HSET key field value # 设置hash表中字段的值HSETNX key field value #只有当字段不存在时候才设置hash表中字段值,HLEN key #获取hash表中字段个数HVALS key #获取hash表中所有字段的值HKEYS key #获取hash表中所有的字段HSTRLEN key field #获取hash表中指定字段的值的长度HMSET key field value [field value ...] #批量设置hash表中字段的值HMGET key field [field ...] #批量获取hash表中字段的值 示例: 集合set操作 Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。 Redis 中集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是 O(1)。 集合中最大的成员数为 232 - 1(4294967295, 每个集合可存储40多亿个成员)。 常用: SADD key member [member ...] #添加一个或多个元素到集合中SREM key member [member ...] #删除一个或多个集合中的元素SCARD key #获取集合中元素数量SMEMBERS key #返回集合中所有的元素SINTER key [key ...] #获取两个或两个以上集合的交集SUNION key [key ...] #获取两个或两个以上集合的并集SDIFF key [key ...] #获取两个或者两个以上集合的差集SISMEMBER key member #判断元素是否是在指定集合中SMOVE source destination member #移动一个集合中的元素到另一个集合SPOP key [count] #移除count个集合中元素,count可选参数,默认为1,即移除一个 有序集合操作 Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。 不同的是每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。 有序集合的成员是唯一的,但分数(score)却可以重复。 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。 集合中最大的成员数为 232 - 1(4294967295, 每个集合可存储40多亿个成员)。 常用: ZADD key [NX|XX] [CH] [INCR] score member [score member ...] #向一个有序集合添加成员(元素)#参数:#XX: 仅仅更新存在的成员,不添加新成员。#NX: 不更新存在的成员。只添加新成员。#CH: 修改返回值为发生变化的成员总数,原始是返回新添加成员的总数 (CH 是 changed 的意思)。更改的元素是新添加的成员,已经存在的成员更新分数。 所以在命令中指定的成员有相同的分数将不被计算在内。注:在通常情况下,ZADD返回值只计算新添加成员的数量。#INCR: 当ZADD指定这个选项时,成员的操作就等同ZINCRBY命令,对成员的分数进行递增操作。ZCARD key #获取有序集合中元素个数ZCOUNT key min max #指定分数范围的元素个数ZINCRBY key increment member #为有序集的元素的score值加上增加指定的incrementZRANGE key start stop [WITHSCORES] #根据有序集合中分数区间获取集合中的元素ZRANGE key start stop [WITHSCORES] #获取有序集合中元素的排名ZREM key member [member ...] #删除有序集合中一个或多个元素ZSCORE key member #设置元素在集合中的分数 GEO类型操作 Redis的GEO是 3.2 版本的新特性,对GEO(地理位置)的支持。这个功能可以将用户给定的地理位置信息储存起来, 并对这些信息进行操作。 geo类型命令不多,总共6个所以这里全部列举出来了。 GEOADD key longitude latitude member [longitude latitude member ...] #将指定的地理空间位置(纬度、经度、名称)添加到指定的key中GEODIST key member1 member2 [unit] #返回两个给定位置之间的距离。如果两个位置之间的其中一个不存在, 那么命令返回空值。指定单位的参数 unit 必须是以下单位的其中一个:#m 表示单位为米#km 表示单位为千米#mi 表示单位为英里#ft 表示单位为英尺GEOPOS key member [member ...] #从key里返回所有给定位置元素的位置(经度和纬度)GEOHASH key member [member ...] #返回一个或多个位置元素的 Geohash 表示。通常使用表示位置的元素使用不同的技术,使用Geohash位置52点整数编码。由于编码和解码过程中所使用的初始最小和最大坐标不同,编码的编码也不同于标准。此命令返回一个标准的GeohashGEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key] #以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。#范围可以使用以下其中一个单位:#m 表示单位为米。#km 表示单位为千米。#mi 表示单位为英里。#ft 表示单位为英尺。#在给定以下可选项时, 命令会返回额外的信息:#WITHDIST: 在返回位置元素的同时, 将位置元素与中心之间的距离也一并返回。 距离的单位和用户给定的范围单位保持一致。#WITHCOORD: 将位置元素的经度和维度也一并返回。#WITHHASH: 以 52 位有符号整数的形式, 返回位置元素经过原始 geohash 编码的有序集合分值。 这个选项主要用于底层应用或者调试, 实际中的作用并不大。#命令默认返回未排序的位置元素。 通过以下两个参数, 用户可以指定被返回位置元素的排序方式:#ASC: 根据中心的位置, 按照从近到远的方式返回位置元素。#DESC: 根据中心的位置, 按照从远到近的方式返回位置元素。#在默认情况下, GEORADIUS 命令会返回所有匹配的位置元素。 虽然用户可以使用 COUNT 选项去获取前 N 个匹配元素, 但是因为命令在内部可能会需要对所有被匹配的元素进行处理, 所以在对一个非常大的区域进行搜索时, 即使只使用 COUNT 选项去获取少量元素, 命令的执行速度也可能会非常慢。 但是从另一方面来说, 使用 COUNT 选项去减少需要返回的元素数量, 对于减少带宽来说仍然是非常有用的。#返回值: #在没有给定任何 WITH 选项的情况下, 命令只会返回一个像 ["New York","Milan","Paris"] 这样的线性(linear)列表。 #在指定了 WITHCOORD 、 WITHDIST 、 WITHHASH 等选项的情况下, 命令返回一个二层嵌套数组, 内层的每个子数组就表示一个元素 #在返回嵌套数组时, 子数组的第一个元素总是位置元素的名字。 至于额外的信息, 则会作为子数组的后续元素, 按照以下顺序被返回: #以浮点数格式返回的中心与位置元素之间的距离, 单位与用户指定范围时的单位一致。 #geohash 整数。 #由两个元素组成的坐标,分别为经度和纬度。GEORADIUSBYMEMBER key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]#这个命令和 GEORADIUS 命令一样, 都可以找出位于指定范围内的元素, 但是 GEORADIUSBYMEMBER 的中心点是由给定的位置元素决定的。 操作示例: 五、发布订阅 Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。 Redis 客户端可以订阅任意数量的频道。 下图代表其发布订阅之间的关系 运作原理 每个Redis 服务器进程都维持着一个表示服务器状态的 redis.h/redisServer结构, 结构的pubsub_channels 属性是一个字典, 这个字典就用于保存订阅频道的信息: struct redisServer { // ... dict *pubsub_channels; // ...}; 其中,字典的键为正在被订阅的频道, 而字典的值则是一个链表, 链表中保存了所有订阅这个频道的客户端。 比如说,在下图展示的这个pubsub_channels示例中,client1 、 client2 和 client3 就订阅了 channel1 , 而client3也同时订阅了channel2。 当客户端调用SUBSCRIBE命令时, 程序就将客户端和要订阅的频道在pubsub_channels字典中关联起来。 SUBSCRIBE命令的行为可以用伪代码表示如下: def SUBSCRIBE(client, channels): // 遍历所有输入频道 for channel in channels: // 将客户端添加到链表的末尾 redisServer.pubsub_channels[channel].append(client) 通过pubsub_channels字典, 程序只要检查某个频道是否为字典的键, 就可以知道该频道是否正在被客户端订阅; 只要取出某个键的值, 就可以得到所有订阅该频道的客户端的信息。 了解了pubsub_channels字典的结构之后, 解释PUBLISH命令的实现就非常简单了: 当调用PUBLISH channel message命令, 程序首先根据channel定位到字典的键, 然后将信息发送给字典值链表中的所有客户端。 订阅模式 redis的发布订阅不仅仅提供简单的订阅频道,还提供模式匹配订阅。模式订阅使用命令PSUBSCRIBE实现。 redisServer.pubsub_patterns属性是一个链表,链表中保存着所有和模式相关的信息: struct redisServer { // ... list *pubsub_patterns; // ...}; 链表中的每个节点都包含一个redis.h/pubsubPattern结构: typedef struct pubsubPattern { redisClient *client; robj *pattern;} pubsubPattern; client 属性保存着订阅模式的客户端,而 pattern 属性则保存着被订阅的模式。 每当调用 PSUBSCRIBE命令订阅一个模式时, 程序就创建一个包含客户端信息和被订阅模式的pubsubPattern结构, 并将该结构添加到redisServer.pubsub_patterns链表中。 作为例子,下图展示了一个包含两个模式的 pubsub_patterns 链表, 其中 client123 和 client256 都正在订阅 tweet.shop.* 模式: 通过遍历整个pubsub_patterns链表,程序可以检查所有正在被订阅的模式,以及订阅这些模式的客户端。 当执行PUBLISH进行命令向channel命令发送消息时,PUBLISH除了将message 发送到所有订阅channel的客户端之外, 它还会将channel和pubsub_patterns中的模式进行对比, 如果channel和某个模式匹配的话, 那么也将message 发送到订阅那个模式的客户端,例如一个客户端订阅了aa.bb.*频道,那么他会收到来自所有aa.bb开头的所有频道消息。 相关命令 PSUBSCRIBE pattern [pattern ...] #使用模式订阅一个或多个符合给定模式的频道PUNSUBSCRIBE [pattern [pattern ...]] #退订所有给定模式的频道SUBSCRIBE channel [channel ...] #订阅给定的一个或多个频道的信息UNSUBSCRIBE [channel [channel ...]] #指退订给定的频道PUBSUB subcommand [argument [argument ...]] #查看订阅与发布系统状态PUBLISH channel message #将信息发送到指定的频道 实践 在以下示例中,将分别用SUBSCRIBE命令订阅aa.bb和使用PSUBSCRIBE模式订阅频道aa.bb*。 SUBSCRIBE订阅:

PSUBSCRIBE subscription:

At this point, we use PUBSH to send a message to aa.bb and return the number of channels received, and both subscribers can receive the message.

Subscriber 1:

Pattern subscribers:

Summary

The subscription information is saved by the redisServer.pubsub_channels dictionary maintained by the server process, the key of the dictionary is the subscribed channel, and the value of the dictionary is all clients of the subscription channel. When a new message is sent to the channel, the program traverses all the clients corresponding to the channel (key) and then sends the message to the clients of all subscribed channels. The information of the subscription pattern is saved by the redisServer.pubsub_patterns linked list maintained by the server process. Each node of the linked list stores a pubsubPattern structure in which the subscribed pattern and the clients subscribing to the pattern are stored. The program traverses the linked list to find out whether a channel matches a pattern. When a new message is sent to the channel, in addition to the client that subscribes to the channel, all clients that subscribe to the pattern of the matching channel also receive the message. Unsubscribe channel and unsubscribe mode are the counter-operation of subscription channel and subscription mode respectively.

VI. Affairs

The so-called transaction should have the following special effects: Atomicity, Consistency, Isolation, Durability, ACID for short, but the transaction provided by redis is relatively simple, it realizes the transaction through MULTI, EXEC, DISCARD, WATCH and other commands.

However, Redis only supports simple transactions and puts execution commands into the queue cache. When there is an exception or command error in the program, DISCARD clears the cache queue and does not execute commands in the queue. The transaction process has the following characteristics:

A transaction is a separate isolation operation: all commands in the transaction are serialized and executed sequentially. In the course of execution, the transaction will not be interrupted by command requests sent by other clients. A transaction is a pan-atomic operation (I call it pan-atomic here, and in some cases the transaction of redis is not atomic, as I will explain later): either all or none of the commands in the transaction are executed.

The EXEC command is responsible for triggering and executing all commands in the transaction:

If the client starts a transaction using MULTI but fails to execute EXEC because of a disconnection, then all commands in the transaction will not be executed. On the other hand, if the client succeeds in executing EXEC after opening the transaction, all commands in the transaction will be executed.

In particular, the pan-atomic operations in the text are explained:

After the redis starts the transaction, if the execution command has a displayed error or the client interrupts, the transaction will call DISCARD to empty the cache queue and not execute all the tasks in the queue when executing the EXEC command, which is atomic. When a command is executed, the command does not show an error (for example, the LSET operation sets a non-existent list), but an error occurs when a command is called by EXEC, then commands that have been executed before will not be rolled back, so strictly speaking, redis does not support atomicity.

Involved in command

MULTI # marks the beginning of the transaction block. Redis queues subsequent commands one by one before you can use the EXEC command to execute commands in the cache queue. EXEC # executes the command DISCARD # in the cache queue to clear all commands that were previously queued in a transaction, and then returns to the normal connection state. If the WATCH command is used, the DISCARD command unmonitors all keys currently monitored by the connection. WATCH key [key.] # when a transaction needs to be executed conditionally, use this command to set the given key to the monitored UNWATCH # to clear all keys previously monitored by a transaction. If you call the EXEC or DISCARD command, you do not need to call the UNWATCH command manually

Optimistic locking mechanism

Optimistic lock: always think that there will be no concurrency problem, every time you go to get the data, you always think that there will be no other threads to modify the data, so it will not be locked, but when you update it, you will judge whether other threads have modified the data before that. Generally, you will use the version number mechanism or check-and-set (CAS) operation to achieve.

Redis implements optimistic locking through the WATCH command, and keys as parameters of the WATCH command are monitored by Redis, and Redis can detect their changes. Before executing the EXEC command, if Redis detects that at least one key has been modified, the entire transaction is aborted, and the EXEC command returns a Nil value to remind the user that the transaction failed.

Note: the WATCH command needs to be executed before MULTI, otherwise redis will put one of its commands in the cache queue.

Example: in the following example, the transaction monitoring name key is enabled through one client, and the other client modifies the name key before executing EXEC. This transaction will not be executed and nil will be returned, as shown below.

Atomicity practice

Some simple practices have been done to demonstrate that redis will not support atomicity in a strict sense.

As can be seen from the above results, the name value is Rose before the transaction is opened, and the SET command and LSET command are executed successively before the transaction is started, but the LSET command is incorrect. When we call EXEC to execute the transaction, we can see that the SET command in the transaction has taken effect and has not been rolled back. Because the command does not show an error in this process, it can be said that the redis transaction does not support atomicity.

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 255

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report