当前位置:网站首页>Redis - Basic operations and usage scenarios of String|Hash|List|Set|Zset data types

Redis - Basic operations and usage scenarios of String|Hash|List|Set|Zset data types

2022-08-10 03:20:00 Don't stay up late hahaha~

redisCommand of refer:http://doc.redisfans.com/index.html

1. Redis基本操作

1. 启动redisService and connectredis客户端

// 启动redis服务
[root@node1 etc]# redis-server /etc/redis.conf

// 连接redis客户端,指定服务器,端口,密码
[root@node1 etc]# cat ~/.passwd/local_redis_passwd
d9be7d760e129d02 
[root@node1 etc]# redis-cli -h localhost -p 6379 -a d9be7d760e129d02

// 测试是否连接成功
localhost:6379> ping
PONG
localhost:6379>

2. 切换数据库

RedisSingle server there are16(0~15)个数据库,And can't be Shared data between each database.After login the default selectiondb0.To switch the database,可以使用如下命令:

localhost:6379> select 1
OK
localhost:6379[1]> set username zhangsan
OK
localhost:6379[1]> get username
"zhangsan"
localhost:6379[1]>

3. 删除键

If you want to delete unwanted keys in business,可以使用del命令:

localhost:6379[1]> del username
(integer) 1
localhost:6379[1]>

4. 删除当前数据库的所有键

Want to delete the current database of all keys,可以执行flushdb命令:

localhost:6379[1]> set username lisi
OK
localhost:6379[1]> flushdb
OK
localhost:6379[1]>

5. For a given key set expiration time

为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除.

EXPIRE key seconds

localhost:6379> set user_id 1
OK
localhost:6379> expire user_id 20
(integer) 1
localhost:6379> ttl user_id
(integer) 14
localhost:6379> get user_id
"1"
localhost:6379>

2. String类型的使用场景

1. String数据类型的API

1、Set and obtain the content of the key

localhost:6379[1]> set user zhangsan
OK
localhost:6379[1]> get user
"zhangsan"

2、As the key to set new contents and returns the old value

localhost:6379[1]> keys *
(empty list or set)
localhost:6379[1]> set user zhangsan
OK
localhost:6379[1]> get user
"zhangsan"
localhost:6379[1]> getset user lisi
"zhangsan"
localhost:6379[1]> get user
"lisi"
localhost:6379[1]>

3、设置key的过期时间,以秒为时间单位

将值 value 关联到 key ,并将 key 的生存时间设为 seconds (以秒为单位).如果 key 已经存在, SETEX 命令将覆写旧值. SETEX 是一个原子性(atomic)操作,关联值和设置生存时间两个动作会在同一时间内完成,该命令在 Redis 用作缓存时,非常实用.

SETEX key seconds value

localhost:6379[1]> setex cache_user 60 zhangsan
OK
localhost:6379[1]> ttl cache_user
(integer) 53
localhost:6379[1]> setex cache_user 60 lisi
OK
localhost:6379[1]> ttl cache_user
(integer) 55
localhost:6379[1]>

4、设置key的过期时间,以毫秒为时间单位

这个命令和 SETEX 命令相似,但它以毫秒为单位设置 key 的生存时间,而不是像 SETEX 命令那样,以秒为单位.

PSETEX key milliseconds value

localhost:6379[1]> psetex cache_user 10000 "haha"
OK
localhost:6379[1]> get cache_user
"haha"
localhost:6379[1]> pttl cache_user
(integer) 2206
localhost:6379[1]> pttl cache_user
(integer) -2
localhost:6379[1]> get cache_user
(nil)
localhost:6379[1]>

5、设置key的过期时间,以毫秒为时间单位

SETNX key value

key 的值设为 value ,当且仅当 key 不存在.若给定的 key 已经存在,则 SETNX 不做任何动作.

localhost:6379> setnx user_id 1
(integer) 1
localhost:6379> setnx user_id 1
(integer) 0

设置值得同时设置过期时间

localhost:6379>  set product_id true ex 20 nx
OK
localhost:6379>  set product_id true ex 20 nx
(nil)

2. A single value cache

The authentication centertoken缓存:

1)The first request service node to generate a usertoken,并存储到Redis服务器,Then you can according to need to set up the corresponding expiration time,从而保证tokenAfter the expiration information fromRedis服务器移除.如果有需要,也可以不设置tokenIn memory to store the expiration date of the.

2)After the request node need only throughgetCommand from the cache to gettoken验证合法性

localhost:6379[1]> psetex cache_userid 10000 "userinfo token"
OK
localhost:6379[1]> get cache_userid
"userinfo token"
localhost:6379[1]> pttl cache_userid
(integer) 3110
localhost:6379[1]> pttl cache_userid
(integer) 523
localhost:6379[1]> pttl cache_userid
(integer) -2
localhost:6379[1]> get cache_userid
(nil)
localhost:6379[1]>

3. 对象缓存

The user information can be a simple string is,May also be an object or high frequency to visit but rarely modified data,The data can be taken as a whole object,If you want to release the pressure of the database access,So it can be object tojsonSerialized cached.This data can be used in aString数据类型进行存储.

localhost:6379[1]> set user_i "{'name':'zhagnsan','age':1}"
OK
localhost:6379[1]> get user
"lisi"
localhost:6379[1]>

4. 计数器

在高并发的业务场景中,May encounter a variety of business scenarios,比如接口限流.In a double tenth or other large festival,Business server resources are limited,但是在高并发的场景下,Too many requests may lead to problems such as server goes down,So will the interface request to do some restrictions,Such as limit the total number of requests per second for200次,超过200Time is waiting for,Wait a second request again,这里用RedisAs a counter mode to realize.

实现流程如下:

1)First after received the request to set up a key,然后自增1,如果不存在,Value will be initialized to0.

incr mykey

这里的mykey可能需要特殊处理,It is according to the SEC,So when the interface after getting a request,Should get the current time to generate dynamic key,如20200101235959:mykey.

2)When the interface after request,执行incr yyyyMMddHHmmss:mykey,If return the result is less than200则进行处理,超过200Will wait for the next second processing.

3)Because every second, generates a key,为了节省内存空间,May need to be a regular task,Regularly delete these have used key.

localhost:6379[1]> incr 202208091101:mykey
(integer) 1
localhost:6379[1]> incr 202208091101:mykey
(integer) 2
localhost:6379[1]> incr 202208091101:mykey

5. Only the increase ofID或者流水号

在有些业务中,In order to improve the literacy of the database,Will likely be a library according to the business split into multiple small library、Will be a big table split into several small table,比如user01表、user02表,But also to ensure that the two tables in theIDIs the global unification since the increase of,So database table to carry on the attribute cannot be use.

At this time also can useRedis的String数据类型实现自增,In the new data row,通过调用RedisService on the function to generate a since of numerical implementation more only on the table.

假设目前有2台单独的Redis服务器,Then generated way is such a,第1Server from the initial value1Begin to generate serial Numbers :

localhost:6379> incrby id 1
(integer) 1
localhost:6379> incrby id 2
(integer) 3
localhost:6379> incrby id 2
(integer) 5
localhost:6379>

第2Server from the initial value2Begin to generate serial Numbers :

localhost:6379> incrby id 2
(integer) 2
localhost:6379> incrby id 2
(integer) 4
localhost:6379> incrby id 2
(integer) 6
localhost:6379>

Each server from the initial value1~2开始,Then every time accumulative value2,Multiple nodes generated from the serial number of the increase and not repeat.

以上只是利用Redis的自增APIHandle multiple tables only since the increaseIDAnd an additional one option.If they understand snowflakes algorithm or other more simple way,Is there is no need to useRedis的这种操作.

6. Article count or web browsing reading statistics

当我们打开浏览器时,Will face a variety of web information,Such as technology blogs or news blogs, etc,These web pages is filled with various statistical number,Such as the user's total number of thumb up、关注数、粉丝数、Post comments、热度、The article reading and collection, etc.To implement these requirements and want to reduce the pressure of the database,And the data of effectiveness when writing articles and the frequency of demanding,则完全可以使用Redis.

Implement article reading quantity statistics need to perform the following commands:

localhost:6379> incr read:count
(integer) 1
localhost:6379> get read:count
"1"
localhost:6379> incr read:count
(integer) 2

7. 分布式锁

With the development of Internet business and demand changing,Applications from monomer architecture evolved to the present distributed and micro service architecture.When using monomer architecture,Multithreaded operations is preempted by thread lock resources control,But in a distributed system need to use other means to achieve,可以借助于Redis中的setnx命令来完成.

具体操作流程如下:If the key has no value to new success,Means to lock the,否则失败.By the time the operation is successful releases the lock,也就是删除键.

// 给 product_id设置值,If the value does not exist before,The new success,返回1,抢到了锁

localhost:6379> setnx product_id true
(integer) 1

// When other threads to execute this command,返回0,获取锁失败

localhost:6379> setnx product_id true
(integer) 0

// When the first get the lock after threads to execute the business,You can delete button,Let other threads to lock

localhost:6379> del product_id
(integer) 1

// Other threads to rob lock success

localhost:6379> setnx product_id true
(integer) 1
localhost:6379>

Which there is a problem:If after the first thread to lock haven't delete key this thread is down,Will result in the permanent lock occupied,The business will not be able to perform other threads.对于这个问题,Can set the expiration time through to the key to solve the,Arrived after the expiration time forRedisService automatically delete this key——释放.

// 抢到锁

localhost:6379> setnx product_id true
(integer) 1

// 设置过期时间20毫秒,Expired keys will be removed

localhost:6379> expire product_id 20
(integer) 1

// Query key and long overdue,值为负数时,The key has expired to be deleted

localhost:6379> ttl product_id
(integer) -2

// 键已经被删除

localhost:6379> get product_id
(nil)
localhost:6379>

The above assignment and set expiration time is divided into two steps.如果要保证原子性,You can at the time of setting values to set the expiration time again:

localhost:6379> set product_id true ex 20 nx
OK
localhost:6379> ttl product_id
(integer) 17
localhost:6379> get product_id
"true"
localhost:6379> ttl product_id
(integer) 10
localhost:6379> ttl product_id
(integer) 3
localhost:6379>

3. Hash类型的使用场景

在Redis中,Hash data type refers toRedis键值对中的值本身又是一个键值对结构.

1. HashThe data type of normal operation

1、Set and get the specifiedkey的值

HSET key field value

将哈希表 key 中的域 field 的值设为 value .如果 key 不存在,一个新的哈希表被创建并进行 HSET 操作.如果域 field 已经存在于哈希表中,旧值将被覆盖.

HGET key field

返回哈希表 key 中给定域 field 的值.

// 如果 `field` 是哈希表中的一个新建域,并且值设置成功,返回 `1` .
localhost:6379> hset user name zhangsan
(integer) 1
localhost:6379> hset user age 18
(integer) 1
localhost:6379> hget user name
"zhangsan"
localhost:6379> hget user age
"18"
    
// 如果哈希表中 `field` 已经存在且旧值已被新值覆盖,返回 `0` .
localhost:6379> hset user name list
(integer) 0
localhost:6379> hset user age 19
(integer) 0
localhost:6379>

2、返回哈希表 key 中,所有的域和值

返回哈希表 key 中,所有的域和值.在返回值里,Follow after each domain is the domain of value,所以返回值的长度是哈希表大小的两倍.

localhost:6379> hset user name zhangsan
(integer) 1
localhost:6379> hset user age 19
(integer) 1
localhost:6379> hgetall user
1) "name"          // field
2) "zhangsan"      // value
3) "age"           // field
4) "19"            // value
localhost:6379> hset user name lisi
(integer) 0
localhost:6379> hset user age 19
(integer) 0
localhost:6379> hgetall user
1) "name"
2) "lisi"
3) "age"
4) "19"
localhost:6379>

3、为哈希表 key 中的域 field 的值加上增量 increment

HINCRBY key field increment

为哈希表 key 中的域 field 的值加上增量 increment .增量也可以为负数,相当于对给定域进行减法操作.如果 key 不存在,一个新的哈希表被创建并执行 HINCRBY 命令.如果域 field 不存在,那么在执行命令前,域的值被初始化为 0 .

localhost:6379> hexists counter page_view
(integer) 0
localhost:6379> hincrby counter page_view 1
(integer) 1
localhost:6379> hget counter page_view
"1"
localhost:6379> hincrby counter page_view -50
(integer) -49
localhost:6379>

2. 实现购物车

购物车的定义非常简单:For each useruserid作为Redis的键(Key),每个用户的购物车都是一个哈希表,It stores the goodsIDThe mapping relationship between goods and order quantities.在商品的订购数量出现变化时,操作Redis哈希对购物车进行更新.

如果用户订购某件商品的数量大于0,那么程序会将这件商品的IDAnd the number of users to order the goods add to theHash中.

localhost:6379> hset userId:1 productId:1 1
(integer) 1
localhost:6379> hgetall userId:1
1) "productId:1"
2) "1"

Goods purchased if the user already exists in the hash table,那么新的订购数量会覆盖已有的订购数量.

localhost:6379> hset userId:1 productId:1 5
(integer) 0
localhost:6379> hgetall userId:1
1) "productId:1"
2) "5"

If the user purchase quantity is not more than0,The program will be deleted from the hash table the.

localhost:6379> hdel userId:1 productId:1
(integer) 1
localhost:6379> hgetall userId:1
(empty list or set)

3. 作为计数器

Redis中的StringData types can be used as a counter,实际上Redis的HashIt is also very widely used as a counter,It is often used to record the website a day、一月、一年的访问数量.每次访问,在对应的field上自增1即可.

Blog posts record monthly traffic command:

localhost:6379> hincrby mylog 202208 1
(integer) 1
localhost:6379> hincrby mylog 202208 1
(integer) 2
localhost:6379> hincrby mylog 202208 1
(integer) 3

Record commodity number of praise、The number of bad review command:

localhost:6379> hincrby good productId 1
(integer) 1
localhost:6379> hincrby good productId 1
(integer) 2
localhost:6379> hincrby bad productId 1
(integer) 1

The number of records website real-time online orders:

localhost:6379> hincrby mysite 202208 1
(integer) 1
localhost:6379> hincrby mysite 202208 1
(integer) 2

4. List类型的使用场景

Redis的ListData types are realized through the list.This means that even if the user millions of elements in the list,The new element is added to the beginning or end of the list of operation will be performed in a fixed time.使用LPUSHCommand to add new elements to have100Element of the list at the beginning of speed and add elements to the1000The list at the beginning of an element at the same speed.

在使用ArrayImplementation of the list,按索引访问元素的速度非常快,And in the list by list access speed is not so fast,Redis的ListData types are realized through the list,Because for a database system,It is essential to a very fast way to add elements to the long list.We can use two different ways to manipulate the list:The first is a queue,In accordance with the first-in, first-out sequence of operation;The second is the stack,In accordance with the order of the advanced after the operation.

1. List数据类型的基本操作

1、LPUSH Add elements to the list head

LPUSH key value [value …]

将一个或多个值 value 插入到列表 key 的表头.如果有多个 value 值,那么各个 value 值按从左到右的顺序依次插入到表头: 比如说,对空列表 mylist 执行命令 LPUSH mylist a b c ,列表的值将是 c b a ,这等同于原子性地执行 LPUSH mylist aLPUSH mylist bLPUSH mylist c 三个命令.如果 key 不存在,一个空列表会被创建并执行 LPUSH 操作.

2、LPOP 移除并返回列表 key 的头元素

LPOP key

移除并返回列表 key 的头元素,当 key 不存在时,返回 nil .

3、LRANGE 返回列表 key 中指定区间内的元素

LRANGE key start stop

返回列表 key 中指定区间内的元素,区间以偏移量 startstop 指定.下标(index)参数 startstop 都以 0 为底,也就是说,以 0 表示列表的第一个元素,以 1 表示列表的第二个元素,以此类推.你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推.

// A single element is added to the list of head
localhost:6379> lpush user zhangsan
(integer) 1
localhost:6379> lpush user lisi
(integer) 2

// 添加重复元素,列表允许重复元素
localhost:6379> lpush user lisi
(integer) 3
    
// Returns a list of all the elements in the
localhost:6379> lrange user 0 -1
1) "lisi"
2) "lisi"
3) "zhangsan"

// Remove the head element of the list
localhost:6379> lpop user
"lisi"
localhost:6379> lrange user 0 -1
1) "lisi"
2) "zhangsan"
    
// Add more elements to the list of head
localhost:6379> lpush user wangwu zhaoliu
(integer) 4
localhost:6379> lrange 0 -1
(error) ERR wrong number of arguments for 'lrange' command
localhost:6379> lrange user 0 -1
1) "zhaoliu"
2) "wangwu"
3) "lisi"
4) "zhangsan"

2. List模拟数据结构

ListData type has the following features:

1)List中的元素是有序的,Could be obtained by the subscript an element or a range of elements in the list.

2)List中的元素可以是重复的.

3)Can realize operation sequence in line and cut in line.

1、用Redis的ListSimulation data type stack

用Redis的ListSimulation data type stack data structure to realize advanced after the operation,执行命令如下:

localhost:6379> lpush mystack a
(integer) 1
localhost:6379> lpush mystack b
(integer) 2
localhost:6379> lpush mystack c
(integer) 3
localhost:6379> lpush mystack d e f
(integer) 6
localhost:6379> lrange mystack 0 2
1) "f"
2) "e"
3) "d"
localhost:6379> lrange mystack 0 -1
1) "f"
2) "e"
3) "d"
4) "c"
5) "b"
6) "a"
localhost:6379> lpop mystack
"f"

2、Redis的ListData type simulation queue

用Redis的ListData type simulation queue data structure to implement the operation of the first in first out,执行命令如下:

localhost:6379> lpush myqueue a
(integer) 1
localhost:6379> lpush myqueue b
(integer) 2
localhost:6379> lpush myqueue c d e
(integer) 5
localhost:6379> lrange myqueue 0 -1
1) "e"
2) "d"
3) "c"
4) "b"
5) "a"
localhost:6379> rpop myqueue
"a"
localhost:6379> lrange myqueue 0 -1
1) "e"
2) "d"
3) "c"
4) "b"

3、阻塞队列

RedisThe list also has a special function,Make it suitable for implementation queue,Usually used for interprocess communication system building blocks:阻止操作.

1)Push the items into the list,生产者调用lpush命令.

2)To extract the data items from the list,消费者调用rpop.有时列表可能为空,No any item of data to be processed,此时rpop就返回null.在这种情况下,消费者被迫等待一段时间,然后使用rpop重试,这称为轮询.But it will have a disadvantage:强制Redis和客户端处理无用的命令.Because consumer processing end after receivingnull之后会等待一段时间,So would increase the delay of processing data items.为了减小延迟,我们可以在两次调用rpop之间等待更少的时间,即对RedisThe call is becoming more and more useless.

按照先进先出的顺序,If the list no elements are waiting for,执行命令如下:

localhost:6379> lpush mymq a
(integer) 1
localhost:6379> lpush mymq b
(integer) 2
localhost:6379> lpush mymq c
(integer) 3
localhost:6379> lrange mymq 0 -1
1) "c"
2) "b"
3) "a"
    
// By blocking the way to obtain element,If no element to wait,直到有元素为止
// 5For there is no element waiting time
localhost:6379> brpop mymq 5
1) "mymq"
2) "a"
localhost:6379> brpop mymq 5
1) "mymq"
2) "b"
localhost:6379> brpop mymq 5
1) "mymq"
2) "c"
localhost:6379> brpop mymq 5
(nil)
(5.33s)  // 等待时间

5. Set类型的使用场景

集合元素无序且唯一.因为是无序的,So it couldn't have carried out in accordance with the order of elements inserted storage.集合类型和列表类型的区别如下:

1)列表可以存储重复元素,集合默认去重.

2)Stored in order list,And collection is disorderly storage.

3)List and collection support、删、改、查,And the intersection of multiple sets of collection also support、并集、差集.

1. Set数据类型的基本操作

1、添加元素到集合

SADD key member [member …]

将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略.假如 key 不存在,则创建一个只包含 member 元素作成员的集合.返回被添加到集合中的新元素的数量,不包括被忽略的元素.

2、返回集合 key 中的所有成员

返回集合 key 中的所有成员,不存在的 key 被视为空集合.

SMEMBERS key

3、返回集合中的一个随机元素

SRANDMEMBER key [count]

如果命令执行时,只提供了 key 参数,那么返回集合中的一个随机元素.

从 Redis 2.6 版本开始, SRANDMEMBER命令接受可选的 count 参数:

如果 count 为正数,且小于集合基数,那么命令返回一个包含 count 个元素的数组,数组中的元素各不相同.如果 count 大于等于集合基数,那么返回整个集合.如果 count 为负数,那么命令返回一个数组,数组中的元素可能会重复出现多次,而数组的长度为 count 的绝对值.

该操作和 SPOP相似,但 SPOP将随机元素从集合中移除并返回,而SRANDMEMBER则仅仅返回随机元素,而不对集合进行任何改动.

// A single element is added to the collection 
localhost:6379> sadd member a
(integer) 1
localhost:6379> sadd member b
(integer) 1
localhost:6379> sadd member c
(integer) 1

// Add more elements to the set
localhost:6379> sadd member d e f
(integer) 3
localhost:6379> sadd member f
(integer) 0

// 返回集合 key 中的所有成员
localhost:6379> smembers member
1) "c"
2) "b"
3) "d"
4) "f"
5) "e"
6) "a"

// 返回集合中的一个随机元素
localhost:6379> srandmember member
"d"
localhost:6379> srandmember member
"f"

4、移除集合 key 中的一个或多个 member 元素

SREM key member [member …]

移除集合 key 中的一个或多个 member 元素,不存在的 member 元素会被忽略.

localhost:6379[15]> sadd user user1 user2 user3 user4 user5
(integer) 5

// Remove a single element of the set
localhost:6379[15]> srem user user1
(integer) 1

// Remove multiple elements of the set
localhost:6379[15]> srem user user2 user3
(integer) 2

// 获取集合中的所有元素
localhost:6379[15]> smembers user
1) "user4"
2) "user5"

1. 微博瘫痪

当出现xxx明星和xxxEvent of gossip,Stress may cause server,导致服务器宕机.Down most of the reason is that many people at the same time pay attention to and view a hot news or gossip,Too much for the hot spot of thumb up or comment would lead to concurrency issues.If the thumb up and comments cache is used to solve,Then don't regularly brush cached data in the database,So will be able to improve performance.

2. 抽奖逻辑

For a user can draw many raffle prizes,则可以执行如下命令:

// To set into all lottery information
localhost:6379> sadd luckuser user1
(integer) 1
localhost:6379> sadd luckuser user2
(integer) 1
localhost:6379> sadd luckuser user3 user4 user5
(integer) 3

// Who, for a collection of all
localhost:6379> smembers luckuser
1) "user4"
2) "user2"
3) "user1"
4) "user3"
5) "user5"

// Randomly chosen one,Finished not to delete personnel information
localhost:6379> srandmember luckuser
"user1"
localhost:6379> srandmember luckuser
"user4"

// Verify personnel information is deleted after finished
localhost:6379> smembers luckuser
1) "user3"
2) "user4"
3) "user1"
4) "user2"
5) "user5"

For a user can only smoke a raffle prizes,则可以执行如下命令:

localhost:6379[15]> sadd luckuser user1 user2 user3 user4 user5
(integer) 5

// Randomly chosen one,Finished deleting personnel information,不允许重复抽奖
localhost:6379[15]> spop luckuser
"user4"
localhost:6379[15]> spop luckuser
"user3"

// Verify personnel information is deleted after finished
localhost:6379[15]> smembers luckuser
1) "user1"
2) "user2"
3) "user5"

3. The article thumb up or vote

In the circle of friends often get links from relatives and friends,For help in thumb up and vote.In terms of voting,如果根据用户ID或者IPAddress to restrict,那么一个IPAddress or a userIDFor one vote only for an information.Set the data type can embody its characteristics,Automatically to heavy.Is the same for the thumb up application.

Thumb up or vote can perform the following operation command:

// 用户点赞
localhost:6379[15]> sadd like:id1 ip1
(integer) 1
localhost:6379[15]> sadd like:id1 ip2
(integer) 1
localhost:6379[15]> sadd like:id1 ip3
(integer) 1
// Repeat the thumb up will fail and return0
localhost:6379[15]> sadd like:id1 ip3
(integer) 0
// 取消点赞
localhost:6379[15]> srem like:id1 ip1
(integer) 1
// Number of thumb up to see all
localhost:6379[15]> smembers like:id1
1) "ip2"
2) "ip3"

4. Mutual friend statistics

localhost:6379[15]> flushdb
OK

// 给zhangsan添加好友friend1、friend2、friend3、friend4 
localhost:6379[15]> sadd zhangsan friend1
(integer) 1
localhost:6379[15]> sadd zhangsan friend2
(integer) 1
localhost:6379[15]> sadd zhangsan friend3
(integer) 1
localhost:6379[15]> sadd zhangsan friend4
(integer) 1

// 给lisi添加好友friend1、friend2、friend5、friend6
localhost:6379[15]> sadd lisi friend1
(integer) 1
localhost:6379[15]> sadd lisi friend2
(integer) 1
localhost:6379[15]> sadd lisi friend5
(integer) 1
localhost:6379[15]> sadd lisi friend6
(integer) 1

// zhangsan和lisi的共同好友
localhost:6379[15]> sinter zhangsan lisi
1) "friend2"
2) "friend1"

// zhangsanMay recognize reallisi的好友
localhost:6379[15]> sdiff lisi zhangsan
1) "friend6"
2) "friend5"

// lisi可能认识zhangsan的好友
localhost:6379[15]> sdiff zhangsan lisi
1) "friend3"
2) "friend4"

// zhangsan和lisi的所有好友
localhost:6379[15]> sunion zhangsan lisi
1) "friend4"
2) "friend2"
3) "friend1"
4) "friend3"
5) "friend6"
6) "friend5"

6. Zset类型的使用场景

有序集(Zset)类型是Redis中一个非常重要的数据类型,Similar to the collection type and hash types between the compound type.像Set集合一样,ZsetOrdered set by the only、Not to repeat a set of elements of,In a sense is a collection of.

虽然ZsetThe elements within the no sorting,But after sorting all elements in the collection that is associated with what is referred to as a floating point value to score.

1. Zset基本操作

1、The elements and their score 值加入到有序集 key 当中

ZADD key score member [[score member] [score member] …]

将一个或多个 member 元素及其 score 值加入到有序集 key 当中.如果某个 member 已经是有序集的成员,那么更新这个 memberscore 值,并通过重新插入这个 member 元素,来保证该 member 在正确的位置上.

2、返回有序集 key 中,指定区间内的成员

ZRANGE key start stop [WITHSCORES]

返回有序集 key 中,指定区间内的成员.其中成员的位置按 score 值递增(从小到大)来排序.具有相同 score 值的成员按字典序来排列.如果你需要成员按 score 值递减(从大到小)来排列,请使用ZREVRANGE 命令.

下标参数 startstop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推.也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推.

// 添加单个元素
127.0.0.1:6379> zadd page_range 10 goole.com
(integer) 1

// 添加多个元素
127.0.0.1:6379> zadd page_range 9 baidu.com 8 csdn.com
(integer) 2

// 显示整个有序集成员
127.0.0.1:6379> zrange page_range 0 -1 withscores
1) "csdn.com"
2) "8"
3) "baidu.com"
4) "9"
5) "goole.com"
6) "10"

// 显示有序集下标区间 1 至 2 的成员
127.0.0.1:6379> zrange page_range 1 2 withscores
1) "baidu.com"
2) "9"
3) "goole.com"
4) "10"

2. 利用Zset实现限流

The service is becoming more and more popular,缓存、降级和限流是保护微服务系统运行稳定性的三大利器.The purpose of cache is to promote system access speed and increase the processing capacity of,Problems and relegation is when the service or affect the performance of the core processes need to temporarily blocked off,待高峰或者问题解决后再打开.Some of the scenes can not use the cache and relegated to solve,比如稀缺资源、数据库的写操作、频繁的复杂查询,因此需有一种手段来限制这些场景的请求量,这就是限流.Redis的ZsetType of structure can realize current limiting function.

3. 新闻排行榜

Baidu hot list may be we often see,For so large amount of data, and the ranking of high real time,With the traditional database to realize the poor performance.下面我们使用Redis中的ZsetData types to simulate.

127.0.0.1:6379> zadd news 10 newId1
(integer) 1
127.0.0.1:6379> zadd news 20 newId2
(integer) 1
127.0.0.1:6379> zadd news 30 newId3
(integer) 1
127.0.0.1:6379> zrange news 0 10 withscores
1) "newId1"
2) "10"
3) "newId2"
4) "20"
5) "newId3"
6) "30"

4. Live exceptional ranking

// For fans of exceptional value scores as elements in the collection
127.0.0.1:6379> zadd anchor 10  fans1
(integer) 1
127.0.0.1:6379> zadd anchor 20 fans2
(integer) 1
127.0.0.1:6379> zadd anchor 30 fans3
(integer) 1
// According to the exceptional value ranking order of fan output fan information
127.0.0.1:6379> zrange anchor 0 -1
1) "fans1"
2) "fans2"
3) "fans3"
// According to the amount of exceptional fans ranking reverse output fan information
127.0.0.1:6379> zrevrange anchor 0 -1
1) "fans3"
2) "fans2"
3) "fans1"
// Fan output information and amount all
127.0.0.1:6379> zrange anchor 0 -1 withscores
1) "fans1"
2) "10"
3) "fans2"
4) "20"
5) "fans3"
6) "30"
原网站

版权声明
本文为[Don't stay up late hahaha~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208100154328335.html