1. 程式人生 > >分散式的redis鎖

分散式的redis鎖

    springboot2本地鎖實踐一文中提到用Guava Cache實現鎖機制,但在叢集中就行不通了,所以我們還一般要藉助類似Redis、ZooKeeper 之類的中介軟體實現分散式鎖,下面我們將利用自定義註解Spring AopRedis Cache 實現分散式鎖。

專案程式碼結構整體圖

一、匯入依賴

在 pom.xml 中新增上 starter-webstarter-aopstarter-data-redis 的依賴

複製程式碼

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework.boot</groupId>
 4         <artifactId>spring-boot-starter-web</artifactId>
 5     </dependency>
 6     <dependency>
 7         <groupId>org.springframework.boot</groupId>
 8         <artifactId>spring-boot-starter-aop</artifactId>
 9     </dependency>
10     <dependency>
11         <groupId>org.springframework.boot</groupId>
12         <artifactId>spring-boot-starter-data-redis</artifactId>
13     </dependency>
14 </dependencies>

複製程式碼

二、屬性配置

在 application.properites 資原始檔中新增 redis 相關的配置項

spring.redis.host=192.168.68.110
spring.redis.port=6379
spring.redis.password=123456

三、註解

1、建立一個 CacheLock 註解,屬性配置如下

  • prefix: 快取中 key 的字首
  • expire: 過期時間,此處預設為 5 秒
  • timeUnit: 超時單位,此處預設為秒
  • delimiter: key 的分隔符,將不同引數值分割開來

複製程式碼

 1 import java.lang.annotation.*;
 2 import java.util.concurrent.TimeUnit;
 3 
 4 /**
 5  * 鎖的註解
 6  */
 7 @Target(ElementType.METHOD)
 8 @Retention(RetentionPolicy.RUNTIME)
 9 @Documented
10 @Inherited
11 public @interface CacheLock {
12 
13     /**
14      * redis 鎖key的字首
15      *
16      * @return redis 鎖key的字首
17      */
18     String prefix() default "";
19 
20     /**
21      * 過期秒數,預設為5秒
22      *
23      * @return 輪詢鎖的時間
24      */
25     int expire() default 5;
26 
27     /**
28      * 超時時間單位
29      *
30      * @return 秒
31      */
32     TimeUnit timeUnit() default TimeUnit.SECONDS;
33 
34     /**
35      * <p>Key的分隔符(預設 :)</p>
36      * <p>生成的Key:N:SO1008:500</p>
37      *
38      * @return String
39      */
40     String delimiter() default ":";
41 }

複製程式碼

2、 key 的生成規則是自己定義的,如果通過表示式語法自己得去寫解析規則還是比較麻煩的,所以依舊是用註解的方式

複製程式碼

 1 import java.lang.annotation.*;
 2 
 3 /**
 4  * 鎖的引數
 5  *
 6  */
 7 @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
 8 @Retention(RetentionPolicy.RUNTIME)
 9 @Documented
10 @Inherited
11 public @interface CacheParam {
12 
13     /**
14      * 欄位名稱
15      *
16      * @return String
17      */
18     String name() default "";
19 }

複製程式碼

四、Key生成策略

1、介面

複製程式碼

 1 import org.aspectj.lang.ProceedingJoinPoint;
 2 
 3 /**
 4  * key生成器
 5  */
 6 public interface CacheKeyGenerator {
 7 
 8     /**
 9      * 獲取AOP引數,生成指定快取Key
10      *
11      * @param pjp PJP
12      * @return 快取KEY
13      */
14     String getLockKey(ProceedingJoinPoint pjp);
15 }

複製程式碼

2、介面實現

複製程式碼

import com.carry.annotation.CacheLock;
import com.carry.annotation.CacheParam;
import com.carry.common.CacheKeyGenerator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 通過介面注入的方式去寫不同的生成規則;
 */
public class LockKeyGenerator implements CacheKeyGenerator {

    @Override
    public String getLockKey(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        CacheLock lockAnnotation = method.getAnnotation(CacheLock.class);
        final Object[] args = pjp.getArgs();
        final Parameter[] parameters = method.getParameters();
        StringBuilder builder = new StringBuilder();
        //預設解析方法裡面帶 CacheParam 註解的屬性,如果沒有嘗試著解析實體物件中的
        for (int i = 0; i < parameters.length; i++) {
            final CacheParam annotation = parameters[i].getAnnotation(CacheParam.class);
            if (annotation == null) {
                continue;
            }
            builder.append(lockAnnotation.delimiter()).append(args[i]);
        }
        if (StringUtils.isEmpty(builder.toString())) {
            final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < parameterAnnotations.length; i++) {
                final Object object = args[i];
                final Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    final CacheParam annotation = field.getAnnotation(CacheParam.class);
                    if (annotation == null) {
                        continue;
                    }
                    field.setAccessible(true);
                    builder.append(lockAnnotation.delimiter()).append(ReflectionUtils.getField(field, object));
                }
            }
        }
        return lockAnnotation.prefix() + builder.toString();
    }
}

複製程式碼

五、Lock攔截器(AOP)

熟悉 Redis 的朋友都知道它是執行緒安全的,我們利用它的特性可以很輕鬆的實現一個分散式鎖,如 opsForValue().setIfAbsent(key,value)它的作用就是如果快取中沒有當前 Key 則進行快取同時返回 true 反之亦然;當快取後給 key 在設定個過期時間,防止因為系統崩潰而導致鎖遲遲不釋放形成死鎖; 那麼我們是不是可以這樣認為當返回 true 我們認為它獲取到鎖了,在鎖未釋放的時候我們進行異常的丟擲….

複製程式碼

 1 import com.carry.annotation.CacheLock;
 2 import com.carry.common.CacheKeyGenerator;
 3 import org.aspectj.lang.ProceedingJoinPoint;
 4 import org.aspectj.lang.annotation.Around;
 5 import org.aspectj.lang.annotation.Aspect;
 6 import org.aspectj.lang.reflect.MethodSignature;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.data.redis.core.StringRedisTemplate;
10 import org.springframework.util.StringUtils;
11 
12 import java.lang.reflect.Method;
13 
14 /**
15  * redis 方案
16  */
17 @Aspect
18 @Configuration
19 public class LockMethodInterceptor {
20 
21     @Autowired
22     public LockMethodInterceptor(StringRedisTemplate lockRedisTemplate, CacheKeyGenerator cacheKeyGenerator) {
23         this.lockRedisTemplate = lockRedisTemplate;
24         this.cacheKeyGenerator = cacheKeyGenerator;
25     }
26 
27     private final StringRedisTemplate lockRedisTemplate;
28     private final CacheKeyGenerator cacheKeyGenerator;
29 
30 
31     @Around("execution(public * *(..)) && @annotation(com.carry.annotation.CacheLock)")
32     public Object interceptor(ProceedingJoinPoint pjp) {
33         MethodSignature signature = (MethodSignature) pjp.getSignature();
34         Method method = signature.getMethod();
35         CacheLock lock = method.getAnnotation(CacheLock.class);
36         if (StringUtils.isEmpty(lock.prefix())) {
37             throw new RuntimeException("lock key can't be null...");
38         }
39         final String lockKey = cacheKeyGenerator.getLockKey(pjp);
40         try {
41             //key不存在才能設定成功
42             final Boolean success = lockRedisTemplate.opsForValue().setIfAbsent(lockKey, "");
43             if (success) {
44                 lockRedisTemplate.expire(lockKey, lock.expire(), lock.timeUnit());
45             } else {
46                 //按理來說 我們應該丟擲一個自定義的 CacheLockException 異常;
47                 throw new RuntimeException("請勿重複請求");
48             }
49             try {
50                 return pjp.proceed();
51             } catch (Throwable throwable) {
52                 throw new RuntimeException("系統異常");
53             }
54         } finally {
55             //如果演示的話需要註釋該程式碼;實際應該放開
56             // lockRedisTemplate.delete(lockKey);
57         }
58     }
59 }

複製程式碼

六、控制層

在介面方法上新增 @CacheLock(prefix = "test"),然後動態的值可以加上@CacheParam;生成後的新 key 將被快取起來;(如:該介面 token = 1,那麼最終的 key 值為 test:1,如果多個條件則依次類推)

複製程式碼

 1 import com.carry.annotation.CacheLock;
 2 import com.carry.annotation.CacheParam;
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RequestParam;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 @RestController
 8 public class LockController {
 9 
10     @CacheLock(prefix = "test")
11     @GetMapping("/test")
12     public String query(@CacheParam(name = "token") @RequestParam String token) {
13         return "success - " + token;
14     }
15 
16 }

複製程式碼

七、主函式

需要注入前面定義好的 CacheKeyGenerator 介面具體實現…

複製程式碼

 1 import com.carry.common.CacheKeyGenerator;
 2 import com.carry.common.LockKeyGenerator;
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.context.annotation.Bean;
 6 
 7 @SpringBootApplication
 8 public class SpringbootCacheRedislockApplication {
 9 
10     public static void main(String[] args) {
11         SpringApplication.run(SpringbootCacheRedislockApplication.class, args);
12     }
13 
14     @Bean
15     public CacheKeyGenerator cacheKeyGenerator() {
16         return new LockKeyGenerator();
17     }
18 }

複製程式碼

八、測試

第一次請求結果:

第二次請求結果:

等key過期了請求又恢復正常。