Master Redis: 16 Real-World Patterns for Caching, Locks, and More
This guide explores 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 models, and ranking—providing code snippets and implementation tips for each pattern.
1. Caching
String type. Example: hot data cache (e.g., reports, trending items), object cache, full‑page cache, 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 across multiple applications.
Example: distributed session.
<code><dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</code>3. Distributed Lock
String type setnx method, succeeds only when the key does not exist and returns true.
<code>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);
}
</code>4. Global ID
int type, incrby, using atomicity.
Example:
incrby userid 1000– suitable for sharding scenarios to obtain a range of IDs.
5. Counter
int type, incr method.
Examples: article view count, social media likes; can tolerate some delay by writing to Redis first and syncing to the database later.
6. Rate Limiting
int type, incr method.
Use visitor IP and other information as the key; each request increments the count, and exceeding the limit returns false.
7. Bit Statistics
String type bitcount (bitmap data structure introduced in Redis 1.6.6).
Characters are stored as 8‑bit binary.
<code>set k1 a
setbit k1 6 1
setbit k1 7 0
get k1
/* 6 7 represent bits of 'a' (ASCII 97 = 01100001) */
</code>Applications: online user statistics, retention statistics.
<code>setbit onlineusers 01
setbit onlineusers 11
setbit onlineusers 20
</code>Supports bitwise AND, OR, XOR, NOT operations.
<code>BITOPAND destkey key1 key2 ...
BITOPOR destkey key1 key2 ...
BITOPXOR destkey key1 key2 ...
BITOPNOT destkey key
</code>Example: compute users online for seven consecutive days.
<code>BITOP "AND" "7_days_both_online_users" "day_1_online_users" "day_2_online_users" ... "day_7_online_users"
</code>8. Shopping Cart
String or hash. All operations possible with strings can be done with hashes.
key: user id; field: product id; value: quantity.
+1: hincr, -1: hdecr, delete: hdel, get all: hgetall, count fields: hlen.
9. User Timeline
list, a doubly linked list, can be used directly as a timeline; insertion keeps order.
10. Message Queue
List provides two blocking pop operations: blpop and brpop, with optional timeout.
blpop key timeout – removes and returns the first element, blocks until an element is available or timeout.
brpop key timeout – removes and returns the last element, blocks similarly.
These correspond to Java's blocking queue. Queue (FIFO): rpush + blpop. Stack (LIFO): rpush + brpop.
11. Lottery
Random value retrieval.
<code>spop myset
</code>12. Like / Check‑in / Punch‑in
Assume a post ID t1001 and a user ID u3001.
Use
like:t1001to store all users who liked the post.
sadd like:t1001 u3001 – like
srem like:t1001 u3001 – unlike
sismember like:t1001 u3001 – check like
smembers like:t1001 – list all likers
scard like:t1001 – count likes
13. Product Tags
Maintain product tags with
tags:i5001.
sadd tags:i5001 "clear picture"
sadd tags:i5001 "true color display"
sadd tags:i5001 "excellent workflow"
14. Product Filtering
<code>// Get difference
sdiff set1 set2
// Get intersection
sinter set1 set2
// Get union
sunion set1 set2
</code>Example: iPhone11 released.
<code>sadd brand:apple iPhone11
sadd brand:ios iPhone11
sad screensize:6.0-6.24 iPhone11
sad screentype:lcd iPhone11
</code>Filter products that are Apple, iOS, screen size 6.0‑6.24, and LCD.
<code>sinter brand:apple brand:ios screensize:6.0-6.24 screentype:lcd
</code>15. Follow / Recommendation Model
follow – following, fans – followers.
Mutual follow:
sadd 1:follow 2
sadd 2:fans 1
sadd 1:fans 2
sadd 2:follow 1
People I follow also follow them (intersection):
sinter 1:follow 2:fans
Potential acquaintances (difference):
sdiff 2:follow 1:follow
sdiff 1:follow 2:follow
16. Ranking
Increment news click count:
zincrby hotNews:20190926 1 n6001Get top 15 items for today:
zrevrange hotNews:20190926 0 15 withscoresmacrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.