16 Practical Redis Use Cases You Should Know
This article walks through sixteen common Redis scenarios—including caching hot data, sharing state across services, implementing distributed locks, generating global IDs, counting events, rate limiting, bitmap statistics, shopping carts, timelines, message queues, lotteries, likes, tagging, product filtering, and leaderboards—each illustrated with concrete commands and code snippets.
1. Caching
Redis strings are used to cache hot data such as reports, popular objects, or full‑page content, dramatically improving read performance for frequently accessed items.
2. Distributed Data Sharing
Because Redis runs as an independent distributed service, multiple applications can share data via strings; a typical example is storing a distributed session.
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>3. Distributed Lock
Using the SETNX command, a lock is acquired only when the key does not exist. The lock is set to expire to avoid dead‑locks.
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 Generation
Redis integer keys with the INCRBY command provide atomic auto‑increment IDs, useful for sharding scenarios where a block of IDs is allocated at once.
INCRBY userid 10005. Counters
Simple integer counters are implemented with INCR. Typical uses include article view counts or social media likes, where writes are frequent and eventual consistency with the database is acceptable.
6. Rate Limiting
By using an integer key that increments on each request (key composed of the visitor’s IP and other attributes), the system can reject requests once a predefined threshold is exceeded.
7. Bitmaps (Bit Statistics)
Redis strings store binary data; the BITCOUNT command (available since 1.6.6) enables space‑efficient statistics. Example commands set and modify bits, then retrieve the value.
SET k1 a
SETBIT k1 6 1
SETBIT k1 7 0
GET k1Bit operations such as BITOPAND, BITOPOR, BITOPXOR, and BITOPNOT allow aggregation of multiple bitmap keys, e.g., finding users online for seven consecutive days.
8. Shopping Cart
Implemented with a Redis hash where key = userId, field = productId, and value = quantity. Operations include HINCRBY to add, HDECRBY to subtract, HDEL to remove, HGETALL to list all items, and HLEN for the number of distinct products.
9. Timeline (Message Feed)
Redis lists (doubly linked) naturally model a timeline; inserting items in order keeps the feed sorted.
10. Message Queue
Lists provide blocking pop operations BLPOP and BRPOP with timeout, behaving like Java’s blocking queue. RPUSH adds to the tail, while BLPOP removes from the head (FIFO queue) or BRPOP for LIFO stack semantics.
11. Lottery
Redis sets support random element removal with SPOP, enabling simple lottery draws.
12. Likes, Check‑ins, and Attendance
Each post can be represented by a set key such as like:t1001. Adding a like uses SADD, removing uses SREM, checking membership uses SISMEMBER, and counting likes uses SCARD. This approach is far simpler than relational tables for this use case.
13. Product Tags
Tags are stored in sets, e.g., SADD tags:i5001 "画面清晰细腻", allowing fast retrieval of all products sharing a tag.
14. Product Filtering
Multiple tag sets (brand, OS, screen size, screen type) are intersected with SINTER to find products matching all criteria, e.g., Apple iOS phones with a 6.0‑6.24‑inch LCD screen.
SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd15. Follow / Recommendation Model
Followers and fans are modeled as sets ( 1:follow 2, 2:fans 1). Intersections find mutual follows, while set differences discover potential connections.
16. Leaderboard
Sorted sets track scores such as news click counts. Increment a member’s score with ZINCRBY and retrieve the top N items with ZREVRANGE including scores.
ZINCRBY hotNews:20190926 1 n6001
ZREVRANGE hotNews:20190926 0 15 WITHSCORESAll the above patterns demonstrate how Redis can replace traditional databases for specific high‑performance scenarios while keeping the implementation concise and scalable.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
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.
