欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

利用redis实现分布式请求防重复提交

发布时间:2025/4/16 编程问答 3 豆豆
生活随笔 收集整理的这篇文章主要介绍了 利用redis实现分布式请求防重复提交 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

1.自定义注解类Token

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Token {String flag() default ""; }

2.在需要拦截的路径上加自定义注解

@Token @RequestMapping(value = "/pda/pick-task/list") public RespJson getPickTask(@RequestParam("whNo") String whNo,@RequestParam(value = "sourceType", required = false) Integer sourceType,@RequestParam(value = "retrieveValue", required = false) String retrieveValue,@RequestParam(value = "realTimePick", required = false, defaultValue = "0") int realTimePick,@RequestParam(value = "taskGroupNo", required = false) String taskGroupNo) { ...

3.利用切面拦截请求

@Aspect @Component public class MethodInterceptor {private Logger logger = LoggerFactory.getLogger(MethodInterceptor.class); /*** 重复请求拦截** @param joinPoint* @return* @throws Throwable*/ @Around("@annotation(com.haiziwang.kwms.common.annotation.Token)") public Object repeatRequestAround(ProceedingJoinPoint joinPoint) throws Throwable {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();Method currentMethod = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());IKMEMCache cache = KMemServiceImpl.getCache();//拼接签名StringBuilder signBuffer = new StringBuilder(currentMethod.getAnnotation(RequestMapping.class).value()[0]);Object[] args = joinPoint.getArgs();for (Object object : args) {if (object != null) {String str = "";try {str = JSONObject.toJSONString(object);} catch (Exception e) {}signBuffer.append("^").append(str);}}String tokenKey = signBuffer.toString();if (StringUtils.isNotBlank(cache.readFromHash(RedisKeyType.TOKEN.getName(), tokenKey))) {if (StringConstants.WCS.equals(currentMethod.getAnnotation(Token.class).flag())) {throw new WMS3CheckedException(WMS3ExceptionCode.WCS_REPEAT_REQUEST_EXCEPTION);}if (currentMethod.getReturnType() == RespJson.class) {throw new WMS3CheckedException(WMS3ExceptionCode.REPEAT_REQUEST_EXCEPTION);}if (currentMethod.getReturnType() == PageRespJson.class) {throw new WMS3CheckedException(WMS3ExceptionCode.REPEAT_REQUEST_PAGE_EXCEPTION);}}cache.write4Hash(RedisKeyType.TOKEN.getName(), tokenKey, "token");try {return joinPoint.proceed();} finally {cache.deleteHashFields(RedisKeyType.TOKEN.getName(), tokenKey);} }

 

转载于:https://my.oschina.net/u/2485283/blog/1859323

总结

以上是生活随笔为你收集整理的利用redis实现分布式请求防重复提交的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。