Table of Contents
redis The application of traditional 5 big data types
string String type
Home Database Redis Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Feb 11, 2022 pm 07:51 PM
redis

This article will introduce you to the five basic types in Redis through commands and application scenarios. There are many commands and practices. I hope it will be helpful to everyone!

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

redis The application of traditional 5 big data types

redis The implementation of traditional 5 big data types

Redis introduction:

Redis is an open source (BSD licensed), in-memory data structure storage system that can be used as a database, cache, and messaging middleware. It supports many types of data structures such as strings, hashes, lists, sets, sorted sets] with range queries, bitmaps, hyperloglogs and geospatial (geospatial) Index radius query. Redis has built-in replication, LUA scripting, LRU eviction, transactions and different levels of disk persistence, and through Redis Sentinel and automatic partitioning (Cluster) ) provides high availability. [Related recommendations: Redis video tutorial]

redis command query: http://www.redis.cn/commands.html

Note: redis commands are not size sensitive Write, and key is case-sensitive

Query command help:

help @type noun

Example:

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

string String type

Most commonly used

## set key vuue

getkey

Set/get multiple key values ​​at the same time

MSET key value [key value .. .]

MGET key [key ,,,]

Increase and decrease the value

increment the number incr key

Increase the specified integer incrby key increment

Decrease the numerical decr key

Decrease the specified integer decrby key decrement

Get the character length

STRLEN key

Distributed lock

setnx key value

set key value [EX seconds] [PX milliseconds] [NX|XX]

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

    EX: how many seconds does the key expire after?
  • PX: key since Expiration after how many milliseconds
  • NX: When the key does not exist, the key is created. The effect is equivalent to setnx
  • XX: When the key exists, overwrite the key

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Application scenarios

    The product number and order number are generated using the INCR command
  • Yes Like the article
Reading count: As long as you click on the rest address, directly use the incr key command to add a number 1 to complete the recording of the number.

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Command practice

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

hash Hash type

and Java data structure mapping

Map>

##Set one field value at a time HSET key field value

Get one field value at a time

HGET key field

Set multiple field values ​​at one time

HMSET key field value [fild value ...]

Get multiple field values ​​at one time

HMGET key field [field ...]

Get all field values

hgetall key

Get all the quantities in a key

hlen

Delete a key

hdel

Command demonstration

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Application scenariosIn the early days of the shopping cart, currently small and medium-sized factories can use

to add new products --> hset shopcar:uid1024 334488 1

Add new product--> hset shopcar:uid2014 334477 1

Add product quantity--> hincrby shopcar:uid1024 334477 1

product Total --> hlen shopcar:uid1024

Select all --> hgetall shopcar:uid1024

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

list List type

Add elements to the left of the list

lpush key value [value ...]

Add elements to the right of the list

rpush key value [value ...]

View the list

lrange key start stop

Get the elements in the list Number

llen key

Command usage

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

Application scenario

WeChat article subscription public account

1, [xx treasure] and [xx newspaper] published articles 11 and 22## respectively

#2. The author follows both of them. As long as they publish a new article, it will be pushed to my list

lpush likearticle: uid1024 11 22

3. View the author All articles of your own subscription account are similar to paging. The following 0-10 is to display 10 items at a time lrange likearticle:uid1024 0 10

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

set Non-duplicate list type

Add element

sadd key member [member ...]

Delete element

srem key member [member ...]

Get all elements of the collection

smembers key

Judge whether the element is in the collection

sismember key member

Get the number of elements in the collection

scard key

From the collection Randomly pop up an element from the collection, the element will not be deleted

srandmember key [number]

Randomly pop up an element from the collection, delete one element

spop key [Number]

Set operation

  • Difference operation of sets A - B

A set constructed from elements that belong to A but not B

sdiff key [key ...]

  • The intersection of the sets is calculated as A ^ B

Elements that belong to A and also belong to B.

simter key [key ...]

  • Union of sets Operation A v B

The merged set of elements belonging to A or B

sunion key [key ...]

Application Scenario

WeChat Lottery Mini Program

Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

1. User id, participate immediately, sadd key user id

2. Display how many people have participated. There are currently 67231 people participating. scard key

3. Lottery (arbitrarily select N winners from the set)

srandmember key 2 random If you draw 2 people, the elements will not be deleted

spop key 3 Drivers draw 3 people, the elements will be deleted

Likes in WeChat Moments

1Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

1. Add a like; sadd pub:msgid like user id1 like user id2

2. Cancel like; srem pub:msgid like user id

3. Show all points Users who have liked smembers pub:msgid

4. Statistics of the number of users who like it, which is the common red number waiting for likes. scard pub:msgid

5. Determine whether a friend is right The author liked it, sismember pub:msgid user id

Weibo friends follow social relationships

1Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

People who follow together

sadd s1 1 2 3 4

sadd s2 2 3 6 8

sinter s1 s2

Common attention: I go to someone’s Weibo and immediately get the information that is shared with someone People

The people I follow also follow him (we all have the same hobbies)

I follow Yu Chengdong of Huawei, Yu Chengdong also follows Zhang Zhaodong, Mr. Yu and I have the same hobbies

sadd s1 1 2 3 4 5

sadd s2 3 4 5 6 7

sismember s1 3

sismember s2 3

QQ Recommend people you may know

sadd s1 1 2 3 4 5

sadd s2 3 4 5 6 7

// Common friends

sinter s1 s2

// Difference set

sdiff s1 s2

sdiff s2 s1

zset ordered set

Common commands

1. Add an element and the score of the element to the ordered set

2. Add element

    ZADD key score member [score member ...]
3. Return all elements with index from strat to stop in the order of arrival of element scores

    zrange key start stop [WITHSORES]
4. Get the score of the element

    zscore key member [member ...]
5. Delete Element

    zrem key member [member ...]
6. Get the elements of the specified score range

    zrangebyscore key min max [ WITHSCORES] [LIMIT offset count]
7. Increase the score of an element

    zincrby key increment member
8. Get the set The number of elements in

    zcard key
9. Obtain the number of elements within the specified score range

    zcount key min max
10. Delete elements according to ranking range

  • zremrangebyrank key start stop

11. Get the ranking of elements

  • zrank key member

  • Zrevrank key member from large to small

Application scenarios

1. More product sales Sorting and displaying products

Idea: Define the product sales ranking list (sorted set), the key is goods:sellsort, and the score is the product sales quantity.

The sales volume of product number 1001 is 9, and the sales volume of product number 1002 is 15 | zadd goods:sellsort 9 1001 15 1002
A customer bought 2 more items Product 1001, the product number is 1001 loudly increase 2 | zincrby goods:sellsort 2 10001
Find the top 10 products by sales zrange goods:sellsort 0 10 withscores
1Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

2. Douyin hot search

1Through commands and application scenarios, we will guide you to understand the five basic types in Redis.

1. Click on the video

ZINCRBY hotavi:20220203 1 八百

ZINCRBY hotavi :20220203 15 Eight Hundred 2 Hua Mulan

2. Display the top 10 items on the day

zrevrange hotavi:20220203 0 9 withscores

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Through commands and application scenarios, we will guide you to understand the five basic types in Redis.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

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 How to clear redis data Apr 10, 2025 pm 10:06 PM

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.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

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.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

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.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles