java / expert
Snippet
Distributed Locking with AOP and Redis
Leveraging Aspect-Oriented Programming (AOP) to implement declarative distributed locking. This ensures thread-safety across multiple instances in a microservices environment without polluting business logic with infrastructure concerns.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Aspect@Componentpublic class RedisLockAspect {@Autowiredprivate RedissonClient redisson;@Around("@annotation(distributedLock)")public Object manageLock(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {RLock lock = redisson.getLock(distributedLock.key());if (lock.tryLock(distributedLock.waitTime(), distributedLock.leaseTime(), TimeUnit.SECONDS)) {try {return joinPoint.proceed();} finally {lock.unlock();}}throw new RuntimeException("Could not acquire lock");}}
spring
Breakdown
1
@Around("@annotation(distributedLock)")
Intercepts method execution only for methods annotated with our custom @DistributedLock.
2
lock.tryLock(...)
Attempts to acquire the lock in Redis with specified timeout and lease constraints.
3
joinPoint.proceed()
Executes the original business method only after the lock is successfully acquired.