Let's talk in depth about the 5 basic data types in Redis
This article will give you a detailed understanding of the 5 basic data types in Redis (String string, List list, Set collection, Hash hash, Zset ordered collection), I hope it will be helpful to you!
Introduction to Redis data structure
For redis, all keys are strings. When we talk about basic data structures, we discuss the data types for storing values, which mainly include 5 common data types: String, List, Set, Zset, and Hash. [Related recommendations: Redis video tutorial]
The value stored in the structure | Structure reading and writing capabilities | |
---|---|---|
String string | can be a string or an integer or floating point numberOperate on the entire string or a part of the string; perform increment or decrement operation on integer or floating point number; | |
List List | A linked list, each node on the linked list contains a stringPerform push and pop operations on both ends of the linked list, and read single or multiple elements; according to Value finds or deletes elements; | |
Set collection | An unordered collection containing stringsA collection of strings, Basic methods include checking whether there is addition, acquisition, and deletion; it also includes calculation of intersection, union, difference, etc. | |
Hash hash | Unordered hash table containing key-value pairsContains methods for adding, getting, and deleting single elements | |
Zset ordered set | Same as hashing, used to store key-value pairsOrdered mapping between string members and floating point scores; the order of elements is determined by the size of the scores; the inclusion method has been added , obtain, delete a single element and obtain elements based on score range or member |
Detailed explanation of basic data structure
## StringString is the most basic data type in redis. One key corresponds to one value.
The String type is binary safe, which means that the string of redis can contain any data. Such as numbers, strings, jpg images or serialized objects.
- Command usage
Brief description | Get the value stored in a given key using | |
---|---|---|
GET name | ||
Set the value stored in the given key | SET name value | |
Delete The value stored in the given key | DEL name | |
Increase the value stored by the key by 1 | INCR key | |
Decrease the value stored in the key by 1 | DECR key | |
Add the integer to the value stored in the key | INCRBY key amount | |
Subtract the integer from the value stored in the key | DECRBY key amount |
Command | Brief description | Use |
---|---|---|
RPUSH | to push the given value to the right end of the list | RPUSH key value |
LPUSH | Push the given value to the left end of the list | LPUSH key value |
RPOP | Pops a value from the right end of the list and returns the popped value | RPOP key |
LPOP | Pops a value from the left end of the list and returns Return the popped value | LPOP key |
LRANGE | Get all values in the list in the given range | LRANGE key 0 -1 |
LINDEX | Get the element in the list by index. You can also use negative subscripts, with -1 representing the last element of the list, -2 representing the penultimate element of the list, and so on. | LINEX key index |
- Tips for using lists
- lpush lpop=Stack(stack)
- lpush rpop=Queue (queue)
- lpush ltrim=Capped Collection (limited collection)
- lpush brpop=Message Queue (message queue)
- Command execution
127.0.0.1:6379> lpush mylist 1 2 ll ls mem (integer) 5 127.0.0.1:6379> lrange mylist 0 -1 1) "mem" 2) "ls" 3) "ll" 4) "2" 5) "1" 127.0.0.1:6379> lindex mylist -1 "1" 127.0.0.1:6379> lindex mylist 10 # index不在 mylist 的区间范围内 (nil)
- Actual scenario
- Weibo TimeLine: Someone posts on Weibo, uses lpush to add to the timeline, and displays New list information.
- Message Queue
Set Collection
Redis’ Set is An unordered collection of type String. Set members are unique, which means that duplicate data cannot appear in the set.
Collections in Redis are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1).
- Command usage
Command | Brief description | Add one or more members to the collection using |
---|---|---|
SADD | SADD key value | |
SCARD | Get the number of members in the set | SCARD key |
SMEMBER | Return all members in the set | SMEMBER key member |
SISMEMBER | Determine whether the member element is a member of the set key | SISMEMBER key member |
For other set operations, please refer here
https://www.runoob.com/redis/redis-sets.html
- Command execution
127.0.0.1:6379> sadd myset ycf ycf1 xiao ycf (integer) 3 127.0.0.1:6379> smember myset 1) "xiao" 2) "ycf1" 3) "ycf" 127.0.0.1:6379> sismember myset ycf (integer) 1
- Actual scenario
- Tag (tag), add to the user Tags, or users add tags to messages, so that those with the same tag or similar tags can recommend things or people to follow.
- Like, dislike, collect, etc. can be placed in the set to achieve
Hash hashing
Redis hash is a mapping table of string type fields and values. Hash is particularly suitable for storing objects.
- Command usage
Brief description | Use | |
---|---|---|
Add key-value pair | HSET hash-key sub-key1 value1 | |
Get the value of the specified hash key | HGET hash-key key1 | |
Get all key-value pairs contained in the hash | HGETALL hash-key | |
If the given key exists in the hash , then remove this key | HDEL hash-key sub-key1 |
命令 | 简述 | 使用 |
---|---|---|
ZADD | 将一个带有给定分值的成员添加到哦有序集合里面 | ZADD zset-key 178 member1 |
ZRANGE | 根据元素在有序集合中所处的位置,从有序集合中获取多个元素 | ZRANGE zset-key 0-1 withccores |
ZREM | 如果给定元素成员存在于有序集合中,那么就移除这个元素 | ZREM zset-key member1 |
更多命令请参考这里
https://www.runoob.com/redis/redis-sorted-sets.html
- 命令执行
127.0.0.1:6379> zadd myscoreset 100 ycf 90 xiaoycf (integer) 2 127.0.0.1:6379> ZRANGE myscoreset 0 -1 1) "xiaoycf" 2) "ycf" 127.0.0.1:6379> ZSCORE myscoreset ycf "100"
- 实战场景
- 排行榜:有序集合经典使用场景。例如小说视频等网站需要对用户上传的小说视频做排行榜,榜单可以按照用户关注数,更新时间,字数等打分,做排行。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Let's talk in depth about the 5 basic data types in Redis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

Redis data loss causes include memory failures, power outages, human errors, and hardware failures. The solutions are: 1. Store data to disk with RDB or AOF persistence; 2. Copy to multiple servers for high availability; 3. HA with Redis Sentinel or Redis Cluster; 4. Create snapshots to back up data; 5. Implement best practices such as persistence, replication, snapshots, monitoring, and security measures.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.
