Springboot2.x AOP 实现缓存锁,分布式锁
IT科技 2025-10-06 13:08:32
0
Springboot2.x AOP 实现 缓存锁,分布式锁 分布式锁 防止重复提交
本人深根后台系统多年的实现锁经验;用户在网络不好情况下; 在做表单提交时;会出现重复提交的情况;故而我们需要:做到防止表单重提
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 后续讲解) * * @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; } }上面的香港云服务器基本都是居于内存级别的缓存;在分布式系统上; 是无法满足的;故而我们需要做到分布式系统中;也能使用
基于Redis 缓存锁的实现
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> spring.redis.host=localhost spring.redis.port=6379RedisLock
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 dont 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); } } }请求
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(); } 云南idc服务商