Redis Use Cases: Caching, Distributed Locks, Counters, Rate Limiting, Bitmaps, Shopping Cart, Timeline, Queues, and More
This article presents a comprehensive guide to applying Redis in backend systems, covering caching strategies, distributed data sharing, locks, global IDs, counters, rate limiting, bitmap statistics, shopping cart implementation, timelines, message queues, lotteries, likes, tags, product filtering, recommendation models, and leaderboards, with practical code examples.
1. Caching
String type. Example: hot data caching (e.g., reports, trending topics), object caching, full‑page caching, which can improve access speed for frequently accessed data.
2. Distributed Data Sharing
String type, because Redis is a distributed independent service that can be shared among multiple applications.
Example: distributed session.
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>3. Distributed Lock
String type using the SETNX command; it succeeds only when the key does not exist, returning 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
Integer type, using INCRBY for atomic increment.
Example: INCRBY userid 1000 – useful in sharding scenarios to obtain a block of IDs at once.
5. Counter
Integer type, using INCR. Typical uses: article view counts, social media likes, where a slight delay is acceptable (write to Redis first, then sync to DB).
6. Rate Limiting
Integer type, using INCR. Use the visitor's IP (or other identifier) as the key; each request increments the counter, and exceeding the limit returns false.
7. Bitmap Statistics
String type with BITCOUNT (Redis 1.6.6 bitmap data structure). Characters are stored as 8‑bit binary.
set k1 a
setbit k1 6 1
setbit k1 7 0
get k1
/* 6 and 7 represent the 6th and 7th bits of the ASCII code for 'a' (97 → 01100001) */Typical uses: online‑user statistics, retention tracking.
setbit onlineusers 01
setbit onlineusers 11
setbit onlineusers 20Supports bitwise AND, OR, XOR, NOT operations.
BITOP AND destkey key1 key2 ... keyN
BITOP OR destkey key1 key2 ... keyN
BITOP XOR destkey key1 key2 ... keyN
BITOP NOT destkey keyExample: compute users online for seven consecutive 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 operations possible on strings are also available on hashes.
key: user ID; field: product ID; value: quantity.
Increment: HINCRBY; decrement: HDECRBY; delete: HDEL; get all: HGETALL; count fields: HLEN.
9. User Timeline
Use a LIST (doubly linked list) as a timeline; insertion maintains order.
10. Message Queue
LISTprovides two blocking pop commands: BLPOP and BRPOP, each allowing a timeout. BLPOP key timeout – removes and returns the first element, blocking until an element is available or timeout. BRPOP key timeout – removes and returns the last element, with the same blocking behavior.
These correspond to Java's blocking queue semantics (FIFO queue: RPUSH + BLPOP; LIFO stack: RPUSH + BRPOP).
11. Lottery
Redis provides a random member operation.
SPOP myset12. Likes, Check‑ins, Clock‑ins
Assume a post ID t1001 and a user ID u3001.
Maintain likes with a set key like:t1001:
Like: SADD like:t1001 u3001 Unlike: SREM like:t1001 u3001 Check like: SISMEMBER like:t1001 u3001 All likers: SMEMBERS like:t1001 Like count:
SCARD like:t100113. Product Tags
Use a set key tags:i5001 to store all tags for a product.
SADD tags:i5001 "clear picture" SADD tags:i5001 "true color display" SADD tags:i5001 "extremely smooth"14. Product Filtering
// Get difference set
SDIFF set1 set2
// Get intersection
SINTER set1 set2
// Get union
SUNION set1 set2Example: an iPhone 11 launch.
SADD brand:apple iPhone11
SADD brand:ios iPhone11
SADD screensize:6.0-6.24 iPhone11
SADD screentype:lcd iPhone11Filter products that are Apple, iOS, screen size between 6.0‑6.24, and LCD:
SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd15. User Follow & Recommendation Model
Use FOLLOW and FANS sets.
SADD 1:follow 2 SADD 2:fans 1 SADD 1:fans 2 SADD 2:follow 1Mutual follow (intersection): SINTER 1:follow 2:fans Potential acquaintances (difference):
SDIFF 2:follow 1:follow // for user 1
SDIFF 1:follow 2:follow // for user 216. Leaderboard
Increment the click count of news item with ID 6001: ZINCRBY hotNews:20190926 1 n6001 Get the top 15 items for today:
ZREVRANGE hotNews:20190926 0 15 WITHSCORESSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
