Implementing a Robust Redis Distributed Lock with AOP and Auto-Extension in Java
Learn how to design and implement a Redis-based distributed lock in Java using custom annotations, AOP interception, and a scheduled executor to automatically extend lock expiration, ensuring safe concurrent access to critical resources while handling timeouts, retries, and thread interruptions.
1. Business Background
Some business requests are time‑consuming operations that need locking to prevent concurrent modifications and must operate on the database without affecting previous business.
2. Analysis Process
Use Redis as a distributed lock, storing lock state in Redis to solve the problem of JVM information not being shared across a cluster, define operation order, and protect user data correctness.
Design Steps
Create a custom annotation @interface with input parameter flags.
Add an AOP pointcut to scan the specific annotation.
Create an @Aspect bean to register and intercept the target method.
Use ProceedingJoinPoint and pjp.proceed() to wrap the method.
Lock before the pointcut and delete the key after task execution.
Core Steps: Lock, Unlock, Extend
Lock
Use RedisTemplate and opsForValue().setIfAbsent to set a key if it does not exist, generate a random UUID as the value, and set an expiration time with expire so the lock releases automatically.
Timeout Issue
If the method execution exceeds the lock timeout, the key may be released early, causing another thread to acquire the lock and both threads to operate on the same data, leading to inconsistency.
Solution: Add “Extension”
Maintain a scheduled thread pool ( ScheduledExecutorService) that scans a task queue every 2 seconds, checks if the lock is about to expire, and extends its expiration time.
/**
* Thread pool, each JVM uses one thread to maintain keyAliveTime, scheduled runnable
*/
private static final ScheduledExecutorService SCHEDULER =
new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool")
.daemon(true).build());
static {
SCHEDULER.scheduleAtFixedRate(() -> {
// do something to extend time
}, 0, 2, TimeUnit.SECONDS);
}Design Scheme
The final design combines the above analysis.
Implementation Steps
Intercept annotation @RedisLock and obtain parameters.
Perform lock operation.
Perform extension operation.
Finish business and release lock.
Testing
Apply the annotation to a controller method, set lock time, and simulate a long‑running request with Thread.sleep. The scheduled executor extends the lock; after the retry limit is exceeded, the thread is interrupted and the request fails.
2020-04-04 14:55:50.864 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : 睡眠执行前
2020-04-04 14:55:52.855 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 0
2020-04-04 14:55:54.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 1
2020-04-04 14:55:56.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 2
2020-04-04 14:55:58.852 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 3
2020-04-04 14:56:00.857 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : has some error
java.lang.InterruptedException: sleep interruptedSummary
For time‑consuming business logic that accesses core data, a Redis distributed lock with automatic extension prevents duplicate concurrent operations and ensures data correctness. The key steps are creating the annotation, adding AOP pointcuts, using @Aspect, handling ProceedingJoinPoint, locking before the pointcut, and deleting the key after execution.
Key knowledge points covered: AOP implementation, ScheduledExecutorService usage, and Thread#interrupt semantics.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
