自定义注解之防刷新(重复提交)
0、前言
在保险行业,有很多场景需要防止用户短时间内重复提交,例如投保单保存操作、提交核保操作、批单保存操作、预提交操作等等,因此我们后端通过注解实现这一功能。
我相信在其他行业应该也会有类似场景,如果有跟好的解决方案欢迎大家一起交流。
1、实现自定义注解–Redis版
1.1、创建自定义注解
import java.lang.annotation.Documented;
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;
/**
* @author :
* @date :Created in 15:11 2022/9/1
* @description :自定义重复提交注解
* @version: 1.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DuplicateSubmit {
/**
* 指定时间内不可重复提交,单位:s
*/
long timeout() default 3;
}
1.2、通过AOP切面实现
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
/**
* @author :
* @date :Created in 15:11 2022/9/2
* @description :
* @version: 1.0
*/
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class DuplicateSubmitAspect {
private final StringRedisTemplate stringRedisTemplate;
@Before("@annotation(com.*.aspect.DuplicateSubmit)")
public void repeatSumbitIntercept(JoinPoint joinPoint) {
// ip + name + timeout
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = NetWorkUtils.getRemoteHost(request);
String jtiInfo = request.getHeader(HttpHeaders.AUTHORIZATION);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 获取配置的信息: 名称 过期时间
DuplicateSubmit annotation = method.getAnnotation(DuplicateSubmit.class);
String name = annotation.name();
long timeout = annotation.timeout();
String key = ip + ":" + jtiInfo;
log.info(" --- >> 防重提交:key -- {}", key);
// 判断是否已经超过重复提交的限制时间
Boolean isAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, key, timeout, TimeUnit.SECONDS);
if (!isAbsent) {
String message = MessageFormat.format("请勿在{0}s内重复提交", timeout);
log.warn("方法:{},{},重复提交", name, ExceptionCode.DUPLICATE_SUBMIT);
throw new CommonException(ExceptionCode.DUPLICATE_SUBMIT.getCodeValue(), message);
}
}
}
1.3、使用
/**
* @author :
* @date :Created in 14:13 2022/9/2
* @description :规则
* @version: 1.0
*/
@Slf4j
@RestController
@RequiredArgsConstructor
public class RuleConfigController implements IRuleConfigController {
private final IRuleConfigService iRuleConfigService;
@Override
@DuplicateSubmit(name = "ruleConfig:add", timeout = 30)
public HttpEntity addRuleConfig(@RequestBody RuleConfigRequest ruleConfigRequest) {
log.info("[ruleConfig add]param-ruleConfigRequest: {}", ruleConfigRequest);
try {
RuleConfig ruleConfigNow = iRuleConfigService.addRuleConfig(new RuleConfig(ruleConfigRequest));
return ResponseObject.createOk(ruleConfigNow);
}catch (RuntimeException e) {
log.error("[ruleConfig add]" + e);
return ResponseObject.createOk(e.getMessage());
}
}
}
1.4、补充网络工具类–NetWorkUtils
NetWorkUtils.getRemoteHost(request)获取IP
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* @author :
* @date :Created in 16:38 2022/9/13
* @description :网络工具类
* @version: 1.0
*/
public class NetWorkUtils {
/**
* 获取到 SessionID
*
* @param request
* HttpServletRequest
* @return SessionID
*/
public static String getSessionID(HttpServletRequest request) {
return request.getSession().getId();
}
/**
* 获取客户端的IP
*
* @param request
* HttpServletRequest
* @return 客户端IP
*/
public static String getRemoteHost(HttpServletRequest request) {
if (request == null) {
return null;
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 多个路由时,取第一个非unknown的ip
final String[] arr = ip.split(",");
for (final String str : arr) {
if (!"unknown".equalsIgnoreCase(str)) {
ip = str;
break;
}
}
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
/**
* 获取得到本机IP地址
*
* @throws SocketException
*/
public static String getLocalIP() {
if (isWindowsOS()) {
return getWindowsIP();
} else {
return getLinuxLocalIp();
}
}
/**
* 判断操作系统是否为windows系统
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取到Host名字
*/
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取WindowsIP
*/
public static String getWindowsIP() {
String serverIP = "";
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
byte[] ipAddr = addr.getAddress();
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
serverIP += ".";
}
serverIP += ipAddr[i] & 0xFF;
}
return serverIP;
}
/**
* 获取LinuxIp
*/
private static String getLinuxLocalIp() {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
&& !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (Exception ex) {
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
}