Common Redis Use Cases and Implementation Patterns

This article presents a comprehensive collection of Redis use cases—including caching, distributed locks, global IDs, counters, rate limiting, bitmaps, shopping carts, timelines, message queues, lotteries, likes, product tagging, filtering, follow relationships, and ranking—along with practical code snippets and command examples for backend developers.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Common Redis Use Cases and Implementation Patterns

1. Cache

Redis strings can be used for hot‑data caching such as report data, celebrity updates, object caching, or full‑page caching, which significantly improves access speed for frequently requested information.

2. Distributed Data Sharing

Because Redis is a distributed, independent service, it enables data sharing across multiple applications, for example distributed sessions. The following Maven dependency adds Spring Session support for Redis:

<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

3. Distributed Lock

Using the SETNX command, a lock can be acquired only when the key does not exist. The Java implementation below demonstrates lock acquisition with expiration and lock release:

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

Atomic integer IDs can be generated with INCRBY. For example, INCRBY userid 1000 yields a unique, sequential ID suitable for sharding scenarios.

5. Counter

Simple counters use the INCR command (e.g., article view counts, likes). Data can be written to Redis first and later synchronized to a relational database.

6. Rate Limiting

By incrementing a key that combines the visitor’s IP and other attributes, the system can reject requests once a predefined threshold is exceeded.

7. Bitmaps

Redis bitmaps (String type) allow space‑efficient statistics. Example commands set bits and retrieve counts, while BITOP provides logical AND/OR/XOR/NOT operations for multi‑day analysis.

set k1 a
setbit k1 6 1
setbit k1 7 0
get k1

To 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

A cart can be stored as a String or Hash. Using a Hash, the key is the user ID, the field is the product ID, and the value is the quantity. Operations include HINCRBY to add, HDECRBY to subtract, HDEL to remove, HGETALL to list all items, and HLEN to count distinct products.

9. User Timeline

Redis List (a double‑ended queue) naturally fits a timeline; items are inserted in order and can be retrieved efficiently.

10. Message Queue

List provides blocking pop operations BLPOP and BRPOP with timeout, effectively implementing a simple message queue similar to Java’s blocking queue.

11. Lottery

Random selection is achieved with SPOP on a set.

spop myset

12. Likes, Check‑in, Clock‑in

Use a Set to record users who liked a post (e.g., like:t1001). Commands include SADD to like, SREM to unlike, SISMEMBER to check, SMEMBERS to list all likers, and SCARD to count likes.

13. Product Tags

Product tags are stored in a Set, e.g., SADD tags:i5001 "画面清晰细腻".

14. Product Filtering

Set operations enable complex filtering: SDIFF for difference, SINTER for intersection, and SUNION for union. Example filtering for iPhone 11 by brand, OS, screen size, and screen type:

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:lcd

15. Follow & Recommendation Model

Follow and fan relationships are modeled with Sets ( user:follow, user:fans). Mutual follows are stored in both sets, and intersections/differences reveal common connections or potential acquaintances.

16. Ranking

Sorted Sets maintain scores, e.g., news click counts. Increment with ZINCRBY and retrieve the top N items with ZREVRANGE … WITHSCORES.

zincrby hotNews:20190926 1 n6001
zrevrange hotNews:20190926 0 15 withscores

The article concludes here.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisData Structures
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.