How to Build a Robust Redis Distributed Lock with AOP and Auto‑Renewal

This article explains how to protect time‑consuming business operations using a Redis‑based distributed lock implemented with a custom annotation, Spring AOP interception, automatic lock renewal via a scheduled executor, and proper lock release, ensuring data consistency across concurrent requests.

Top Architect
Top Architect
Top Architect
How to Build a Robust Redis Distributed Lock with AOP and Auto‑Renewal

Business Background

Some business requests are time‑consuming and need locking to prevent concurrent operations and protect database data.

Analysis Process

Use Redis as a distributed lock, store lock state in Redis, define operation order, and protect data correctness.

Design Steps

Create annotation @RedisLockAnnotation to mark locked methods and specify the lock field.

Add AOP pointcut to scan the annotation.

Define @Aspect class to intercept methods, acquire lock with RedisTemplate.opsForValue().setIfAbsent, set expiration, and record the task in a queue.

Execute business logic via ProceedingJoinPoint.proceed().

In the finally block delete the key to release the lock.

Lock Acquisition

Use RedisTemplate.opsForValue().setIfAbsent(businessKey, uuid) and

RedisTemplate.expire(businessKey, lockTime, TimeUnit.SECONDS)

to obtain the lock.

Timeout Issue

If the protected method runs longer than the lock timeout, the key may expire early, allowing another thread to acquire the lock and cause data inconsistency.

Solution – Auto‑Renewal

Maintain a ScheduledExecutorService that runs every 2 seconds, scans a ConcurrentLinkedQueue of lock holders, extends the expiration when the remaining time is less than one‑third of the lock timeout, and interrupts the thread after a configured retry count.

private static final ScheduledExecutorService SCHEDULER =
    new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder()
        .namingPattern("redisLock-schedule-pool")
        .daemon(true)
        .build());

SCHEDULER.scheduleAtFixedRate(() -> {
    // iterate holders, extend or remove
}, 0, 2, TimeUnit.SECONDS);

Aspect Implementation

@Around("redisLockPC()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
    Method method = resolveMethod(pjp);
    RedisLockAnnotation ann = method.getAnnotation(RedisLockAnnotation.class);
    String businessKey = ann.typeEnum().getUniqueKey(pjp.getArgs()[ann.lockFiled()].toString());
    String uuid = UUID.randomUUID().toString();
    if (!redisTemplate.opsForValue().setIfAbsent(businessKey, uuid)) {
        throw new Exception("Lock already held");
    }
    redisTemplate.expire(businessKey, ann.lockTime(), TimeUnit.SECONDS);
    // add holder to queue for renewal
    Object result = pjp.proceed();
    return result;
} finally {
    redisTemplate.delete(businessKey);
    log.info("release the lock, businessKey is [" + businessKey + "]");
}

Testing

A controller method annotated with @RedisLockAnnotation demonstrates that when the lock timeout is exceeded, the thread is interrupted and the request fails, confirming that the lock works.

Lock design diagram
Lock design diagram

Conclusion

For time‑consuming operations that modify core data, a Redis‑based distributed lock with automatic renewal and thread interruption prevents duplicate concurrent processing and ensures data consistency.

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.

aopconcurrencyredisspringdistributed-lock
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn 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.