Implementing a Distributed Redis Lock with Spring AOP and Automatic Renewal
This article explains how to protect time‑consuming business operations by using Redis as a distributed lock, designing a custom @RedisLock annotation, applying Spring AOP to intercept methods, handling lock acquisition, expiration, renewal via a ScheduledExecutorService, and releasing the lock safely after execution.
Some business requests are time‑consuming and require locking to prevent concurrent operations that could corrupt data.
Redis is used as a distributed lock, storing the lock state centrally to solve the problem of JVM isolation in a cluster.
The design process includes creating a custom annotation @RedisLockAnnotation, adding an AOP pointcut to scan this annotation, and implementing an @Aspect that registers a bean and intercepts the target method.
Core steps are lock acquisition, lock release, and lock renewal.
Lock acquisition uses RedisTemplate.opsForValue().setIfAbsent with a UUID value and sets an expiration time; only the first request that successfully sets the key proceeds with the business logic.
To avoid premature expiration when the business method runs longer than the lock timeout, a scheduled thread pool periodically checks pending tasks and extends the lock expiration before it expires.
private static final ScheduledExecutorService SCHEDULER =
new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder()
.namingPattern("redisLock-schedule-pool")
.daemon(true)
.build());
static {
SCHEDULER.scheduleAtFixedRate(() -> {
// iterate holderList, extend expiration if needed
}, 0, 2, TimeUnit.SECONDS);
}The lock type enum defines business‑specific prefixes:
public enum RedisLockTypeEnum {
ONE("Business1", "Test1"),
TWO("Business2", "Test2");
private String code;
private String desc;
// getters and utility methods
}A holder class stores lock metadata such as business key, lock time, last modify time, thread reference, and retry counters:
public class RedisLockDefinitionHolder {
private String businessKey;
private Long lockTime;
private Long lastModifyTime;
private Thread currentThread;
private int tryCount;
private int currentCount;
private Long modifyPeriod;
// constructor and getters/setters
}The annotation definition specifies lock field index, retry count, lock type, and lock duration:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RedisLockAnnotation {
int lockFiled() default 0;
int tryCount() default 3;
RedisLockTypeEnum typeEnum();
long lockTime() default 30;
}The aspect defines the pointcut and the around advice that performs lock acquisition, adds the task to the renewal queue, executes the business method, and finally releases the lock:
@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")
public void redisLockPC() {}
@Around("redisLockPC()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Method method = resolveMethod(pjp);
RedisLockAnnotation annotation = method.getAnnotation(RedisLockAnnotation.class);
// resolve key, acquire lock, set expiration, add to holderList
Object result = pjp.proceed();
// release lock in finally block
return result;
}Testing is done by annotating a controller method with
@RedisLockAnnotation(typeEnum = RedisLockTypeEnum.ONE, lockTime = 3)and simulating a long‑running task with Thread.sleep(10000). Log output shows the lock being acquired, renewed three times, and finally released when the retry limit is reached.
The conclusion emphasizes that distributed locks are essential for protecting critical data in long‑running operations, and that automatic renewal prevents premature lock release.
References include the original GitHub source and several related articles.
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.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.
