Databases 9 min read

16 Common Redis Application Scenarios with Code Examples

This article presents sixteen typical Redis use cases—including caching, distributed locks, global IDs, counters, rate limiting, bitmaps, shopping carts, timelines, message queues, lotteries, likes, product tags, filtering, follow relationships, and ranking—each explained with practical code snippets and command examples.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
16 Common Redis Application Scenarios with Code Examples

The author, an architect who writes code and poetry, shares sixteen common Redis application scenarios, providing explanations, command-line examples, and Java code snippets for each use case.

1. Cache

String type. Examples: hot data cache such as reports or celebrity news, 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, e.g., distributed session storage.

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

3. Distributed Lock

String type setnx method; the lock is acquired 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, leveraging atomicity. Example: incrby userid 1000 to generate sequential IDs, useful in sharding scenarios.

5. Counter

Integer type using the incr command. Typical for article view counts, likes, or any metric that can tolerate slight delay by writing to Redis first and syncing to the database later.

6. Rate Limiting

Integer type using incr. The key can be composed of the visitor's IP and other info; each request increments the counter, and exceeding the limit returns false.

7. Bit Statistics (Bitmap)

String type bitcount (Redis 1.6.6 bitmap). Characters are stored as 8‑bit binary values, enabling space‑efficient large‑scale statistics.

set k1 a
setbit k1 6 1
setbit k1 7 0
get k1
/* 6 and 7 represent the binary bits of 'a' (ASCII 97 = 01100001) */

Example: online user statistics.

setbit onlineusers 01
setbit onlineusers 11
setbit onlineusers 20

Bitwise operations:

BITOP AND destkey key1 key2 ...
BITOP OR destkey key1 key2 ...
BITOP XOR destkey key1 key2 ...
BITOP NOT destkey key

Calculate 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

Implemented with String or hash. All operations possible on strings are also available on hashes. Example key: user ID; field: product ID; value: quantity. Increment with hincrby , decrement with hdecrby , delete with hdel , retrieve all with hgetall , count items with hlen .

9. User Timeline

Use a Redis list (doubly linked list) as a timeline; insertions maintain order.

10. Message Queue

Redis list provides two blocking pop operations: blpop and brpop , each allowing a timeout. This mirrors Java's blocking queue semantics (FIFO).

11. Lottery

Redis set provides a random member command for lottery draws.

spop myset

12. Likes, Check‑ins, and Punch‑in

Use a set to record users who liked a post: sadd like:t1001 u3001 . Remove with srem , check membership with sismember , and count with scard .

13. Product Tags

Maintain product tags with sets, e.g., sadd tags:i5001 "clear display" .

14. Product Filtering

Use set operations to filter products by brand, OS, screen size, etc.

// Get intersection of brand, OS, screen size, and screen type
sinter brand:apple brand:ios screensize:6.0-6.24 screentype:lcd

15. Follow / Recommendation Model

Use sets to represent follow relationships and fans. Intersection finds mutual follows; difference finds potential acquaintances.

sadd 1:follow 2
sadd 2:fans 1
sinter 1:follow 2:fans   // mutual follows
sdiff 2:follow 1:follow   // people user2 follows that user1 does not

16. Ranking

Use sorted sets for ranking. Increment a news item's score with zincrby and retrieve top N items with zrevrange .

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

The article concludes by encouraging readers to share the content, join the architect community, and continue learning.

backendCacheDatabaseRediscodeDistributedLock
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

login 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.