使用自定义注解的方式来解决接口幂等性的问题,方法仅供参考,可以按照实际业务进行调整。
一、定义注解
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* 自定义防接口重复提交注解
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestSubmit {
/**
* 间隔时间,小于此时间为重复提交
*/
int interval() default 5000;
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
/**
* 提示语
*/
String message() default "不允许重复提交,请稍后再试!";
}
二、引入切面依赖
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
三、定义切面
import com.alibaba.fastjson.JSON;
import com.yichangqiao.common.annotation.RequestSubmit;
import com.yichangqiao.common.utils.EmptyUtil;
import com.yichangqiao.exception.GlobalException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* 防止接口重复提交
*/
@Aspect
@Component
public class RequestSubmitAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Before("@annotation(requestSubmit)")
public void doBefore(JoinPoint point, RequestSubmit requestSubmit) {
// 获取请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String nowParams = argsArrayToString(point.getArgs());
// 唯一值 (没有消息头则使用请求地址)
String submitKey = StringUtils.removeStart(request.getHeader("token"), "Bearer ");
if (StringUtils.isEmpty(submitKey)) {
submitKey = request.getRequestURI();
}
// 这里可以对key进行加密
submitKey = DigestUtils.md5Hex(submitKey + ":" + nowParams);
// 唯一标识
String cacheRepeatKey = "request_submit:" + submitKey;
// 从redis中获取这个key,判断是否存在
String value = redisTemplate.opsForValue().get(cacheRepeatKey);
if (null == value) {
// 将这个key存到redis中,并指定过期时间
redisTemplate.opsForValue().set(cacheRepeatKey, "", requestSubmit.timeUnit().toMillis(requestSubmit.interval()), TimeUnit.MILLISECONDS);
} else {
// 重复提交
throw new GlobalException(requestSubmit.message());
}
}
/**
* 拼接参数
*/
public String argsArrayToString(Object[] args) {
StringBuilder params = new StringBuilder();
if (EmptyUtil.isNotBlank(args)) {
for (Object o : args) {
if (Objects.nonNull(o) && !isFilterObject(o)) {
params.append(JSON.toJSONString(o)).append(";");
}
}
}
return params.toString().trim();
}
/**
* 判断是否需要过滤对象
*/
public boolean isFilterObject(Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Object value : collection) {
return value instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Object value : map.entrySet()) {
Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
}
四、测试
/**
* 接口防止重复提交
*
* @return
*/
@RequestSubmit(interval = 10000)
@GetMapping("/data")
public R dataAnno(@RequestParam("num") String num) {
log.info("请求参数:{}", num);
return R.success("请求成功!");
}