Mastering Redis: 16 Real-World Patterns for Caching, Locks, Queues, and More
This article presents 16 practical Redis use cases—including caching, distributed sessions, locks, global IDs, counters, rate limiting, bitmaps, shopping carts, timelines, message queues, lotteries, likes, product tags, filtering, follow relationships, and ranking—detailing data types, commands, and implementation tips for building scalable backend services.
1. Cache
String type. Example scenarios: hot‑data cache such as reports or trending topics, object cache, full‑page cache, all of which can improve access speed for frequently requested data.
2. Distributed Data Sharing
String type because Redis is an independent distributed service that can be shared across multiple applications. Typical use case: distributed session storage.
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>3. Distributed Lock
String type using the SETNX command; the lock is acquired only when the key does not exist.
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, which is atomic.
Example: INCRBY userid 1000 – useful for sharding scenarios where a block of IDs is allocated at once.
5. Counter
Integer type with the INCR command.
Typical uses: article view counts, social media likes, etc. Data can be written to Redis first and later synchronized to a relational database.
6. Rate Limiting
Integer type with INCR. Use the visitor’s IP (or other identifier) as the key; each request increments the counter, and exceeding a predefined threshold returns false.
7. Bit Statistics
String type with BITCOUNT (bitmap introduced in Redis 1.6.6). Characters are stored as 8‑bit binary values.
set k1 a
setbit k1 6 1
setbit k1 7 0
get k1Applications: online‑user statistics, retention analysis.
setbit onlineusers 01
setbit onlineusers 11
setbit onlineusers 20Bitwise operations such as AND, OR, XOR, NOT are supported.
BITOP AND destkey key1 key2 ...
BITOP OR destkey key1 key2 ...
BITOP XOR destkey key1 key2 ...
BITOP NOT destkey keyExample: compute users who were online all 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; any operation possible on a string can be performed on a hash.
Key: user ID; field: product ID; value: quantity.
Increment: HINCRBY; decrement: HDECRBY; delete: HDEL; get all: HGETALL; count items: HLEN.
9. User Timeline
Implemented with a Redis LIST (doubly linked list). Insertions keep the list ordered, making it suitable for timeline feeds.
10. Message Queue
Redis LIST provides two blocking pop commands: BLPOP and BRPOP, each accepting a timeout. BLPOP key1 timeout – removes and returns the first element, blocking until an element is available or the timeout expires. BRPOP key1 timeout – removes and returns the last element with the same blocking behavior.
These map directly to Java’s blocking queue semantics (FIFO). A stack can be simulated with RPUSH + BRPOP.
11. Lottery
Redis sets provide a built‑in random element extraction.
SPOP myset12. Likes, Check‑in, Punch‑in
Assume a post ID t1001 and a user ID u3001. Use a set like:t1001 to store all users who liked the post. SADD like:t1001 u3001 – like the post. SREM like:t1001 u3001 – unlike. SISMEMBER like:t1001 u3001 – check if liked. SMEMBERS like:t1001 – list all likers. SCARD like:t1001 – count likes.
This approach is far simpler than maintaining the same data in a relational database.
13. Product Tags
Use a set tags:i5001 to store all tags for product i5001.
SADD tags:i5001 "画面清晰细腻" SADD tags:i5001 "真彩清晰显示屏" SADD tags:i5001 "流程至极"14. Product Filtering
Set operations enable multi‑criteria filtering.
// Get difference
SDIFF set1 set2
// Get intersection
SINTER set1 set2
// Get union
SUNION set1 set2Example: an iPhone 11 that belongs to the Apple brand, runs iOS, has a screen size between 6.0‑6.24 inches, and uses an LCD panel.
SADD brand:apple iPhone11
SADD brand:ios iPhone11
SADD screensize:6.0-6.24 iPhone11
SADD screentype:lcd iPhone11
SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd15. Follow & Recommendation Model
Use sets to represent follow and fan relationships.
SADD 1:follow 2 SADD 2:fans 1 SADD 1:fans 2 SADD 2:follow 1Mutual follow is the intersection of a user’s follow set and another user’s fan set: SINTER 1:follow 2:fans Potential acquaintances can be discovered via set differences:
SDIFF 2:follow 1:follow // for user 1
SDIFF 1:follow 2:follow // for user 216. Ranking
Sorted sets ( ZSET) store scores such as article click counts.
ZINCRBY hotNews:20190926 1 n6001 // increment click count for news ID 6001
ZREVRANGE hotNews:20190926 0 15 WITHSCORES // top 15 items todaySigned-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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
