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

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值