Where can Redis be used? 16 common usage scenarios shared
Where can Redis be applied? This article will share with you 16 common usage scenarios of Redis in one go. I hope it will be helpful to everyone!

[Related recommendations: Redis video tutorial]
1. Cache
String type
For example: hot data cache (such as reports, celebrity cheating), object cache, full page cache, access data that can improve hot data.

2. Distributed data sharing
String type, because Redis is a distributed independent service and can be shared between multiple applications
For example: Distributed Session
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
3, Distributed lock
String type setnx method can only be added successfully if it does not exist, and returns true
public static boolean getLock(String key) {
Long flag = jedis.setnx(key, "1");
if (flag == 1) {
jedis.expire(key, 10);
}
return flag == 1;
}
public static void releaseLock(String key) {
jedis.del(key);
}4, Global ID
int type, incrby, using atomicity
incrby userid 1000
In the scenario of sub-database and sub-table, get a section at one time
5, Counter
int type, incr method
For example: the number of articles read, the number of Weibo likes, allow a certain delay, first write to Redis and then synchronize to the database regularly
6. Current limit
int type, incr method
uses the visitor's IP and other information as the key. Each visit increases the count. If the number exceeds the number, false is returned
7. Bit statistics
Bitcount of String type (bitmap data structure introduction in 1.6.6)
characters are stored in 8-bit binary
set k1 a setbit k1 6 1 setbit k1 7 0 get k1 /* 6 7 代表的a的二进制位的修改 a 对应的ASCII码是97,转换为二进制数据是01100001 b 对应的ASCII码是98,转换为二进制数据是01100010 因为bit非常节省空间(1 MB=8388608 bit),可以用来做大数据量的统计。 */
For example: online user statistics , retain user statistics
setbit onlineusers 01 setbit onlineusers 11 setbit onlineusers 20
Support bitwise AND, bitwise OR, etc. operations
BITOPANDdestkeykey[key...] ,对一个或多个 key 求逻辑并,并将结果保存到 destkey 。 BITOPORdestkeykey[key...] ,对一个或多个 key 求逻辑或,并将结果保存到 destkey 。 BITOPXORdestkeykey[key...] ,对一个或多个 key 求逻辑异或,并将结果保存到 destkey 。 BITOPNOTdestkeykey ,对给定 key 求逻辑非,并将结果保存到 destkey 。
Calculate users who have been online for 7 days
BITOP "AND" "7_days_both_online_users" "day_1_online_users" "day_2_online_users" ... "day_7_online_users"
8. Shopping cart
String or hash. All hashes that can be done with String can be done

- key: user id; field: product id; value: product quantity.
- 1: hincr. -1:hdecr. Delete:hdel. Select all: hgetall. Number of items: hlen.
9. User message timeline timeline
list, a doubly linked list, can be used directly as timeline. Insertion order
10. Message queue
List provides two blocking pop-up operations: blpop/brpop, and the timeout can be set
- blpop: blpop key1 timeout removes and gets the first element of the list. If there is no element in the list, the list will be blocked until the wait times out or a pop-up element is found.
- brpop: brpop key1 timeout removes and gets the last element of the list. If there are no elements in the list, the list will be blocked until the wait times out or a pop-up element is found.
The above operation. In fact, it is Java's blocking queue. The more things you learn. The lower the learning cost
- Queue: first in, last out: rpush blpop, left head and right tail, right side enters the queue, left side exits the queue
- Stack: first in, last out: rpush brpop
11. Draw
Comes with a random value
spop myset
12. Like, sign in, clock in

Suppose the above Weibo ID is t1001 and the user ID is u3001
Use like:t1001 to maintain t1001. All users who liked this Weibo
- liked this Weibo: sadd like:t1001 u3001
- Cancel like: srem like:t1001 u3001
- Like or not: sismember like:t1001 u3001
- All users who like it :smembers like:t1001
- Likes: scard like:t1001
Isn’t it much simpler than the database?
13. Product tags

The old rule is to use tags:i5001 to maintain all tags of the product.
- sadd tags:i5001 The picture is clear and delicate
- sadd tags:i5001 True color clear display
- sadd tags:i5001 The process is superb
14. Product selection
// 获取差集 sdiff set1 set2 // 获取交集(intersection ) sinter set1 set2 // 获取并集 sunion set1 set2
If: iPhone11 is on the market
sadd brand:apple iPhone11 sadd brand:ios iPhone11 sad screensize:6.0-6.24 iPhone11 sad screentype:lcd iPhone 11
Select products, Apple, ios, screen between 6.0-6.24 Sometimes, the screen material is LCD screen
sinter brand:apple brand:ios screensize:6.0-6.24 screentype:lcd
15. User attention, recommended models
follow Follow fans Fans
Follow each other:
- sadd 1:follow 2
- sadd 2:fans 1
- sadd 1:fans 2
- sadd 2:follow 1
I follow People also followed him (take intersection):
- sinter 1:follow 2:fans
People you may know:
- 用户1可能认识的人(差集):sdiff 2:follow 1:follow
- 用户2可能认识的人:sdiff 1:follow 2:follow
16、排行榜
id 为6001 的新闻点击数加1:
zincrby hotNews:20190926 1 n6001
获取今天点击最多的15条:
zrevrange hotNews:20190926 0 15 withscores
Redis 用的好,加薪少不了
原文地址:https://juejin.cn/post/6994229128534687781
作者:码猿技术专栏
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Where can Redis be used? 16 common usage scenarios shared. For more information, please follow other related articles on the PHP Chinese website!
Redis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AMRedis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.
Why Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AMRedis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,
Understanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AMKey features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.
Redis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AMThe core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.
Redis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AMRedis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.
How to implement redis counterApr 10, 2025 pm 10:21 PMRedis 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 use the redis command lineApr 10, 2025 pm 10:18 PMUse 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 build the redis cluster modeApr 10, 2025 pm 10:15 PMRedis 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


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function







