一起來學SpringBoot | 第二十三篇:輕鬆搞定重複提交(分散式鎖)
SpringBoot
是為了簡化Spring
應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程
在 一起來學SpringBoot | 第二十二篇:輕鬆搞定重複提交(一) 一文中介紹了單機版的重複提交解決方案,在如今這個分散式與叢集橫行的世道中,那怎麼夠用呢,所以本章重點來了....
重複提交(分散式)
單機版中我們用的是Guava Cache
,但是這玩意存在叢集的時候就涼了,所以我們還是要藉助類似Redis
、ZooKeeper
之類的中介軟體實現分散式鎖。
本章目標
利用 自定義註解
、Spring Aop
、Redis Cache
實現分散式鎖,你想鎖表單鎖表單,想鎖介面鎖介面….
具體程式碼
也很簡單…
匯入依賴
在 pom.xml
中新增上 starter-web
、starter-aop
、starter-data-redis
的依賴即可
<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
相關的配置項
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=battcn
CacheLock 註解
建立一個 CacheLock
註解,本章內容都是實戰使用過的,所以屬性配置會相對完善了,話不多說註釋都給各位寫齊全了….
prefix:
快取中 key 的字首expire:
過期時間,此處預設為 5 秒timeUnit:
超時單位,此處預設為秒delimiter:
key 的分隔符,將不同引數值分割開來
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 的生成規則是自己定義的,如果通過表示式語法自己得去寫解析規則還是比較麻煩的,所以依舊是用註解的方式…
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
具體實現由使用者自己去注入
/**
* key生成器
*
* @author Levin
* @date 2018/03/22
*/
public interface CacheKeyGenerator {
/**
* 獲取AOP引數,生成指定快取Key
*
* @param pjp PJP
* @return 快取KEY
*/
String getLockKey(ProceedingJoinPoint pjp);
}
Key 生成策略(實現)
解析過程雖然看上去優點繞,但認真閱讀或者除錯就會發現,主要是解析帶 CacheLock
註解的屬性,獲取對應的屬性值,生成一個全新的快取 Key
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
我們認為它獲取到鎖了,在鎖未釋放的時候我們進行異常的丟擲….
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 方式呼叫,靈活度更加高
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,如果多個條件則依次類推)
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
介面具體實現…
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
自行測試即可,測試手段相信大夥都不陌生了,如 瀏覽器
、postman
、junit
、swagger
,此處基於 postman
,如果你覺得自帶的異常資訊不夠友好,那麼配上一起來學SpringBoot | 第十八篇:輕鬆搞定全域性異常 可以輕鬆搞定…
第一次請求
第二次請求
總結
目前很多大佬都寫過關於 SpringBoot
的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.2.RELEASE
編寫,包括新版本的特性都會一起介紹…
說點什麼
- 個人QQ:1837307557
- battcn開源群(適合新手):391619659
- 微信公眾號(歡迎調戲):
battcn
相關推薦
一起來學SpringBoot | 第二十三篇:輕鬆搞定重複提交(分散式鎖)
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 在 一起來學S
一起來學SpringBoot | 第十三篇:RabbitMQ延遲佇列
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 初探Rabbi
一起來學SpringBoot | 第二十六篇:輕鬆搞定安全框架(Shiro)
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 Shiro 是
一起來學SpringBoot | 第十九篇:輕鬆搞定資料驗證(一)
SpringBoot是為了簡化Spring應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 對於任何一個
一起來學SpringBoot | 第二篇:SpringBoot配置詳解
文章目錄 自定義屬性配置 自定義檔案配置 多環境化配置 外部命令引導 總結 說點什麼 SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配
SpringBoot第二十三篇:安全性之Spring Security
作者:追夢1819 原文:https://www.cnblogs.com/yanfei1819/p/11350255.html 版權宣告:本文為博主原創文章,轉載請附上博文連結! 引言 系統的安全的重要性人人皆知,其也成為評判系統的重要標準。 Spring Security 是基於 Spring 的
一起來學SpringBoot | 第一篇:構建第一個SpringBoot工程
文章目錄 1. 設計的目標 2. 前提 3. 建立專案 3.1. 目錄結果 3.2. pom.xml 依賴 3.3. 主函式入口 3.4. 初窺配置檔案 3.5. 測試 4. 拓展知識 4.1. 自定義Banner 5. 總結 6. 說點什麼
一起來學SpringBoot | 第十四篇:強大的 actuator 服務監控與管理
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 actuato
一起來學 SpringBoot 2.x | 第七篇:整合 Mybatis
點選上方“芋道原始碼”,選擇“置頂公眾號”技術文章第一時間送達!原始碼精品專欄 摘要: 原創出處
一起來學SpringBoot | 第十一篇:整合Swagger線上除錯
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 隨著網際網路技
一起來學SpringBoot | 第十五篇:actuator與spring-boot-admin 可以說的祕密
SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程 一起來學Spr
轉載:SpringBoot非官方教程 | 第二十三篇: 非同步方法
轉載:https://blog.csdn.net/forezp/article/details/71024169 這篇文章主要介紹在springboot 使用非同步方法,去請求github api. 建立工程 在pom檔案引入相關依賴: <dependency
一起來學SpringBoot ——JDK8 日期格式化
為什麼要用新的日期型別 在 JDK8 中,一個新的重要特性就是引入了全新的時間和日期API,它被收錄在 java.time 包中。藉助新的時間和日期API可以以更簡潔的方法處理時間和日期。 在 JDK8 之前,所有關於時間和日期的API存在以
一起來學SpringBoot(十)快取的使用
Spring Framework支援透明地嚮應用程式新增快取。從本質上講,抽象將快取應用於方法,從而根據快取中可用的資訊減少執行次數。快取邏輯應用透明,不會對呼叫者造成任何干擾。只要通過@EnableCaching 註釋啟用了快取支援,Spring Boot就會
一起來學SpringBoot(十一)定時任務的使用
Quartz是一個功能豐富的開源作業排程庫,幾乎可以整合在任何Java應用程式中 - 從最小的獨立應用程式到最大的電子商務系統。Quartz可用於建立簡單或複雜的計劃,以執行數十,數百甚至數萬個作業; 將任務定義為標準Java元件的作業,這些元件可以執行幾乎任何
一起來學SpringBoot(十六)優雅的整合Shiro
Apache Shiro是一個功能強大且易於使用的Java安全框架,可執行身份驗證,授權,加密和會話管理。藉助Shiro易於理解的API,您可以快速輕鬆地保護任何應用程式 - 從最小的移動應用程式到最大的Web和企業應用程式。網上找到大部分文章都是以前Sprin
一起來學SpringBoot(十五)MybatisPlus的整合
MyBatis-Plus(簡稱 MP)是一個MyBatis的增強工具 ,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。本篇文章介紹的是與springboot的整合。 特性 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,
SpringBoot第十三篇:日誌處理
作者:追夢1819 原文:https://www.cnblogs.com/yanfei1819/p/10973583.html 版權宣告:本文為博主原創文章,轉載請附上博文連結! 引言 日誌是軟體系統的“基礎設施”,它可以幫助我們瞭解系統的執行軌跡,查詢系統的執行異常等。很多人都沒有引起對日誌的重視。
SpringBoot 2.X課程學習 | 第二篇:讓依賴管理更加便捷(Dependency Management)
一、前言 傳統我們搭建SSM專案的時候,使用maven做jar依賴管理的
跟我學SpringCloud | 第十三篇:Spring Cloud Gateway服務化和過濾器
SpringCloud系列教程 | 第十三篇:Spring Cloud Gateway服務化和過濾器 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 如無特殊說明,本系列教程全採用以上版本 上一篇文章服務閘道器 Spring Cloud G