自定义注解之防刷新(重复提交)(一)

自定义注解之防刷新(重复提交)

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白de成长之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值