Home  >  Article  >  Database  >  Organize some common Redis data structures (summary)

Organize some common Redis data structures (summary)

青灯夜游
青灯夜游forward
2021-12-06 09:57:042261browse

This article will share with you some common Redis data structures, as well as some common instructions. I hope it will be helpful to you!

Organize some common Redis data structures (summary)

#What is a data structure?

Those who have a Java background should know some commonly used data structures, such as arrays, queues, stacks, etc... So what is the difference between Redis's data structure and Java's data structure? The answer is yes. If some friends know about Map, they know that there is a Key value and a Value value in the Map. The data structure of Redis is also like this.

Redis data structure: String, List, Hash, and Set all have a Key value and a Value value.

Key value is the name, Value value is the data. These two are bound together, and a Key value corresponds to a Value value. We call this a key-value pair. [Related recommendations: Redis video tutorial]

Commonly used basic commands in Redis

In Redis, different commands are used in different scenarios. Order. But not every command needs to be remembered? No, you just need to be familiar with the most commonly used commands. If you need to use some less commonly used commands, you can check the official documentation. Here are some commonly used commands in Redis.

1.# exists(判断key值是否存在):如果存在返回1,反之返回0
  例子: exists name(name为key)

2.# del(删除key): 删除成功返回1,反之返回0

3.# type(判断key的类型)

4.ttl(查看key存活时间

If you want to learn more commands, you can go to the Chinese documentation to query: http://www.redis.cn/

Introduction and usage scenarios of the String type

String The string type is the most basic data type in Redis. It has a wide range of application scenarios in Redis. One key corresponds to one value.

Redis's String is a dynamic string and a modifiable string. Its internal structure is similar to Java's ArrayList, which uses pre-allocated redundant space to reduce memory allocation.

The String type is binary safe, which means that Redis String can contain any data. Such as: numbers, strings, pictures, etc.

String type application scenarios: verification codes, counters, repeated order submissions, user login information, product details

Common use of String Command

1.# set/get 设置和获取key-value 注意中间一定要加空格
  例子: set xxx(key) xxx(value) 
         get xxx(key)
         
2.# mget/mset 批量设置或获取多个key的值
     mset user:name jack user:age 2
     mget user:name user:age
     
3.# incr incr对key对应的值进行加1操作,并返回新的值
    incr video:uv:1 
     
4. # incrby 将key对应的数字加increment.如果key不存在,操作之前,key就会被置为0
    incrby video:uv:1 10
    
5.# setex 设置key对应字符串value,并且设置key在给定的seconds时间之后超时过期操作
    setex code 20 778899 (设置一个key为code value为778899 20秒后过期)4

6. # setnx 将key设置值为value,如果存在该key那么什么都不做,如果不存在key那么等同于set命令
   setnx name xdclass.net
 
7. # getset 设置key的值,并返回key旧的值
    get name uuuuu (这时会返回xdclass.net,重新在get一下会获得重新设置的值uuuuu)

Note: The length of the value cannot exceed 512MB, follow the key naming convention: Business name: Indicate: ID (not too long, separate with colon)

The internal structure of String (the internal structure is for in-depth exploration)

Redis does not use the traditional string representation of the C language, but builds a simple dynamic character called Abstract type of string (SDS). Why does Redis use its own built SDS instead of directly using String in C language? The reason is actually very simple, it is to improve the performance of Redis operations.

What are the advantages of SDS strings and C language strings?

  • Constant complexity Obtaining the string length: If C language wants to obtain the length, it must traverse the entire string. The time complexity of SDS obtaining the SDS string length through the len attribute has changed from O(N) to O(1), ensuring that obtaining the string length will not become a performance bottleneck for Redis.

  • Reduce the number of memory reallocations caused by modifications: Memory reallocation means that when modifying a string, due to insufficient or excessive memory space, the execution memory needs to be reallocated. Operation, because this operation involves memory, it results in high time cost, so we should try to avoid memory reallocation. In SDS, there are two attributes, len and free, and optimization strategies can be used to reduce the number of memory reallocations.

Introduction and usage scenarios of the List type

The List type is simply a linked list,After inserting elements, it is Arranged in an orderly manner, the value can be repeated. The corresponding value can be obtained through the corresponding subscript. Data can be inserted and deleted on both sides of the linked list. During insertion, if the key does not exist, Redis will create a new linked list for the key. In contrast, if all elements in the linked list are deleted, the key will also be deleted.

Application scenarios: simple queue, latest comment list, non-real-time ranking: scheduled calculation of rankings, such as mobile phone daily sales list

Common commands for List

1. # lpush 将一个或多个值插入到列表头部
     lpush phone:rank:daily iphone6
     
2. # rpop 移除并获取列表的最后一个元素
     rpor phone:rank:daily 

3. # llen 获取列表长度
     llen phone:rank:daily
     
4. # lrange 获取key对应的list的指定下标范围元素,其中0表示列表的第一个元素,-1表示获取列表的所有元素     
     lrange phone:rank:daily 0 -1
     
5. # rpush 在key对应的list尾部添加一个元素
     rpush phone:rank:daily xiaodi 

6. # lpop 从key对应的List的尾部删除一个元素,并返回该元素
     lpop phone:rank:daily
     
7. # bropo 移出并获取列表的最后一个元素,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止    
     brpop phone:rank:daily 20
     
8. # lrem 移除元素
     lrem phone:rank:daily 2 a

The internal structure of List (the internal structure is for in-depth exploration)

We have learned about the use of common commands of List. Let us now take a look at the underlying structure of List.

List has two implementation methods

  • Compressed linked list (ziplist): It is developed by Redis to save memory space. It is composed of specially coded continuous memory blocks. A sequential data structure, a compressed list can contain many arbitrary nodes, its focus is memory contiguous!

  • 双端链表:使用prev和next这两个指针,是可以从前向后也可以从后向前来实现lpush和rpush这些指令。因为是链表,所以也导致了lindex指令获取某个元素需要遍历链表才能获取得到。时间复杂度O(n)。

     当列表的对象同时满足下述两个条件时,列表对象采用压缩链表编码:

    (1)列表对象保存的所有元素长度都小于64个字节;

    (2)列表元素所保存的元素个数小于512个

在Redis3.2之后,采用的是快速链表-quicklist。quicklist是一个双向链表,并且它还是一个有ziplist特性的双向链表,就是说quicklist每个节点都是ziplist。这个快速链表结合了两者的优点。

Hash类型的介绍与使用场景

Redis中的Hash类型是一个String类型的field和value的映射表,Hash特别适合用于存储对象,Hash类似于Map结构。因为在Redis里,Hash又是另外的一种键值对结构,而Redis本身就是key-value类型,所以这个Hash结构是套在了Redis下的value里。

下面说说Hash的底层数据结构:

一种是ziplist 当存储的数据超过所配置的数量大小时就是转成Hashtable这种结构。这种转换会比较消耗性能,所以尽量少用这种转换操作。

另一种就是hashtable 这种结构的时间复杂度为O(1),但是会比较消耗内存空间。  

对于Hash在Redis中的应用场景:购物车、用户个人信息、商品详情的实现

Hash的常用命令

1. # hset 设置key指定的哈希集指定字段的值
     hset product:detail:1 title iphone11
     
2. # hget 返回key指定的哈希集中该字段所关联的值
     hget product:detail:1 title

3. # hgetall 返回key指定的哈希集中所有的字段和值
     hegetall product:detail:1
     
4. # hdel 从key指定的哈希集中移除指定的域     
     hdel product:detail:1 title
     
5. # hexists 返回hash里面的field是否存在
    hexists product:detail:1 title  (存在返回1,不存在返回0)

6. # hincrby 增加key指定的哈希集中的指定字段的数值,如果是-1则是递减
     hincrby product:detail:1 key 1 (对key里的value值进行递增或递减)
     
7. # hmset 设置key指定的哈希集中指定字段的值    
     hmset product:detail:2 title xiaomi price 1000 stock 10
     
8. # hmget 返回key指定的哈希集中指定字段的值
     hmget product:detail:2 title price

注意: 每个Hash可以存储232-1键值对

Set类型的介绍与使用场景

Redis中的Set类型是一个集合,集合的概念是一堆不重复的组合。利用Redis提供的Set数据结构可以存储一些集合性的数据。因为Redis很友好的为集合提供了求集、并集、差集等操作( PS:不懂的同学可以问下以前的数学老师哦~哈哈哈哈),那么就可以非常方便的实现共同关注、共同喜好等功能。对上面的集合操作,你还可以使用不同的命令选择奖结果返回给客户端还是存集合到一个新的集合中。

Redis中Set应用场景:去重、社交应用关注(粉丝,共同好友)、统计网站PV(UV、IP)大数据里面的用户画像标签集合

Set的常用命令

1. # sadd 添加一个或多个指定的元素到集合中,如果指定的元素已经在集合key中则忽略
     sadd user:tags female
     sadd user:tags bmw
     
2. # scard 返回集合存储的key的基数(集合元素的数量)
     scard user:tags

3. # sdiff 返回的集合元素是第一个key集合与后面所有key集合的差集
     sdiff user:tags:1 user:tags:2
     
4. # sinter 返回指定所有的集合的成员的交集    
     sinter user:tags:1 user:tags:2
     
5. # sismember 返回成员是否有存储的集合key的成员
    sismember user:tags:1 bmw  

6. # srem 在集合中移除指定的元素,如果指定元素不是key集合中的则忽略
     srem user:tags:1 bmw 
     
7. # sunion 返回给定的多个集合的并集所有的成员   
     sunion user:tags:1 user:tags:2

SortedSet类型的介绍与使用场景

和Set相比,SortedSet是将Set中的元素增加了一个权重参数score,使得集合中的元素能够按 score进行有序排序,比如存储一个存储班上同学成绩的SortedSet集合,该集合value可以设为同学的学号,然而score就可以是考试成绩。这样才插入数据的时候,就已经为数据进行了排序。另外,SortedSet还可以用来做带权重的队列。

应用场景:实时排行榜、优先级任务(队列)、朋友圈(文章)点赞-取消

SortedSet中跳跃表的介绍

跳跃表实则是一个链表,在传统的链表中想要查找一个元素就要从最原始的地方开始查找,直到查找到该元素。在跳跃表中呢,它会把链表进行抽层,抽层的时候会隔几个元素分为一个节点,抽层之后也是一条链表,节点会变少了。如下图所示,当要寻找元素78时,如果是寻常的链表就会从左往右挨个查询,这时查询了8次才能找带该元素。当使用跳跃表后,从第二层的开始出发,当查询到79这个节点时发现没有78,则返回到57这个节点再返回第一层去寻找该元素。

Organize some common Redis data structures (summary)

SortedSet的常用命令

1.# zadd 向有序集合里添加一个或者多个成员,或者更新已存在成员的分数
    zadd video:rank 90 springcloud
    zadd video:rank 80 springboot
    zadd video:rank 50 redis
    
 2.# zcard 获取有序集合的成员数
    zcard video:rank
    
 3.# zcount 计算在有序集合中指定的区间分数的成员数
     zcount video:rank 0 60
 
 4.# zincrby 在有序集合中对指定成员的分数加上增量
     zincrby video:rank 2 springcloud
 
 5.# zrange 通过索引区间返回有序集合指定内的成员,成员位置分数按(从小到大排序)
     zrange voideo:rank 0 -1 
     zrange voideo:rank 0 -1  withscores(返回分数)
 
 6.# zrevrange 通过索引集合中指定成员的排名,其中有序集合成员按score值递增(从大到小排序)
     zrevrange voideo:rank 0 -1 
 
 7.# zrevrank 返回有序集合中指定的成员排名,有序集合成员按分数递减(从大到小排序)
     zrevrank voideo:rank springcloud 
 
 8.# zrank 返回有序集key中成员member的排名,其中有序集成员按score值递增(从小到大排序)
     zrank voideo:rank
 
 9.# zrem 移除有序集合中的一个或者多个成员
      zrem voideo:rank redis
 
 10.# zscore 返回有序集合中的成员分数值
     zscore voideo:rank springcloud

好啦Redis的数据类型都整理好了,如果文章对你有帮助的话记得点点赞哈,可以的话也点点关注哦。求求各位大哥啦。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Organize some common Redis data structures (summary). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete