基于自定义注解、切面实现防止重复提交

自定义注解:


import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD, ElementType.TYPE })
public @interface RepeatSubmit {

	/**
	 * 锁定毫秒数
	 * @return
	 */
	int lockMillis() default 1000;
	
	/**
	 * Key的组合方式
	 * @return
	 */
	RepeatKeyMode[] keyMode() default { RepeatKeyMode.SESSIONID,RepeatKeyMode.TOKEN,RepeatKeyMode.VALUE };
	
	/**
	 * 提示信息
	 * @return
	 */
	String message() default "请勿重复请求";
}

Key组合方式枚举:

public enum RepeatKeyMode {
	TOKEN, SESSIONID, VALUE
}

防止重复提交切面:

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class RepeatSubmitAspect {
	
	// 单服务部署可以使用这个,集群部署可以直接用redis
	private ConcurrentMapCache cache = new ConcurrentMapCache();
	
	@Around(value = "@annotation(repeatSubmit)" , argNames="joinPoint,repeatSubmit")
	public Object around(ProceedingJoinPoint joinPoint, RepeatSubmit repeatSubmit) throws Throwable {
		
		int lockMillis = repeatSubmit.lockMillis();
		
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
		StringBuffer keyBuffer = new StringBuffer(request.getServletPath() + ";");
		
		RepeatKeyMode[] keyModes = repeatSubmit.keyMode();
		
		for ( RepeatKeyMode keyMode : keyModes) {
			
			if ( keyMode == RepeatKeyMode.SESSIONID ) {
				keyBuffer.append( request.getSession().getId() + ";" );
			}
			
			if ( keyMode == RepeatKeyMode.TOKEN ) {
				// TokenUtils自定义工具类,从request中获取头中的token信息
				keyBuffer.append( TokenUtils.getToken(request) + ";" );
			}
			
			if ( keyMode == RepeatKeyMode.VALUE ) {
				// JsonUtils自定义工具类,将对象转换成Json串
				keyBuffer.append( JsonUtils.toJson(joinPoint.getArgs()) + ";" );
			}
			
		}
		
		String key = DigestUtils.md5DigestAsHex(keyBuffer.toString().getBytes()); // 组合Key

		if ( cache.get(key) == null ) {
			cache.set(key, true , lockMillis);
			return joinPoint.proceed();
			
		} else {
			cache.put(key, lockMillis);
			// ResultBeanUtils,自定义工具类,封装ResultBean通用返回对象
			return ResultBeanUtils.FAIL(noRepeatSubmit.message());
		}
	}
}

ConcurrentMapCache 参考上一篇

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值