Springboot后端接口幂等性实现方案

一、什么是幂等性

本文一至五部分是关于幂等性的概念介绍,实现方案在第六部分,基于防重Token令牌方案代码在第七部分。
幂等是一个数学与计算机学概念,在数学中某一元运算为幂等时,其作用在任一元素两次后会和其作用一次的结果相同。在计算机中编程中,一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同。

幂等函数或幂等方法是指可以使用相同参数重复执行,并能获得相同结果的函数。这些函数不会影响系统状态,也不用担心重复执行会对系统造成改变。

二、什么是接口幂等性

在HTTP/1.1中,对幂等性进行了定义。它描述了一次和多次请求某一个资源对于资源本身应该具有同样的结果(网络超时等问题除外),即第一次请求的时候对资源产生了副作用,但是以后的多次请求都不会再对资源产生副作用。

这里的副作用是不会对结果产生破坏或者产生不可预料的结果。也就是说,其任意多次执行对资源本身所产生的影响均与一次执行的影响相同。

三、为什么要实现幂等性

在接口调用时一般情况下都能正常返回信息不会重复提交,不过在遇见以下情况时可以就会出现问题,如:

1.前端重复提交表单: 在填写一些表格时候,用户填写完成提交,很多时候会因网络波动没有及时对用户做出提交成功响应,致使用户认为没有成功提交,然后一直点提交按钮,这时就会发生重复提交表单请求。

2.用户恶意进行刷单: 例如在实现用户投票这种功能时,如果用户针对一个用户进行重复提交投票,这样会导致接口接收到用户重复提交的投票信息,这样会使投票结果与事实严重不符。

3.接口超时重复提交: 很多时候 HTTP 客户端工具都默认开启超时重试的机制,尤其是第三方调用接口时候,为了防止网络波动超时等造成的请求失败,都会添加重试机制,导致一个请求提交多次。

4.消息进行重复消费: 当使用 MQ 消息中间件时候,如果发生消息中间件出现错误未及时提交消费信息,导致发生重复消费。

使用幂等性最大的优势在于使接口保证任何幂等性操作,免去因重试等造成系统产生的未知的问题。

四、引入接口幂等性对系统的影响

幂等性是为了简化客户端逻辑处理,能放置重复提交等操作,但却增加了服务端的逻辑复杂性和成本,其主要是:

  • 把并行执行的功能改为串行执行,降低了执行效率。

  • 增加了额外控制幂等的业务逻辑,复杂化了业务功能;

所以在使用时候需要考虑是否引入幂等性的必要性,根据实际业务场景具体分析,除了业务上的特殊要求外,一般情况下不需要引入的接口幂等性。

五、Restful API 接口的幂等性

现在流行的 [Restful 推荐的几种HTTP 接口方法中,分别存在幂等行与不能保证幂等的方法,如下:

  • √ 满足幂等

  • x 不满足幂等

    • 可能满足也可能不满足幂等,根据实际业务逻辑有关


      接口幂等性.png

六、如何实现幂等性

方案一:数据库唯一主键

方案描述:
数据库唯一主键的实现主要是利用数据库中主键唯一约束的特性,一般来说唯一主键比较适用于“插入”时的幂等性,其能保证一张表中只能存在一条带该唯一主键的记录。

使用数据库唯一主键完成幂等性时需要注意的是,该主键一般来说并不是使用数据库中自增主键,而是使用分布式 ID 充当主键,这样才能能保证在分布式环境下 ID 的全局唯一性。
适用操作:

  • 插入操作

  • 删除操作

使用限制:

需要生成全局唯一主键 ID;
主要流程:

① 客户端执行创建请求,调用服务端接口。

② 服务端执行业务逻辑,生成一个分布式 ID,将该 ID 充当待插入数据的主键,然后执数据插入操作,运行对应的 SQL 语句。

③ 服务端将该条数据插入数据库中,如果插入成功则表示没有重复调用接口。如果抛出主键重复异常,则表示数据库中已经存在该条记录,返回错误信息到客户端。

方案二:数据库乐观锁

方案描述:

数据库乐观锁方案一般只能适用于执行“更新操作”的过程,我们可以提前在对应的数据表中多添加一个字段,充当当前数据的版本标识。这样每次对该数据库该表的这条数据执行更新时,都会将该版本标识作为一个条件,值为上次待更新数据中的版本标识的值。

适用操作:

  • 更新操作

使用限制:

  • 需要数据库对应业务表中添加额外字段;
  • 不适合有一定并发量的应用使用,在同一时刻对同一份资源更新只有一个操作能够成功.

主要流程:


数据库乐观锁.png

例如,存在如下的数据表中:


原始表结构.jpg

为了每次执行更新时防止重复更新,确定更新的一定是要更新的内容,我们通常都会添加一个 version 字段记录当前的记录版本,这样在更新时候将该值带上,那么只要执行更新操作就能确定一定更新的是某个对应版本下的信息。


基于乐观锁实现幂等性的表结构.png

这样每次执行更新时候,都要指定要更新的版本号,如下操作就能准确更新 version=5 的信息:
UPDATE my_table SET price=price+50,version=version+1 WHERE id=1 AND version=5

上面 WHERE 后面跟着条件 id=1 AND version=5 被执行后,id=1 的 version 被更新为 6,所以如果重复执行该条 SQL 语句将不生效,因为 id=1 AND version=5 的数据已经不存在,这样就能保住更新的幂等,多次更新对结果不会产生影响。

方案三:防重token令牌

方案描述:

针对客户端连续点击或者调用方的超时重试等情况,例如提交订单,此种操作就可以用 Token 的机制实现防止重复提交。

简单的说就是调用方在调用接口的时候先向后端请求一个全局 ID(Token),请求的时候携带这个全局 ID 一起请求(Token 最好将其放到 Headers 中),后端需要对这个 Token 作为 Key,用户信息作为 Value 到 Redis 中进行键值内容校验,如果 Key 存在且 Value 匹配就执行删除命令,然后正常执行后面的业务逻辑。如果不存在对应的 Key 或 Value 不匹配就返回重复执行的错误信息,这样来保证幂等操作。

适用操作:

  • 插入操作

  • 更新操作

  • 删除操作

使用限制:

  • 需要生成全局唯一 Token 串;

  • 需要使用第三方组件 Redis 进行数据效验。

主要流程:


防重Token令牌.png

① 服务端提供获取 Token 的接口,该 Token 可以是一个序列号,也可以是一个分布式 ID 或者 UUID 串。

② 客户端调用接口获取 Token,这时候服务端会生成一个 Token 串。

③ 然后将该串存入 Redis 数据库中,以该 Token 作为 Redis 的键(注意设置过期时间)。

④ 将 Token 返回到客户端,客户端拿到后应存到表单隐藏域中。

⑤ 客户端在执行提交表单时,把 Token 存入到 Headers 中,执行业务请求带上该 Headers。

⑥ 服务端接收到请求后从 Headers 中拿到 Token,然后根据 Token 到 Redis 中查找该 key 是否存在。

⑦ 服务端根据 Redis 中是否存该 key 进行判断,如果存在就将该 key 删除,然后正常执行业务逻辑。如果不存在就抛异常,返回重复提交的错误信息。

七、防重Token令牌代码实现

首先构建一个SpringBoot项目,maven依赖如下:
父工程:



    4.0.0

    com.cube
    share
    0.0.1-SNAPSHOT
    
        dynamic-proxy
        idempotence
    
    share
    share project
    pom

    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.3
    

    
        1.8
        UTF-8
        1.8
        1.8
        2.4.3
        1.1.10
        8.0.18
        2.0.1
    

    
        
            
            
                org.springframework.boot
                spring-boot-starter-web
                ${boot.version}
            

            
            
                com.alibaba
                druid-spring-boot-starter
                ${druid.version}
            
            
                mysql
                mysql-connector-java
                ${mysql.version}
            

            
            
                org.mybatis.spring.boot
                mybatis-spring-boot-starter
                ${mybatis.boot.version}
            

            
            
                org.springframework.boot
                spring-boot-starter-aop
                ${boot.version}
            

            
            
                org.springframework.boot
                spring-boot-starter-data-redis
                ${boot.version}
            
        
    

    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.projectlombok
            lombok
            true
        

        
            junit
            junit
            4.12
        

        
        
            org.springframework.boot
            spring-boot-starter
        

    



当前工程:



    
        share
        com.cube
        0.0.1-SNAPSHOT
    
    4.0.0

    idempotence

    
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
            org.apache.commons
            commons-pool2
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-aop
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

我这里因为是在父工程下建立的子工程,所以把两份pom文件都贴出来了,如果只是建立一个单独的工程在当前工程pom文件引入全部依赖即可。
Redis配置:
连接池采用了lettuce,没有采用jedis,两种连接池的区别大家可自行百度这里就不展开了。

spring:
  redis:
    host: 127.0.0.1
    ssl: false
    port: 6379
    database: 1
    connect-timeout: 1000
    lettuce:
      pool:
        max-active: 10
        max-wait: -1
        min-idle: 0
        max-idle: 20
package com.cube.share.idempotence.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author litb
 * @date 2021/3/11 13:44
 * @description Redis配置
 */
@Configuration
public class RedisConfig {

    @Bean
    public GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());
        return redisTemplate;
    }
}

自定义注解和切面对幂等方法的幂等性Token进行校验
自定义注解:

package com.cube.share.idempotence.annotations;

import com.cube.share.idempotence.constants.Constant;

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

/**
 * @author litb
 * @date 2021/3/11 14:17
 * @description 支持幂等性注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SupportIdempotence {

    /**
     * 幂等性校验的token前缀
     *
     * @return
     */
    String prefix() default Constant.IDEMPOTENCE_TOKEN_PREFIX;

    /**
     * 是否需要在客户端弹出警告,如果为true则弹出警告例如[请勿重复提交]
     *
     * @return
     */
    boolean alert() default false;
}

自定义注解切面

package com.cube.share.idempotence.annotations.aspects;

import com.cube.share.idempotence.annotations.SupportIdempotence;
import com.cube.share.idempotence.constants.Constant;
import com.cube.share.idempotence.templates.ApiResult;
import com.cube.share.idempotence.templates.CustomException;
import com.cube.share.idempotence.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
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;
import java.util.Collections;
import java.util.Objects;

/**
 * @author litb
 * @date 2021/3/11 14:22
 * @description 幂等性切面
 * eval "return redis.call('get',KEYS[1])" 1 key1
 */
@Component
@Slf4j
@Aspect
public class IdempotenceAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 确保get和del两部操作原子性的lua脚本
     */
    private static final String LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    private static final RedisScript REDIS_GET_DEL_SCRIPT = new DefaultRedisScript<>(LUA_SCRIPT, Long.class);

    @Pointcut("@annotation(com.cube.share.idempotence.annotations.SupportIdempotence)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取注解属性
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        SupportIdempotence idempotence = method.getAnnotation(SupportIdempotence.class);
        String keyPrefix = idempotence.prefix();
        boolean alert = idempotence.alert();

        //从方法中获取请求头
        HttpServletRequest request = Objects.requireNonNull(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).getRequest();
        String ip = IpUtil.getIpAddress(request);
        //前端传入的token
        String token = request.getHeader(Constant.IDEMPOTENCE_TOKEN_HEADER);

        //token校验
        if (token == null) {
            log.error("请求头缺少幂等性token,url_path = {}", request.getServletPath());
            throw new CustomException("幂等性校验token缺失");
        }
        //拼接成存放在redis中的key
        String redisKey = keyPrefix + token;
        //执行lua脚本
        Long result = stringRedisTemplate.execute(REDIS_GET_DEL_SCRIPT, Collections.singletonList(redisKey), ip);
        if (result == null || result == 0L) {
            if (alert) {
                throw new CustomException("请勿重复提交");
            } else {
                return ApiResult.success();
            }
        }
        return joinPoint.proceed();
    }
}

获取用于幂等性校验的Token
这里采用UUID作为Token,并将指定前缀与token拼接作为key存入Redis,当前用户信息作为value(我这里采用的是ip),也可以采用用户的其他信息作为value,后面幂等性校验时会同时对key和value进行校验,在确保key能够唯一的情况下,仅对key进行校验也可。

package com.cube.share.idempotence.service;

import com.cube.share.idempotence.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author litb
 * @date 2021/3/11 15:30
 * @description 幂等性token Service
 */
@Service
@Slf4j
public class IdempotenceTokenService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取幂等性token,执行成功后会在redis中存入 prefix+token:value一条记录
     *
     * @param value 存入redis中的value
     * @return
     */
    public String generateIdempotenceToken(String value) {
        String token = UUID.randomUUID().toString();
        String key = Constant.IDEMPOTENCE_TOKEN_PREFIX + token;
        stringRedisTemplate.opsForValue().set(key, value, 3, TimeUnit.MINUTES);
        return token;
    }
}

全局异常处理器

package com.cube.share.idempotence.config;

import com.cube.share.idempotence.templates.ApiResult;
import com.cube.share.idempotence.templates.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author litb
 * @date 2021/3/11 15:21
 * @description 全局异常处理器
 */
@ResponseBody
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ApiResult customExceptionHandler(CustomException ce) {
        return ApiResult.error(ce.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResult exceptionHandler(Exception e) {
        log.error("系统异常,error_msg = {}", e.getMessage());
        return ApiResult.error("系统异常!");
    }
}

Controller

package com.cube.share.idempotence.controller;

import com.cube.share.idempotence.annotations.SupportIdempotence;
import com.cube.share.idempotence.service.IdempotenceTokenService;
import com.cube.share.idempotence.templates.ApiResult;
import com.cube.share.idempotence.utils.IpUtil;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author litb
 * @date 2021/3/11 15:37
 * @description
 */
@RestController
public class IdempotenceController {

    @Resource
    private IdempotenceTokenService idempotenceTokenService;

    @GetMapping("/token")
    public ApiResult getToken(HttpServletRequest request) {
        return ApiResult.success(idempotenceTokenService.generateIdempotenceToken(IpUtil.getIpAddress(request)));
    }

    @DeleteMapping("/delete")
    @SupportIdempotence
    public ApiResult delete() {
        return ApiResult.success("删除成功");
    }

    @PostMapping("/submit")
    @SupportIdempotence(alert = true)
    public ApiResult submit() {
        return ApiResult.success("提交成功");
    }
}

测试结果:
1、获取Token


获取token.png

2、请求头中无幂等性Token


幂等性token缺失.png

3、成功请求


成功请求.png

4、alert为false,不需要进行重复提交提示,响应体msg为null


不需要进行重复请求提示.png

5、alert为true,需要进行重复提交提示,前端拿到提示信息后可将其弹出


需要进行重复提交提示.png

完整代码:https://gitee.com/li-cube/share/tree/master/idempotence

你可能感兴趣的:(Springboot后端接口幂等性实现方案)