Java 项目 Redis处理接口重复并发请求

一、项目描述

		在Java后台开发的小伙伴,都会面临接口被重复请求,生成了脏数据,对数据的统计,查询都会造成错乱。

二、解决方案

		通过Java Aop 拦截请求的Url,将请求的url 保存在redis 缓存中,当重复访问时,判断Redis 中是否存在该请求。

三、代码示例

	1.创建一个拦截注解
	@Inherited
	@Target(ElementType.METHOD)
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	public @interface RepeatSubmit {
	
	    // 当前名称
	    String name() default "";
	    // 默认延时
	    String delay() default "1L";
	}
   2.对重复的请求进行拦截处理
	@Aspect
	@Component
	@Slf4j
	public class RepeatAop {
	
	   @Pointcut("@annotation(com.linln.component.actionLog.annotation.RepeatSubmit)")
	   public void getRepeatSubmit() {
	   }
	
	   @Before(value = "getRepeatSubmit()")
	   public void getSubmit(JoinPoint joinPoint) {
	
	       RequestAttributes ra = RequestContextHolder.getRequestAttributes();
	       ServletRequestAttributes sra = (ServletRequestAttributes) ra;
	       assert sra != null;
	       HttpServletRequest request = sra.getRequest();
	       String url = request.getRequestURL().toString();
	       String method = request.getMethod();
	       String queryString = request.getQueryString();
	       long startTime = System.currentTimeMillis();
	       log.info("{url:{}, method:{}, queryString:{}}", url, method, queryString);
	
	       MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	       Method targetMethod = ((MethodSignature)(joinPoint.getSignature())).getMethod();
	
	       com.linln.component.actionLog.annotation.RepeatSubmit anno =
	               targetMethod.getAnnotation(com.linln.component.actionLog.annotation.RepeatSubmit.class);
	
	       // 组建请求链接
	       String key = url + method + queryString;
	       // 获取延时的值
	       String delay = anno.delay();
			 synchronized (this){
			   RedisUtils redisUtils = SpringContextUtil.getBean(RedisUtils.class);
		       if (redisUtils.hasKey(key)) {
		           throw new ResultException(ResultEnum.NO_REPEATING_REQ);
		       }
		       System.out.println(signature.getName());
		       Map<String, Object> map = new HashMap<>();
		       map.put(key, "Cache-" + key);
		       redisUtils.hmset(key, map, Long.parseLong(delay));
	       }
	   }
     3.对有拦截需要的接口添加注解
    @PostMapping("register")
    @ResponseBody
    @RepeatSubmit(delay = "1") // 1秒内禁止重复请求
    public String registerAccount(@Validated User user, User user) {
    	 userService.save(user);
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值