10 Real-World Redis Use Cases Every Backend Engineer Should Know
Discover ten practical Redis scenarios—from counting page visits and caching category trees to implementing distributed locks, leaderboards, rate limiting, bitmap analytics, message queues, and global ID generation—each illustrated with concise code snippets and best‑practice tips for robust backend development.
Redis is a high‑performance key/value cache widely used in development and interviews.
This article presents ten practical Redis scenarios with code examples and implementation tips.
1. Count page visits
Define a key such as
OFFICIAL_INDEX_VISIT_COUNTand use
INCRto increment the count, or
INCRBYto add a larger value.
<code>INCR OFFICIAL_INDEX_VISIT_COUNT</code> <code>INCRBY OFFICIAL_INDEX_VISIT_COUNT 5</code>2. Retrieve category tree
Cache the JSON representation of a category tree in Redis with a key like
MALL_CATEGORY_TREE. A scheduled job populates the cache, and the API reads directly from this key, avoiding expensive recursive database queries.
3. Implement distributed lock
Use Redis
SETwith the
NXand
PXoptions to acquire a lock atomically. Example Java code:
<code>try{String result=jedis.set(lockKey,requestId,"NX","PX",expireTime);if("OK".equals(result)){return true;}return false;}finally{unlock(lockKey);}</code>Be aware of edge cases where a lock may be released unintentionally.
4. Build leaderboards
Store ranking data in a Sorted Set. Use
ZADDto add scores and
ZRANGE(with
WITHSCORES) to retrieve the ordered list.
<code>ZADD rank:score 100 "周星驰"
ZADD rank:score 90 "周杰伦"
ZADD rank:score 80 "周润发"
ZRANGE rank:score 0 -1 WITHSCORES</code> <code>1) "周星驰"
2) "100"
3) "周杰伦"
4) "90"
5) "周润发"
6) "80"</code>5. Record user login status
Store a user's login information in Redis with an expiration time (e.g., 1800 seconds). Subsequent requests check this key to verify authentication.
<code>jedis.set(userId, userInfo, 1800);</code>6. Rate limiting
Track request counts per IP or user ID in Redis. Increment a counter for each request and set an expiration (e.g., one day). If the count exceeds a threshold, reject the request.
7. Bitmaps for statistics
Use Redis bitmap commands to record daily user activity.
SETBITmarks a user as active on a specific date;
GETBITchecks the status.
<code>SETBIT user:view:2024-01-17 123456 1</code> <code>GETBIT user:view:2024-01-17 123456</code>Iterate over user IDs to compute weekly or monthly active user metrics.
8. Cache acceleration
Implement a read‑through cache: query Redis first; if a miss occurs, fetch from the database, store the result in Redis, and return it. Be mindful of cache‑related issues such as penetration, breakdown, and avalanche.
9. Message queue
Redis Pub/Sub can serve as a lightweight message queue. Implement a Java
MessageListenerto consume messages from a channel.
<code>@Slf4j
@Component
public class RedisMessageListenerListener implements MessageListener {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(pattern);
RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();
Object deserialize = valueSerializer.deserialize(message.getBody());
if (deserialize == null) return;
String md5DigestAsHex = DigestUtils.md5DigestAsHex(deserialize.toString().getBytes(StandardCharsets.UTF_8));
Boolean result = redisTemplate.opsForValue().setIfAbsent(md5DigestAsHex, "1", 20, TimeUnit.SECONDS);
if (Boolean.TRUE.equals(result)) {
log.info("Received result: {}", deserialize.toString());
} else {
log.info("Other service processing");
}
}
}
</code>10. Generate global IDs
Use
INCRBYon a dedicated key to obtain atomic, incrementing identifiers, useful for sharding or batch ID allocation.
<code>INCRBY userid 10000</code>macrozheng
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.