一、概念

幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次

比如:

  • 订单接口, 不能多次创建订单
  • 支付接口, 重复支付同一笔订单只能扣一次钱
  • 支付宝回调接口, 可能会多次回调, 必须处理重复回调
  • 普通表单提交接口, 因为网络超时等原因多次点击提交, 只能成功一次

    等等

二、常见解决方案

  1. 唯一索引 -- 防止新增脏数据
  2. token机制 -- 防止页面重复提交
  3. 悲观锁 -- 获取数据的时候加锁(锁表或锁行)
  4. 乐观锁 -- 基于版本号version实现, 在更新数据那一刻校验数据
  5. 分布式锁 -- redis(jedis、redisson)或zookeeper实现
  6. 状态机 -- 状态变更, 更新数据时判断状态

三、本文实现

本文采用第2种方式实现, 即通过redis + token机制实现接口幂等性校验

四、实现思路

为需要保证幂等性的每一次请求创建一个唯一标识token, 先获取token, 并将此token存入redis, 请求接口时, 将此token放到header或者作为请求参数请求接口, 后端接口判断redis中是否存在此token:

  • 如果存在, 正常处理业务逻辑, 并从redis中删除此token, 那么, 如果是重复请求, 由于token已被删除, 则不能通过校验, 返回请勿重复操作提示
  • 如果不存在, 说明参数不合法或者是重复请求, 返回提示即可

五、项目简介

  • springboot
  • redis
  • @ApiIdempotent注解 + 拦截器对请求进行拦截
  • @ControllerAdvice全局异常处理
  • 压测工具: jmeter

说明:

  • 本文重点介绍幂等性核心实现, 关于springboot如何集成redisServerResponseResponseCode等细枝末节不在本文讨论范围之内, 有兴趣的小伙伴可以查看我的Github项目: https://github.com/wangzaiplus/springboot/tree/wxw

六、代码实现

  1. pom
        <!-- Redis-Jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
  1. JedisUtil
package com.wangzaiplus.test.util;

import com.wangzaiplus.test.common.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import java.util.Set; @Component
public class JedisUtil { @Autowired
private JedisPool jedisPool; private Jedis getJedis() {
return jedisPool.getResource();
} /**
* 设值
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.set(key, value);
} catch (Exception e) {
throw new RuntimeException("set异常: key: " + key + ", cause: " + e.getMessage());
} finally {
close(jedis);
}
} /**
* 设值
*
* @param key
* @param value
* @param expireTime 过期时间, 单位: s
* @return
*/
public String set(String key, String value, int expireTime) {
Jedis jedis = null;
try {
jedis = getJedis();
String result = jedis.set(key, value);
if (Constant.Redis.OK.equals(result)) {
jedis.expire(key, expireTime);
}
return result;
} catch (Exception e) {
throw new RuntimeException("set-expireTime异常: key: " + key + ", cause: " + e.getMessage());
} finally {
close(jedis);
}
} /**
* 删除key
*
* @param key
* @return
*/
public Long del(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.del(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("del异常: key: " + key + ", cause: " + e.getMessage());
} finally {
close(jedis);
}
} /**
* 判断key是否存在
*
* @param key
* @return
*/
public Boolean exists(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.exists(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("exists异常: key: " + key + ", cause: " + e.getMessage());
} finally {
close(jedis);
}
} public void close(Jedis jedis) {
if (null != jedis) {
jedis.close();
}
} }

说明: 篇幅有限, 完整JedisUtil请参考GitHub

  1. 自定义注解@ApiIdempotent
package com.wangzaiplus.test.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* 在需要保证 接口幂等性 的Controller的方法上使用此注解
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiIdempotent {
}
  1. ApiIdempotentInterceptor拦截器
package com.wangzaiplus.test.interceptor;

import com.wangzaiplus.test.annotation.ApiIdempotent;
import com.wangzaiplus.test.exception.ServiceException;
import com.wangzaiplus.test.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method; /**
* 接口幂等性拦截器
*/
public class ApiIdempotentInterceptor implements HandlerInterceptor { @Autowired
private TokenService tokenService; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod)) {
return true;
} HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod(); ApiIdempotent methodAnnotation = method.getAnnotation(ApiIdempotent.class);
if (methodAnnotation != null) {
checkApiIdempotent(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
} return true;
} private void checkApiIdempotent(HttpServletRequest request) {
tokenService.checkToken(request);
} @Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
} @Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
  1. TokenServiceImpl
package com.wangzaiplus.test.service.impl;

import com.wangzaiplus.test.common.Constant;
import com.wangzaiplus.test.common.ResponseCode;
import com.wangzaiplus.test.common.ServerResponse;
import com.wangzaiplus.test.exception.ServiceException;
import com.wangzaiplus.test.service.TokenService;
import com.wangzaiplus.test.util.JedisUtil;
import com.wangzaiplus.test.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; @Service
public class TokenServiceImpl implements TokenService { private static final String TOKEN_NAME = "token"; @Autowired
private JedisUtil jedisUtil; @Override
public ServerResponse createToken() {
String str = RandomUtil.generateStr(24);
StrBuilder token = new StrBuilder();
token.append(Constant.Redis.TOKEN_PREFIX).append(str); jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE); return ServerResponse.success(token.toString());
} @Override
public void checkToken(HttpServletRequest request) {
String token = request.getHeader(TOKEN_NAME);
if (StringUtils.isBlank(token)) {// header中不存在token
token = request.getParameter(TOKEN_NAME);
if (StringUtils.isBlank(token)) {// parameter中也不存在token
throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
}
} if (!jedisUtil.exists(token)) {
throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
} Long del = jedisUtil.del(token);
if (del <= 0) {
throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
}
} }
  1. TestApplication
package com.wangzaiplus.test;

import com.wangzaiplus.test.interceptor.ApiIdempotentInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication
@MapperScan("com.wangzaiplus.test.mapper")
public class TestApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
} /**
* 跨域
* @return
*/
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
} @Override
public void addInterceptors(InterceptorRegistry registry) {
// 接口幂等性拦截器
registry.addInterceptor(apiIdempotentInterceptor());
super.addInterceptors(registry);
} @Bean
public ApiIdempotentInterceptor apiIdempotentInterceptor() {
return new ApiIdempotentInterceptor();
} }

OK, 目前为止, 校验代码准备就绪, 接下来测试验证

七、测试验证

  1. 获取token的控制器TokenController
package com.wangzaiplus.test.controller;

import com.wangzaiplus.test.common.ServerResponse;
import com.wangzaiplus.test.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/token")
public class TokenController { @Autowired
private TokenService tokenService; @GetMapping
public ServerResponse token() {
return tokenService.createToken();
} }
  1. TestController, 注意@ApiIdempotent注解, 在需要幂等性校验的方法上声明此注解即可, 不需要校验的无影响
package com.wangzaiplus.test.controller;

import com.wangzaiplus.test.annotation.ApiIdempotent;
import com.wangzaiplus.test.common.ServerResponse;
import com.wangzaiplus.test.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/test")
@Slf4j
public class TestController { @Autowired
private TestService testService; @ApiIdempotent
@PostMapping("testIdempotence")
public ServerResponse testIdempotence() {
return testService.testIdempotence();
} }
  1. 获取token

查看redis

  1. 测试接口安全性: 利用jmeter测试工具模拟50个并发请求, 将上一步获取到的token作为参数

  1. header或参数均不传token, 或者token值为空, 或者token值乱填, 均无法通过校验, 如token值为"abcd"

八、注意点(非常重要)

上图中, 不能单纯的直接删除token而不校验是否删除成功, 会出现并发安全性问题, 因为, 有可能多个线程同时走到第46行, 此时token还未被删除, 所以继续往下执行, 如果不校验jedisUtil.del(token)的删除结果而直接放行, 那么还是会出现重复提交问题, 即使实际上只有一次真正的删除操作, 下面重现一下

稍微修改一下代码:

再次请求

再看看控制台

虽然只有一个真正删除掉token, 但由于没有对删除结果进行校验, 所以还是有并发问题, 因此, 必须校验

九、总结

其实思路很简单, 就是每次请求保证唯一性, 从而保证幂等性, 通过拦截器+注解, 就不用每次请求都写重复代码, 其实也可以利用spring aop实现, 无所谓

如果小伙伴有什么疑问或者建议欢迎提出

Github

https://github.com/wangzaiplus/springboot/tree/wxw

springboot + redis + 注解 + 拦截器 实现接口幂等性校验的更多相关文章

  1. Springboot + redis + 注解 + 拦截器来实现接口幂等性校验

    Springboot + redis + 注解 + 拦截器来实现接口幂等性校验   1. SpringBoot 整合篇 2. 手写一套迷你版HTTP服务器 3. 记住:永远不要在MySQL中使用UTF ...

  2. springboot + 注解 + 拦截器 + JWT 实现角色权限控制

    1.关于JWT,参考: (1)10分钟了解JSON Web令牌(JWT) (2)认识JWT (3)基于jwt的token验证 2.JWT的JAVA实现 Java中对JWT的支持可以考虑使用JJWT开源 ...

  3. Springboot中SpringMvc拦截器配置与应用(实战)

    一.什么是拦截器,及其作用 拦截器(Interceptor): 用于在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,其实就是AOP的一种实现策略.它通过动态拦截Action调用的对 ...

  4. 在springboot中使用拦截器

    在springMVC中可以实现拦截器,是通过实现HandlerInterceptor接口,然后在springmvc-web.xml中配置就可以使用拦截器了.在springboot中拦截器也是一样的思想 ...

  5. Spring MVC 方法注解拦截器

    应用场景,在方法级别对本次调用进行鉴权,如api接口中有个用户唯一标示accessToken,对于有accessToken的每次请求可以在方法加一个拦截器,获得本次请求的用户,存放到request或者 ...

  6. SpringBoot如何添加拦截器

    在web开发的过程中,为了实现登录权限验证,我们往往需要添加一个拦截器在用户的的请求到达controller层的时候实现登录验证,那么SpringBoot如何添加拦截器呢? 步骤如下: 1.继承Web ...

  7. springmvc以及springboot中的拦截器配置

    拦截器两种实现   如果不同的controller中都需要拦截器,不能使用相同的拦截器,因为拦截器不能跨controller,这个时候只能为不同的controller配置不同的拦截器,每一个拦截器只能 ...

  8. springboot+redis+Interceptor+自定义annotation实现接口自动幂等

    前言: 在实际的开发项目中,一个对外暴露的接口往往会面临很多次请求,我们来解释一下幂等的概念:任意多次执行所产生的影响均与一次执行的影响相同.按照这个含义,最终的含义就是 对数据库的影响只能是一次性的 ...

  9. springboot中使用拦截器、监听器、过滤器

     拦截器.过滤器.监听器在web项目中很常见,这里对springboot中怎么去使用做一个总结. 1. 拦截器(Interceptor)   我们需要对一个类实现HandlerInterceptor接 ...

随机推荐

  1. 【指南】本地如何搭建IPv6环境测试你的APP

    由于苹果最近更新IOS10之后他们的工作环境升级了,统一用IPV6网络,所以我们发出去的申请的APP不兼容IPV6的话,会通过不了审核! 所幸的是苹果会自动把你服务器要接的协议自动把iPV6转成IPV ...

  2. 10种简单的Java性能优化(转)

    本文由 ImportNew - 一直在路上 翻译自 jaxenter.欢迎加入翻译小组.转载请见文末要求. 你是否正打算优化hashCode()方法?是否想要绕开正则表达式?Lukas Eder介绍了 ...

  3. More Effective C++: 04效率

    16:牢记80-20准则 80-20准则说的是大约20%的代码使用了80%的程序资源:大约20%的代码耗用了大约80%的运行时间:大约20%的代码使用了80%的内存:大约20%的代码执行80%的磁盘访 ...

  4. 让超出div内容的显示滚动条:overflow:auto,以及overflow其它属性

    css的属性,以前没用过遇到了,记录一下: 虽然layui本来自带这个处理,但是为了灵活,抛弃layui原有的加载,只是用layui的样样式,就要使用到这个css属性 总结overflow属性: /* ...

  5. KiCad 5.1.4 无法覆铜?

    KiCad 5.1.4 无法覆铜? 群里有小伙伴发现焊盘无法覆铜,只能靠手工连接. 这就奇怪了,正常情况不会出现的这种现象的. 分析了很多可能,比较间隙太小,有试着调过,但还是连接不上. 把封装的所有 ...

  6. python 解释器编码

  7. Java练习 SDUT-2246_时间日期格式转换

    时间日期格式转换 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 对于日期的常用格式,在中国常采用格式的是"年 ...

  8. Auto CAD 安装问题 “acad.exe - 系统错误 ”

    Auto CAD 安装不上,提示“cad装不上 提示无法启动此程序,因为计算机中丢失 ac1st16.dll” 解决方法: 我的电脑——>右键 属性——>高级选项卡(win7的是高级系统设 ...

  9. python 类与类之间的关系. 特殊成员

    一.类与类之间的关系 1.依赖关系 在方法的参数位置把另一个类的对象作为参数进行传递 class Person: def play(self, tools): # 通过参数的传递把另一个类的对象传递进 ...

  10. Tcp之双向通信

    TestServer.java package com.sxt.tcp; /* * 服务端 */ import java.io.DataInputStream; import java.io.Data ...