28c61dfeb1d959b9fb20cfc0b88f8f2f38ab9701.svn-base 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package org.jeecg.boot.starter.lock.aspect;
  2. /**
  3. * @author zyf
  4. */
  5. import org.aspectj.lang.ProceedingJoinPoint;
  6. import org.aspectj.lang.annotation.Around;
  7. import org.aspectj.lang.annotation.Aspect;
  8. import org.aspectj.lang.annotation.Pointcut;
  9. import org.aspectj.lang.reflect.MethodSignature;
  10. import org.jeecg.boot.starter.lock.annotation.JRepeat;
  11. import org.jeecg.boot.starter.lock.client.RedissonLockClient;
  12. import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
  13. import org.springframework.stereotype.Component;
  14. import javax.annotation.Resource;
  15. import java.util.Objects;
  16. import java.util.concurrent.TimeUnit;
  17. /**
  18. * 防止重复提交分布式锁拦截器
  19. *
  20. * @author 2019年6月18日
  21. */
  22. @Aspect
  23. @Component
  24. public class RepeatSubmitAspect extends BaseAspect{
  25. @Resource
  26. private RedissonLockClient redissonLockClient;
  27. /***
  28. * 定义controller切入点拦截规则,拦截JRepeat注解的业务方法
  29. */
  30. @Pointcut("@annotation(jRepeat)")
  31. public void pointCut(JRepeat jRepeat) {
  32. }
  33. /**
  34. * AOP分布式锁拦截
  35. *
  36. * @param joinPoint
  37. * @return
  38. * @throws Exception
  39. */
  40. @Around("pointCut(jRepeat)")
  41. public Object repeatSubmit(ProceedingJoinPoint joinPoint,JRepeat jRepeat) throws Throwable {
  42. String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
  43. if (Objects.nonNull(jRepeat)) {
  44. // 获取参数
  45. Object[] args = joinPoint.getArgs();
  46. // 进行一些参数的处理,比如获取订单号,操作人id等
  47. StringBuffer lockKeyBuffer = new StringBuffer();
  48. String key =getValueBySpEL(jRepeat.lockKey(), parameterNames, args,"RepeatSubmit").get(0);
  49. // 公平加锁,lockTime后锁自动释放
  50. boolean isLocked = false;
  51. try {
  52. isLocked = redissonLockClient.fairLock(key, TimeUnit.SECONDS, jRepeat.lockTime());
  53. // 如果成功获取到锁就继续执行
  54. if (isLocked) {
  55. // 执行进程
  56. return joinPoint.proceed();
  57. } else {
  58. // 未获取到锁
  59. throw new Exception("请勿重复提交");
  60. }
  61. } finally {
  62. // 如果锁还存在,在方法执行完成后,释放锁
  63. if (isLocked) {
  64. redissonLockClient.unlock(key);
  65. }
  66. }
  67. }
  68. return joinPoint.proceed();
  69. }
  70. }