解决接口幂等性的最佳方式

解决接口幂等性的最佳方式

  1. 什么是幂等性
    简而言之,多次提交只有一次生效,例:用户付款的时候多次点击付款应当只有一次生效。

  2. 解决幂等性的方式
    1、数据库加入唯一索引(缺点:1、扩展 2、数据库的负担)
    2、前端加入拦截
    3、加入拦截器(缺点:只能对controller层进行拦截 对service层不友好)
    4、aop+redis+token(优点:易扩展)

  3. aop+redis+token实现方式
    (1)添加注解

import java.lang.annotation.*;

/**
 * @author cgd
 * @version 1.0
 * @date 2021/2/1 14:43
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IdempotenceAnnotation {

}

(2)创建token和检查token

package com.xdd.apiprojectseed.config;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xdd.apiprojectseed.common.RedisUtil;
import com.xdd.apiprojectseed.util.IpUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author cgd
 * @version 1.0
 * @date 2021/2/3 15:45
 */
@AllArgsConstructor
@Service
public class TokenService {
    @Autowired
    RedisTemplate redisTemplate;
    public String createToken(HttpServletRequest request) {
        String token = IpUtils.getIpAddr(request)+"_"+UUID.randomUUID();
        redisTemplate.opsForValue().set(token, token, 100, TimeUnit.MINUTES);
        return token;
    }

    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader("IDEMPOTENT-TOKEN");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("IDEMPOTENT-TOKEN");
            if (StrUtil.isBlank(token)) {
                throw new IdempotentException("非法提交");
            }
        }
        Object tokenVal = redisTemplate.opsForValue().get(token);
        if (Objects.isNull(tokenVal)) {
            throw new IdempotentException("禁止重复提交或者token已过期!");
        }
        Boolean del = redisTemplate.delete(token);
        if (!del) {
            throw new IdempotentException("禁止重复提交!");
        }
    }


}


(3)创建切面

package com.xdd.apiprojectseed.config;

/**
 * @author cgd
 * @version 1.0
 * @date 2021/2/1 14:50
 */

import cn.hutool.core.net.NetUtil;
import com.xdd.apiprojectseed.common.RedisUtil;
import com.xdd.apiprojectseed.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author szn
 */
@Aspect
@Component
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class IdempotenceAnnotationAspect {

    @Autowired
    TokenService tokenService;
    @Autowired
    RedisUtil redisUtil;
    /**
     * 定义切入点为添加了自定如注解的方法
     */
    @Pointcut("@annotation(com.xdd.apiprojectseed.config.IdempotenceAnnotation)")
    public void idempotence() {
    }

    /**
     * 在方法执行之前使用redis分布式锁进行接口等幂性约束
     * @param joinPoint
     */
    @Around("idempotence()")
    public Object redisLock(ProceedingJoinPoint joinPoint) throws Throwable {

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        IdempotenceAnnotation idempotenceAnnotation=method.getAnnotation(IdempotenceAnnotation.class);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        Object result = null;
        //判断方法是否配置@IdempotenceAnnotation注解
       if (idempotenceAnnotation==null){
           result = joinPoint.proceed();
       }else{
           tokenService.checkToken(request);
           result = joinPoint.proceed();
        }
        return result;
    }
}

(4)获取ip工具类

package com.xdd.apiprojectseed.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cgd
 */
public class IpUtils {
    private IpUtils() {
    }

    /**
     * 获取当前网络ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获得MAC地址
     * @param ip
     * @return
     */
    public static String getMACAddress(String ip){
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC Address") > 1) {
                        macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

}

(5)添加异常类

package com.xdd.apiprojectseed.config;

/**
 * @author cgd
 * @version 1.0
 * @date 2021/2/3 16:03
 */
public class IdempotentException extends RuntimeException {

    public IdempotentException() {
    }

    public IdempotentException(String message) {
        super(message);
    }

    public IdempotentException(Throwable cause) {
        super(cause);
    }

    public IdempotentException(String message, Throwable cause) {
        super(message, cause);
    }

    public IdempotentException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

(6) 测试

    @GetMapping("getMessage")
    @IdempotenceAnnotation
    public String getMessage(){
        return "你一通过))))))))))))))";
    }
  1. 总结
    (1)自定义注解
    (2)aop切面类判断对象是否有相应的注解 如果有 从或者header获取参数 进行校验
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值