Ten Redis Techniques That Go Way Beyond Caching
10 Advanced Uses of Redis That Take Off Directly
Preface
In many developers' minds, Redis is just a caching tool. But if you only use it as a cache, that's like "killing a chicken with a cattle knife." Redis's power goes far beyond that. Its advanced features can make your system take off directly in terms of performance, scalability, and reliability. Today's article talks about 10 advanced uses of Redis, hoping to help you.
More hands-on projects at Java Commando Network: susan.net.cn/project
1. Bloom Filter
Some developers building high-concurrency systems fear cache penetration the most - a large number of requests bypass the cache and crush the database. A Bloom filter is a powerful tool for solving this.
1.1 What is a Bloom Filter
A Bloom filter is a space-efficient probabilistic data structure used to judge whether an element exists in a set. Its characteristics:
- Extremely memory-saving: storing 100 million elements requires only about 100MB of memory
- Has false positives: "not in set" is always accurate; "in set" may be a false positive (small probability)
- Cannot delete: does not support deleting elements
1.2 Principle
The principle of the Bloom filter is as shown:
The query flow is shown below:
1.3 Code Example (using Redisson)
@Component
public class BloomFilterService {
@Autowired
private RedissonClient redissonClient;
private RBloomFilter<String> bloomFilter;
@PostConstruct
public void init() {
bloomFilter = redissonClient.getBloomFilter("user:bloom");
// Initialization: expected 1 million entries, false positive rate 0.01
bloomFilter.tryInit(1000000L, 0.01);
}
// Add whitelist data
public void addUser(Long userId) {
bloomFilter.add(userId.toString());
}
// Intercept before query
public User getUserById(Long userId) {
// If not in bloom filter, return null directly to avoid DB query
if (!bloomFilter.contains(userId.toString())) {
return null;
}
// If it exists, query DB (cache as fallback)
return queryFromDB(userId);
}
}
Advantages: Very small memory footprint, effective against cache penetration.
Disadvantages: Has false positives, does not support deletion (counting bloom filters can be used if deletion is required).
Applicable scenarios: Preventing malicious requests from bypassing cache, spam email filtering, crawler URL deduplication.
2. Redisson Distributed Lock
Many people still use SET NX EX for distributed locks in Redis, but this has many pitfalls in complex scenarios. Redisson's distributed lock provides a more complete solution.
2.1 Why Not Use SET NX
Problems with plain SET NX:
- Improper lock expiration can release the lock prematurely
- Not verifying the holder when releasing a lock could delete another's lock
- No automatic renewal, so a long-running task loses the lock halfway through
2.2 Redisson Distributed Lock Principle
Redisson uses Lua scripts to ensure atomicity and a built-in watchdog mechanism for automatic renewal.
2.3 Code Example
@Service
public class OrderService {
@Autowired
private RedissonClient redissonClient;
public void processOrder(String orderId) {
RLock lock = redissonClient.getLock("order:lock:" + orderId);
try {
// Try to acquire lock, wait up to 10 seconds, lock validity 30 seconds (auto-renewed)
if (lock.tryLock(10, 30, TimeUnit.SECONDS)) {
// Execute business logic
doProcess(orderId);
} else {
throw new RuntimeException("Failed to acquire lock");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
} finally {
// Must release lock
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
Advantages: Automatic renewal avoids deadlock; reentrant; supports read/write locks, red locks, etc.
Disadvantages: Adds a Redisson dependency, slightly heavier than native Redis.
Applicable scenarios: Distributed task scheduling, inventory deduction, order creation, and other mutually exclusive scenarios.
3. Redisson Delayed Queue
Many scenarios require delayed processing, like auto-canceling orders not paid within 30 minutes. Traditional solutions use scheduled tasks scanning tables, which is inefficient and has latency. Redisson's delayed queue is based on Redis's Sorted Set and is precise and reliable.
3.1 Principle Diagram
3.2 Code Example
@Component
public class DelayQueueService {
@Autowired
private RedissonClient redissonClient;
private RBlockingQueue<Order> blockingQueue;
private RDelayedQueue<Order> delayedQueue;
@PostConstruct
public void init() {
blockingQueue = redissonClient.getBlockingQueue("order:queue");
delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
}
// Add delayed task
public void addOrder(Order order, long delay, TimeUnit unit) {
delayedQueue.offer(order, delay, unit);
}
// Consumer (separate thread)
@Async
public void startConsumer() {
while (true) {
try {
Order order = blockingQueue.take();
// Handle expired order
processExpiredOrder(order);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
Advantages: Precise scheduling, distributed, automatic persistent storage.
Disadvantages: Depends on Redis, message consumption failures require manual compensation.
Applicable scenarios: Order timeout closure, delayed notifications, scheduled task scheduling.
4. Token Bucket Rate Limiting
Facing sudden traffic, rate limiting is key to protecting the system. Redis + Lua can implement a high-performance token bucket algorithm.
4.1 Token Bucket Principle
4.2 Lua Script Implementation
@Component
public class RateLimiterService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String LUA_SCRIPT =
"local key = KEYS[1]\n" +
"local limit = tonumber(ARGV[1])\n" +
"local interval = tonumber(ARGV[2])\n" +
"local current = redis.call('get', key)\n" +
"if current and tonumber(current) >= limit then\n" +
" return 0\n" +
"else\n" +
" redis.call('incr', key)\n" +
" redis.call('expire', key, interval)\n" +
" return 1\n" +
"end";
public boolean tryAcquire(String key, int limit, int intervalSec) {
DefaultRedisScript<Long> script = new DefaultRedisScript<>(LUA_SCRIPT, Long.class);
Long result = redisTemplate.execute(script, Collections.singletonList(key), limit, intervalSec);
return result != null && result == 1L;
}
}
Advantages: Smooths sudden traffic spikes, simple implementation.
Disadvantages: Needs to be combined with sliding window for more fine-grained rate limiting.
Applicable scenarios: API rate limiting, anti-abuse, spike entry control.
5. Bitmap Statistics
Bitmap is a highly efficient data structure in Redis, suitable for counting boolean data. It's perfect for minimal-statistics of massive data.
5.1 Use Cases
- Counting daily active users: use user ID as offset, 1 means active
- Check-in records: for a year of 365 days, one user only needs 365 bits
5.2 Code Example
@Component
public class BitmapService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// User check-in
public void signIn(Long userId, LocalDate date) {
String key = "sign:" + date.toString();
redisTemplate.opsForValue().setBit(key, userId, true);
}
// Count check-ins on a day
public Long countSignIn(LocalDate date) {
String key = "sign:" + date.toString();
return redisTemplate.execute(
(RedisCallback<Long>) connection -> connection.bitCount(key.getBytes())
);
}
// Count consecutive check-in days (needs Lua)
public Long continuousSignDays(Long userId, LocalDate date) {
// Use BITFIELD command to get consecutive check-in days
// Implementation omitted
}
}
Advantages: Very low memory usage (100 million users only 12MB), fast computation.
Disadvantages: Only represents 0/1 states, not suitable for complex statistics.
Applicable scenarios: User check-in, online status, Bloom filter implementation.
6. HyperLogLog
It's the "memory-saving wonder" for deduplication statistics. If you need to count UV (unique visitors) with extremely large data (tens of millions), using a Set would consume a lot of memory. HyperLogLog is the solution.
6.1 Principle
HyperLogLog is a probabilistic algorithm that uses fixed memory (about 12KB) to count the cardinality of massive data, with an error rate around 0.81%.
6.2 Code Example
@Component
public class UVService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// Add visit record
public void addVisit(String date, String userId) {
String key = "uv:" + date;
redisTemplate.opsForHyperLogLog().add(key, userId);
}
// Count UV
public Long countUV(String date) {
String key = "uv:" + date;
return redisTemplate.opsForHyperLogLog().size(key);
}
// Merge multiple days' UV (e.g., weekly active)
public Long countWeeklyUV(List<String> dates) {
String destKey = "uv:weekly:" + LocalDate.now();
for (String date : dates) {
redisTemplate.opsForHyperLogLog().union(destKey, "uv:" + date);
}
return redisTemplate.opsForHyperLogLog().size(destKey);
}
}
Advantages: Fixed memory, suitable for ultra-large-scale deduplication.
Disadvantages: Not precise, cannot judge whether a specific element exists.
Applicable scenarios: UV counting, website traffic, large-scale deduplication.
7. GEO Geographic Location
It's commonly used in "nearby people" and store query features. Redis has supported geographic location since version 3.2, based on Sorted Sets, making it easy to calculate distances and search nearby locations.
7.1 Principle
Uses GeoHash to encode longitude and latitude, stored as scores, supporting search by radius and rectangular range.
7.2 Code Example
@Component
public class GeoService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// Add store location
public void addStore(Long storeId, double lng, double lat) {
String key = "stores:geo";
redisTemplate.opsForGeo().add(key, new Point(lng, lat), storeId.toString());
}
// Search nearby stores
public List<Store> findNearbyStores(double lng, double lat, double radiusKm) {
String key = "stores:geo";
Circle circle = new Circle(new Point(lng, lat), new Distance(radiusKm, Metrics.KILOMETERS));
GeoResults<RedisGeoCommands.GeoLocation<Object>> results =
redisTemplate.opsForGeo().radius(key, circle);
List<Store> stores = new ArrayList<>();
for (GeoResult<RedisGeoCommands.GeoLocation<Object>> result : results) {
// Parse result and construct Store object
}
return stores;
}
// Calculate distance between two stores
public Distance distanceBetweenStores(Long storeId1, Long storeId2) {
String key = "stores:geo";
return redisTemplate.opsForGeo().distance(key, storeId1.toString(), storeId2.toString());
}
}
Advantages: Rich features, supports radius and rectangular search, accurate distance calculation.
Disadvantages: Precision affected by GeoHash, index updates require rebuilding.
Applicable scenarios: Delivery rider dispatch, nearby store recommendations, ride-hailing matching.
8. Stream Message Queue
Redis 5.0 introduced Stream, a powerful message queue data structure supporting consumer groups, message acknowledgments, history replay, etc., and can replace MQ in some scenarios. It's a lightweight MQ alternative.
8.1 Architecture Diagram
8.2 Code Example (using Redisson)
@Component
public class StreamService {
@Autowired
private RedissonClient redissonClient;
private RStream<String, String> stream;
@PostConstruct
public void init() {
stream = redissonClient.getStream("order-stream");
// Create consumer group (if not exists)
stream.createGroup("order-group", StreamMessageId.AUTO);
}
// Producer
public void publish(String orderId) {
Map<String, String> data = new HashMap<>();
data.put("orderId", orderId);
data.put("timestamp", String.valueOf(System.currentTimeMillis()));
stream.add(data);
}
// Consumer (batch pull)
@Async
public void consume() {
while (true) {
Map<StreamMessageId, Map<String, String>> messages =
stream.readGroup("order-group", "consumer-1", 10);
for (Map.Entry<StreamMessageId, Map<String, String>> entry : messages.entrySet()) {
// Process message
process(entry.getValue());
// Acknowledge
stream.ack("order-group", entry.getKey());
}
// Sleep briefly when no messages
if (messages.isEmpty()) {
try { Thread.sleep(1000); } catch (InterruptedException e) { break; }
}
}
}
}
Advantages: Supports message persistence, consumer groups, message acknowledgment, and message replay.
Disadvantages: Compared to professional MQ, features are simpler, suitable for lightweight scenarios.
Applicable scenarios: Task queues, log collection, message notifications.
9. Lua Scripts
Some complex operations require multiple Redis commands to execute atomically; Lua scripts are the best solution.
9.1 Typical Scenarios
- Inventory deduction: check stock first, then deduct, to prevent overselling
- Set conditional locks
- Complex data aggregation
9.2 Code Example
@Component
public class LuaScriptService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// Lua script: inventory deduction
private static final String DECREASE_STOCK_SCRIPT =
"local key = KEYS[1]\n" +
"local count = tonumber(ARGV[1])\n" +
"local stock = redis.call('get', key)\n" +
"if not stock or tonumber(stock) < count then\n" +
" return 0\n" +
"else\n" +
" redis.call('decrby', key, count)\n" +
" return 1\n" +
"end";
public boolean decreaseStock(String productId, int count) {
DefaultRedisScript<Long> script = new DefaultRedisScript<>(DECREASE_STOCK_SCRIPT, Long.class);
Long result = redisTemplate.execute(script, Collections.singletonList("stock:" + productId), count);
return result != null && result == 1L;
}
// Distributed lock with timeout
private static final String LOCK_SCRIPT =
"if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then\n" +
" redis.call('expire', KEYS[1], ARGV[2])\n" +
" return 1\n" +
"else\n" +
" return 0\n" +
"end";
public boolean lock(String key, String value, int expireSec) {
DefaultRedisScript<Long> script = new DefaultRedisScript<>(LOCK_SCRIPT, Long.class);
Long result = redisTemplate.execute(script, Collections.singletonList(key), value, expireSec);
return result != null && result == 1L;
}
}
Advantages: Atomicity, less network transfer, high performance.
Disadvantages: Difficult to debug, scripts need careful writing.
Applicable scenarios: Inventory deduction, rate limiting, complex conditional updates.
10. RedisJSON
The RedisJSON module allows storing JSON documents directly in Redis and supports add, delete, modify, and query operations on fields within the document.
10.1 Installation
RedisJSON needs to be loaded as a module (Redis Stack includes it), or compiled and installed separately.
10.2 Code Example (using Lettuce)
@Component
public class RedisJsonService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// Store JSON object
public void saveUser(Long userId, User user) {
String key = "user:" + userId;
redisTemplate.opsForValue().set(key, user);
// Actually RedisJSON requires dedicated commands. This demonstrates the idea; in real use, use Lettuce's JSON command set.
}
// Update field
public void updateUserAge(Long userId, int age) {
// Use JSON.SET command
// redisTemplate.execute(connection -> connection.execute("JSON.SET", key, "$.age", String.valueOf(age)));
}
}
Advantages: Directly manipulate fields inside JSON, supports indexing and querying (with RediSearch).
Disadvantages: Requires an additional module, higher memory usage.
Applicable scenarios: User configuration, session information, dynamic forms.
More hands-on projects at Java Commando Network: susan.net.cn/project
Summary
The 10 advanced uses above cover many of Redis's powerful capabilities beyond caching:
| Use | Core Advantage | Typical Scenario |
|---|---|---|
| Bloom filter | Extremely memory-saving, prevents penetration | Cache penetration protection, spam |
| Redisson distributed lock | Auto-renewal, reentrant | Distributed mutual exclusion |
| Delayed queue | Precise scheduling | Order timeout, delayed notification |
| Token bucket rate limiting | Smooths traffic bursts | API rate limiting |
| Bitmap | Extremely memory-saving | Check-in, online status |
| HyperLogLog | Fixed memory | UV counting |
| GEO | Geographic search | Nearby people |
| Stream | Lightweight MQ | Task queue |
| Lua script | Atomic operations | Inventory deduction |
| RedisJSON | Document storage | User configuration |
In real projects, combining these advanced features wisely can help you build a high-performance, high-availability distributed system at very low cost.
Note that Redis is still an in-memory database; for large data volumes, memory cost must be considered, and persistence solutions may be needed.
Hope this article opens the door to Redis's advanced uses for you.
If you have better Redis practices, feel free to share in the comments!
More recommended articles: