輕松搞定重復提交(分布式鎖)


SpringBoot 是為了簡化 Spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規范,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

在 一起來學SpringBoot | 第二十二篇:輕松搞定重復提交(一) 一文中介紹了單機版的重復提交解決方案,在如今這個分布式與集群橫行的世道中,那怎么夠用呢,所以本章重點來了....

重復提交(分布式)

單機版中我們用的是Guava Cache,但是這玩意存在集群的時候就涼了,所以我們還是要借助類似RedisZooKeeper 之類的中間件實現分布式鎖。

本章目標

利用 自定義注解Spring AopRedis Cache 實現分布式鎖,你想鎖表單鎖表單,想鎖接口鎖接口….

具體代碼

也很簡單…

導入依賴

在 pom.xml 中添加上 starter-webstarter-aopstarter-data-redis 的依賴即可

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

屬性配置

在 application.properites 資源文件中添加 redis 相關的配置項

1
2
3
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=battcn

CacheLock 注解

創建一個 CacheLock 注解,本章內容都是實戰使用過的,所以屬性配置會相對完善了,話不多說注釋都給各位寫齊全了….

  • prefix: 緩存中 key 的前綴
  • expire: 過期時間,此處默認為 5 秒
  • timeUnit: 超時單位,此處默認為秒
  • delimiter: key 的分隔符,將不同參數值分割開來
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.battcn.annotation;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
* @author Levin
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheLock {

/**
* redis 鎖key的前綴
*
* @return redis 鎖key的前綴
*/
String prefix() default "";

/**
* 過期秒數,默認為5秒
*
* @return 輪詢鎖的時間
*/
int expire() default 5;

/**
* 超時時間單位
*
* @return 秒
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;

/**
* <p>Key的分隔符(默認 :)</p>
* <p>生成的Key:N:SO1008:500</p>
*
* @return String
*/
String delimiter() default ":";
}

CacheParam 注解

上一篇中給說過 key 的生成規則是自己定義的,如果通過表達式語法自己得去寫解析規則還是比較麻煩的,所以依舊是用注解的方式…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.battcn.annotation;

import java.lang.annotation.*;

/**
* 鎖的參數
*
* @author Levin
*/
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheParam {

/**
* 字段名稱
*
* @return String
*/
String name() default "";
}

Key 生成策略(接口)

創建一個 CacheKeyGenerator 具體實現由使用者自己去注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* key生成器
*
* @author Levin
* @date 2018/03/22
*/
public interface CacheKeyGenerator {

/**
* 獲取AOP參數,生成指定緩存Key
*
* @param pjp PJP
* @return 緩存KEY
*/
String getLockKey(ProceedingJoinPoint pjp);
}

Key 生成策略(實現)

解析過程雖然看上去優點繞,但認真閱讀或者調試就會發現,主要是解析帶 CacheLock 注解的屬性,獲取對應的屬性值,生成一個全新的緩存 Key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.battcn.interceptor;

import com.battcn.annotation.CacheLock;
import com.battcn.annotation.CacheParam;
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;

/**
* 上一章說過通過接口注入的方式去寫不同的生成規則;
* @author Levin
* @since 2018/6/13 0026
*/
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();
// TODO 默認解析方法里面帶 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.battcn.interceptor;

import com.battcn.annotation.CacheLock;
import com.battcn.utils.RedisLockHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.UUID;

/**
* redis 方案
*
* @author Levin
* @since 2018/6/12 0012
*/
@Aspect
@Configuration
public class LockMethodInterceptor {

@Autowired
public LockMethodInterceptor(RedisLockHelper redisLockHelper, CacheKeyGenerator cacheKeyGenerator) {
this.redisLockHelper = redisLockHelper;
this.cacheKeyGenerator = cacheKeyGenerator;
}

private final RedisLockHelper redisLockHelper;
private final CacheKeyGenerator cacheKeyGenerator;


@Around("execution(public * *(..)) && @annotation(com.battcn.annotation.CacheLock)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
CacheLock lock = method.getAnnotation(CacheLock.class);
if (StringUtils.isEmpty(lock.prefix())) {
throw new RuntimeException("lock key don't null...");
}
final String lockKey = cacheKeyGenerator.getLockKey(pjp);
String value = UUID.randomUUID().toString();
try {
// 假設上鎖成功,但是設置過期時間失效,以后拿到的都是 false
final boolean success = redisLockHelper.lock(lockKey, value, lock.expire(), lock.timeUnit());
if (!success) {
throw new RuntimeException("重復提交");
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("系統異常");
}
} finally {
// TODO 如果演示的話需要注釋該代碼;實際應該放開
redisLockHelper.unlock(lockKey, value);
}
}
}

RedisLockHelper

通過封裝成 API 方式調用,靈活度更加高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.battcn.utils;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.util.StringUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
* 需要定義成 Bean
*
* @author Levin
* @since 2018/6/15 0015
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisLockHelper {


private static final String DELIMITER = "|";

/**
* 如果要求比較高可以通過注入的方式分配
*/
private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10);

private final StringRedisTemplate stringRedisTemplate;

public RedisLockHelper(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}

/**
* 獲取鎖(存在死鎖風險)
*
* @param lockKey lockKey
* @param value value
* @param time 超時時間
* @param unit 過期單位
* @return true or false
*/
public boolean tryLock(final String lockKey, final String value, final long time, final TimeUnit unit) {
return stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), value.getBytes(), Expiration.from(time, unit), RedisStringCommands.SetOption.SET_IF_ABSENT));
}

/**
* 獲取鎖
*
* @param lockKey lockKey
* @param uuid UUID
* @param timeout 超時時間
* @param unit 過期單位
* @return true or false
*/
public boolean lock(String lockKey, final String uuid, long timeout, final TimeUnit unit) {
final long milliseconds = Expiration.from(timeout, unit).getExpirationTimeInMilliseconds();
boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid);
if (success) {
stringRedisTemplate.expire(lockKey, timeout, TimeUnit.SECONDS);
} else {
String oldVal = stringRedisTemplate.opsForValue().getAndSet(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid);
final String[] oldValues = oldVal.split(Pattern.quote(DELIMITER));
if (Long.parseLong(oldValues[0]) + 1 <= System.currentTimeMillis()) {
return true;
}
}
return success;
}


/**
* @see <a href="http://redis.io/commands/set">Redis Documentation: SET</a>
*/
public void unlock(String lockKey, String value) {
unlock(lockKey, value, 0, TimeUnit.MILLISECONDS);
}

/**
* 延遲unlock
*
* @param lockKey key
* @param uuid client(最好是唯一鍵的)
* @param delayTime 延遲時間
* @param unit 時間單位
*/
public void unlock(final String lockKey, final String uuid, long delayTime, TimeUnit unit) {
if (StringUtils.isEmpty(lockKey)) {
return;
}
if (delayTime <= 0) {
doUnlock(lockKey, uuid);
} else {
EXECUTOR_SERVICE.schedule(() -> doUnlock(lockKey, uuid), delayTime, unit);
}
}

/**
* @param lockKey key
* @param uuid client(最好是唯一鍵的)
*/
private void doUnlock(final String lockKey, final String uuid) {
String val = stringRedisTemplate.opsForValue().get(lockKey);
final String[] values = val.split(Pattern.quote(DELIMITER));
if (values.length <= 0) {
return;
}
if (uuid.equals(values[1])) {
stringRedisTemplate.delete(lockKey);
}
}

}

控制層

在接口上添加 @CacheLock(prefix = "books"),然后動態的值可以加上@CacheParam;生成后的新 key 將被緩存起來;(如:該接口 token = 1,那么最終的 key 值為 books:1,如果多個條件則依次類推

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.battcn.controller;

import com.battcn.annotation.CacheLock;
import com.battcn.annotation.CacheParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
* BookController
*
* @author Levin
* @since 2018/6/06 0031
*/
@RestController
@RequestMapping("/books")
public class BookController {

@CacheLock(prefix = "books")
@GetMapping
public String query(@CacheParam(name = "token") @RequestParam String token) {
return "success - " + token;
}

}

主函數

這里需要注入前面定義好的 CacheKeyGenerator 接口具體實現…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.battcn;

import com.battcn.interceptor.CacheKeyGenerator;
import com.battcn.interceptor.LockKeyGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;


/**
* @author Levin
*/
@SpringBootApplication
public class Chapter22Application {

public static void main(String[] args) {

SpringApplication.run(Chapter22Application.class, args);

}

@Bean
public CacheKeyGenerator cacheKeyGenerator() {
return new LockKeyGenerator();
}

}

測試

完成准備事項后,啟動 Chapter22Application 自行測試即可,測試手段相信大伙都不陌生了,如 瀏覽器postmanjunitswagger,此處基於 postman,如果你覺得自帶的異常信息不夠友好,那么配上一起來學SpringBoot | 第十八篇:輕松搞定全局異常 可以輕松搞定…

第一次請求

正確響應

正確響應

第二次請求

錯誤響應

錯誤響應


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM