Based on SpringBoot AOP aspect oriented programming implementation Redis distributed lock based on SpringBoot AOP aspect oriented programming implementation Redis distributed lock

The goal of locking is to ensure that the resources they access are mutually exclusive. In fact, this resource is usually a string. Locking with Redis is primarily about putting resources into Redis and taking advantage of its atomicity. If the resource already exists in Redis when accessed by another thread, certain subsequent operations are not allowed.

Spring Boot uses Redis with the RedisTemplate, and in practice, distributed locks can be used at the method level after encapsulation, making it easier to use without having to go around fetching and releasing locks.

First, define an annotation:

@target ({elementtype.method}) @Retention(retentionPolicy.runtime) @Inherited Public @interface RedisLock {// Inherited resources, Redis key String value() default" default"; // Lock hold time (in milliseconds) long keepMills() default 30000; // Operation performed on failure LockFailAction Action () Default lockfailAction.continue; Public enum LockFailAction{GIVEUP, CONTINUE; } // Long sleepMills() default 200; Int retryTimes() default 5; }Copy the code

Beans with distributed locks

@Configuration 
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class DistributedLockAutoConfiguration {    
    @Bean    
    @ConditionalOnBean(RedisTemplate.class)    
    public DistributedLock redisDistributedLock(RedisTemplate redisTemplate){       
        return new RedisDistributedLock(redisTemplate);   
    }
}Copy the code

Programming for facets – Define facets

@Aspect @Configuration @ConditionalOnClass(DistributedLock.class) @AutoConfigureAfter(DistributedLockAutoConfiguration.class) public class DistributedLockAspectConfiguration { private final Logger logger = LoggerFactory.getLogger(DistributedLockAspectConfiguration.class); @Autowired private DistributedLock distributedLock; @Pointcut("@annotation(com.itopener.lock.redis.spring.boot.autoconfigure.annotations.RedisLock)") private void lockPoint(){ } @Around("lockPoint()") public Object around(ProceedingJoinPoint pjp) throws Throwable{ Method method = ((MethodSignature) pjp.getSignature()).getMethod(); RedisLock redisLock = method.getAnnotation(RedisLock.class); String key = redisLock.value(); if(StringUtils.isEmpty(key)){ Object\[\] args = pjp.getArgs(); key = Arrays.toString(args); } int retryTimes = redisLock.action().equals(LockFailAction.CONTINUE) ? redisLock.retryTimes() : 0; Boolean lock = distributedLock.lock(key, redislock. keepMills(), retryTimes, redislock. sleepMills()); if(! lock) { logger.debug("get lock failed : " + key); return null; } // Release the distributed lock logger.debug("get lock success: "+ key); try { return pjp.proceed(); } catch (Exception e) {logger.error("execute locked method occured an Exception ", e); } finally { boolean releaseResult = distributedLock.releaseLock(key); Logger. debug("release Lock :" + key + (releaseResult?" success" :" failed")); } return null; }}Copy the code

Method of use

  • When entering this method, the distributed lock is occupied,
  • The distributed lock is released when the method completes execution
  • Use multiple functions of the same resource, such as your-custom-service-redis-key, to preempt the same lock. Whoever grabs it gets the first shot.
@redislock (value="your-custom-service-redis-key") public void serviceMethod(){Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series