Springboot2.x AOP 實現緩存鎖,分布式鎖
作者:西西文
本人深根后臺系統(tǒng)多年的經驗;用戶在網絡不好情況下; 在做表單提交時;會出現重復提交的情況;故而我們需要:做到防止表單重提。
Springboot2.x AOP 實現 緩存鎖, 分布式鎖 防止重復提交
本人深根后臺系統(tǒng)多年的經驗;用戶在網絡不好情況下; 在做表單提交時;會出現重復提交的情況;故而我們需要:做到防止表單重提
google的guave cache
- <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>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>21.0</version>
- </dependency>
注解接口
- package com.ouyue.xiwenapi.annotation;
- import java.lang.annotation.*;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- public @interface GuaveLock
- {
- String key() default "";
- /**
- * 過期時間 TODO 由于用的 guava 暫時就忽略這屬性吧 集成 redis 需要用到
- *
- * @author fly
- */
- int expire() default 5;
- }
AOP的運用
- package com.ouyue.xiwenapi.config;
- import com.google.common.cache.Cache;
- import com.google.common.cache.CacheBuilder;
- import com.ouyue.xiwenapi.annotation.GuaveLock;
- 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.context.annotation.Configuration;
- import org.springframework.util.StringUtils;
- import java.lang.reflect.Method;
- import java.util.concurrent.TimeUnit;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @Aspect
- @Configuration
- public class LockMethodAopConfigure {
- private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
- // 最大緩存 100 個
- .maximumSize(1000)
- // 設置寫緩存后 5 秒鐘過期
- .expireAfterWrite(5, TimeUnit.SECONDS)
- .build();
- @Around("execution(public * *(..)) && @annotation(com.ouyue.xiwenapi.annotation.GuaveLock)")
- public Object interceptor(ProceedingJoinPoint pjp) {
- MethodSignature signature = (MethodSignature) pjp.getSignature();
- Method method = signature.getMethod();
- GuaveLock localLock = method.getAnnotation(GuaveLock.class);
- String key = getKey(localLock.key(), pjp.getArgs());
- if (!StringUtils.isEmpty(key)) {
- if (CACHES.getIfPresent(key) != null) {
- throw new RuntimeException("請勿重復請求");
- }
- // 如果是第一次請求,就將 key 當前對象壓入緩存中
- CACHES.put(key, key);
- }
- try {
- return pjp.proceed();
- } catch (Throwable throwable) {
- throw new RuntimeException("服務器異常");
- } finally {
- // TODO 為了演示效果,這里就不調用 CACHES.invalidate(key); 代碼了
- }
- }
- /**
- * key 的生成策略,如果想靈活可以寫成接口與實現類的方式(TODO 后續(xù)講解)
- *
- * @param keyExpress 表達式
- * @param args 參數 可以 采用MD5加密成一個
- * @return 生成的key
- */
- private String getKey(String keyExpress, Object[] args) {
- for (int i = 0; i < args.length; i++) {
- keyExpress = keyExpress.replace("arg[" + i + "]", args[i].toString());
- }
- return keyExpress;
- }
- }
Controller
- @RestController
- @RequestMapping("/business")
- public class BusinessController {
- @GuaveLock(key = "business:arg[0]")
- @GetMapping
- public String query(@RequestParam String token) {
- return "success - " + token;
- }
- }
上面的基本都是居于內存級別的緩存;在分布式系統(tǒng)上; 是無法滿足的;故而我們需要做到分布式系統(tǒng)中;也能使用
基于Redis 緩存鎖的實現
pom.xml
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- spring.redis.host=localhost
- spring.redis.port=6379
RedisLock
- prefix: 緩存中 key 的前綴
- expire: 過期時間,此處默認為 5 秒
- timeUnit: 超時單位,此處默認為秒
- delimiter: key 的分隔符,將不同參數值分割開來
- package com.ouyue.xiwenapi.annotation;
- import java.lang.annotation.*;
- import java.util.concurrent.TimeUnit;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- public @interface RedisLock {
- /**
- * 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 注解
- package com.ouyue.xiwenapi.annotation;
- import java.lang.annotation.*;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- public @interface CacheParam {
- /**
- * 字段名稱
- *
- * @return String
- */
- String name() default "";
- }
Key 生成策略
- package com.ouyue.xiwenapi.componet;
- import org.aspectj.lang.ProceedingJoinPoint;
- public interface CacheKeyGenerator {
- /**
- * 獲取AOP參數,生成指定緩存Key
- *
- * @param pjp PJP
- * @return 緩存KEY
- */
- String getLockKey(ProceedingJoinPoint pjp);
- }
Key 生成策略(實現)
- package com.ouyue.xiwenapi.service;
- import com.ouyue.xiwenapi.annotation.CacheParam;
- import com.ouyue.xiwenapi.annotation.RedisLock;
- import com.ouyue.xiwenapi.componet.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;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- public class LockKeyGenerator implements CacheKeyGenerator {
- @Override
- public String getLockKey(ProceedingJoinPoint pjp) {
- MethodSignature signature = (MethodSignature) pjp.getSignature();
- Method method = signature.getMethod();
- RedisLock lockAnnotation = method.getAnnotation(RedisLock.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)
- package com.ouyue.xiwenapi.config;
- import com.ouyue.xiwenapi.annotation.RedisLock;
- import com.ouyue.xiwenapi.componet.CacheKeyGenerator;
- 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;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @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.ouyue.xiwenapi.annotation.RedisLock)")
- public Object interceptor(ProceedingJoinPoint pjp) {
- MethodSignature signature = (MethodSignature) pjp.getSignature();
- Method method = signature.getMethod();
- RedisLock lock = method.getAnnotation(RedisLock.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("系統(tǒng)異常");
- }
- } finally {
- // TODO 如果演示的話需要注釋該代碼;實際應該放開
- // lockRedisTemplate.delete(lockKey);
- }
- }
- }
請求
- package com.ouyue.xiwenapi.controller;
- import com.ouyue.xiwenapi.annotation.CacheParam;
- import com.ouyue.xiwenapi.annotation.GuaveLock;
- import com.ouyue.xiwenapi.annotation.RedisLock;
- 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;
- /**
- * @ClassName:${}
- * @Description:TODO
- * @author:xx@163.com
- * @Date:
- */
- @RestController
- @RequestMapping("/business")
- public class BusinessController {
- @GuaveLock(key = "business:arg[0]")
- @GetMapping
- public String query(@RequestParam String token) {
- return "success - " + token;
- }
- @RedisLock(prefix = "users")
- @GetMapping
- public String queryRedis(@CacheParam(name = "token") @RequestParam String token) {
- return "success - " + token;
- }
- }
mian 函數啟動類上;將key 生產策略函數注入
- @Bean
- public CacheKeyGenerator cacheKeyGenerator() {
- return new LockKeyGenerator();
- }
責任編輯:武曉燕
來源:
今日頭條