是為了簡化
SpringBoot
應用的建立、運作、調試、部署等一系列問題而誕生的産物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們隻需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程
Spring
重複送出(分布式)
單機版中我們用的是
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 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.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.lang.reflect.Method;
/**
* redis 方案
*
* @author Levin
* @since 2018/6/12 0012
*/
@Aspect
@Configuration
public class LockMethodInterceptor {
@Autowired
public LockMethodInterceptor(StringRedisTemplate lockRedisTemplate, CacheKeyGenerator cacheKeyGenerator) {
this.lockRedisTemplate = lockRedisTemplate;
this.cacheKeyGenerator = cacheKeyGenerator;
}
private final StringRedisTemplate lockRedisTemplate;
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);
try {
// 采用原生 API 來實作分布式鎖
final Boolean success = lockRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), new byte[0], Expiration.from(lock.expire(), lock.timeUnit()), RedisStringCommands.SetOption.SET_IF_ABSENT));
if (!success) {
// TODO 按理來說 我們應該抛出一個自定義的 CacheLockException 異常;這裡偷下懶
throw new RuntimeException("請勿重複請求");
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("系統異常");
}
} finally {
// TODO 如果示範的話需要注釋該代碼;實際應該放開
// lockRedisTemplate.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輕松搞定全局異常 可以輕松搞定…
第一次請求

正确響應