1概念
幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次
比如:
订单接口, 不能多次创建订单支付接口, 重复支付同一笔订单只能扣一次钱支付宝回调接口, 可能会多次回调, 必须处理重复回调普通表单提交接口, 因为网络超时等原因多次点击提交, 只能成功一次 等等
2 常见解决方案
唯一索引-- 防止新增脏数据token机制-- 防止页面重复提交悲观锁-- 获取数据的时候加锁(锁表或锁行)乐观锁-- 基于版本号version实现, 在更新数据那一刻校验数据分布式锁-- redis(jedis、redisson)或zookeeper实现状态机-- 状态变更, 更新数据时判断状态
3 本文实现
本文采用第2种方式实现, 即通过redis + token机制实现接口幂等性校验
4 实现思路
为需要保证幂等性的每一次请求创建一个唯一标识 token, 先获取 token, 并将此 token存入redis, 请求接口时, 将此 token放到header或者作为请求参数请求接口, 后端接口判断redis中是否存在此 token:
如果存在, 正常处理业务逻辑, 并从redis中删除此 token, 那么, 如果是重复请求, 由于 token已被删除, 则不能通过校验, 返回 请勿重复操作提示
如果不存在, 说明参数不合法或者是重复请求, 返回提示即可
5 项目简介
springbootredis@ApiIdempotent注解 + 拦截器对请求进行拦截@ControllerAdvice全局异常处理压测工具: jmete
说明:
本文重点介绍幂等性核心实现, 关于springboot如何集成redis、ServerResponse、ResponseCode等细枝末节不在本文讨论范围之内, 有兴趣的小伙伴可以查看作者的Github项目: https://github.com/wangzaiplus/springboot/tree/wxw
6 代码实现
POM
<!-- Redis-Jedis -->redis.clientsjedis2.9.0<!--lombok 本文用到@Slf4j注解, 也可不引用, 自定义log即可-->org.projectlomboklombok1.16.10
JedisUtil
packagecom.wangzaiplus.test.util;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;importredis.clients.jedis.Jedis;importredis.clients.jedis.JedisPool;@Component@Slf4jpublicclassJedisUtil{@AutowiredprivateJedisPool jedisPool;privateJedis getJedis() {returnjedisPool.getResource(); }/** * 设值 **@paramkey*@paramvalue*@return */publicStringset(String key, String value) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.set(key, value);}catch(Exception e) {log.error("set key:{} value:{} error", key, value, e);returnnull;}finally{ close(jedis); } }/** * 设值 **@paramkey*@paramvalue*@paramexpireTime 过期时间, 单位: s*@return */publicStringset(String key, String value, int expireTime) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.setex(key, expireTime, value);}catch(Exception e) {log.error("set key:{} value:{} expireTime:{} error", key, value, expireTime, e);returnnull;}finally{ close(jedis); } }/** * 取值 **@paramkey*@return */publicStringget(String key) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.get(key);}catch(Exception e) {log.error("get key:{} error", key, e);returnnull;}finally{ close(jedis); } }/** * 删除key **@paramkey*@return */publicLongdel(String key) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.del(key.getBytes());}catch(Exception e) {log.error("del key:{} error", key, e);returnnull;}finally{ close(jedis); } }/** * 判断key是否存在 **@paramkey*@return */publicBooleanexists(String key) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.exists(key.getBytes());}catch(Exception e) {log.error("exists key:{} error", key, e);returnnull;}finally{ close(jedis); } }/** * 设值key过期时间 **@paramkey*@paramexpireTime 过期时间, 单位: s*@return */publicLongexpire(String key, int expireTime) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.expire(key.getBytes(), expireTime);}catch(Exception e) {log.error("expire key:{} error", key, e);returnnull;}finally{ close(jedis); } }/** * 获取剩余时间 **@paramkey*@return */publicLongttl(String key) {Jedis jedis =null;try{ jedis = getJedis();returnjedis.ttl(key);}catch(Exception e) {log.error("ttl key:{} error", key, e);returnnull;}finally{ close(jedis); } }privatevoid close(Jedis jedis) {if(null!= jedis) { jedis.close(); } }}
自定义注解 @ApiIdempotent
packagecom.wangzaiplus.test.annotation;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/** * 在需要保证 接口幂等性 的Controller的方法上使用此注解 */@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface ApiIdempotent {}
1.ApiIdempotentInterceptor拦截器
packagecom.wangzaiplus.test.interceptor;importcom.wangzaiplus.test.annotation.ApiIdempotent;importcom.wangzaiplus.test.service.TokenService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.method.HandlerMethod;importorg.springframework.web.servlet.HandlerInterceptor;importorg.springframework.web.servlet.ModelAndView;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.lang.reflect.Method;/** * 接口幂等性拦截器 */publicclassApiIdempotentInterceptorimplementsHandlerInterceptor{@AutowiredprivateTokenService tokenService;@OverridepublicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler){if(!(handlerinstanceofHandlerMethod)) {returntrue; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); ApiIdempotent methodAnnotation = method.getAnnotation(ApiIdempotent.class);if(methodAnnotation !=null) {check(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示 }returntrue; }privatevoidcheck(HttpServletRequest request){ tokenService.checkToken(request); }@OverridepublicvoidpostHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throwsException{ }@OverridepublicvoidafterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)throwsException{ }}
TokenServiceImpl
package com.wangzaiplus.test.service.impl;importcom.wangzaiplus.test.common.Constant;importcom.wangzaiplus.test.common.ResponseCode;importcom.wangzaiplus.test.common.ServerResponse;importcom.wangzaiplus.test.exception.ServiceException;importcom.wangzaiplus.test.service.TokenService;importcom.wangzaiplus.test.util.JedisUtil;importcom.wangzaiplus.test.util.RandomUtil;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.lang3.StringUtils;importorg.apache.commons.lang3.text.StrBuilder;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjavax.servlet.http.HttpServletRequest;@ServicepublicclassTokenServiceImplimplementsTokenService{privatestaticfinalStringTOKEN_NAME="token";@AutowiredprivateJedisUtiljedisUtil;@OverridepublicServerResponsecreateToken() {Stringstr =RandomUtil.UUID32();StrBuildertoken = newStrBuilder();token.append(Constant.Redis.TOKEN_PREFIX).append(str);jedisUtil.set(token.toString(), token.toString(),Constant.Redis.EXPIRE_TIME_MINUTE);returnServerResponse.success(token.toString()); }@Overridepublicvoid checkToken(HttpServletRequestrequest) {Stringtoken = request.getHeader(TOKEN_NAME);if(StringUtils.isBlank(token)) {// header中不存在tokentoken = request.getParameter(TOKEN_NAME);if(StringUtils.isBlank(token)) {// parameter中也不存在tokenthrownewServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg()); } }if(!jedisUtil.exists(token)) {thrownewServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg()); }Longdel = jedisUtil.del(token);if(del <=0) {thrownewServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg()); } }}
TestApplication
packagecom.wangzaiplus.test;importcom.wangzaiplus.test.interceptor.ApiIdempotentInterceptor;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.annotation.Bean;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.UrlBasedCorsConfigurationSource;importorg.springframework.web.filter.CorsFilter;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@SpringBootApplication@MapperScan("com.wangzaiplus.test.mapper")publicclassTestApplicationextendsWebMvcConfigurerAdapter{publicstaticvoidmain(String[] args){ SpringApplication.run(TestApplication.class, args); }/** * 跨域*@return */@BeanpublicCorsFiltercorsFilter(){finalUrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource =newUrlBasedCorsConfigurationSource();finalCorsConfiguration corsConfiguration =newCorsConfiguration();corsConfiguration.setAllowCredentials(true);corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);returnnewCorsFilter(urlBasedCorsConfigurationSource); }@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){// 接口幂等性拦截器 registry.addInterceptor(apiIdempotentInterceptor());super.addInterceptors(registry); }@BeanpublicApiIdempotentInterceptorapiIdempotentInterceptor(){returnnewApiIdempotentInterceptor(); }}
OK,目前为止, 校验代码准备就绪, 接下来测试验证
7 测试验证
获取 token的控制器 TokenController
packagecom.wangzaiplus.test.controller;importcom.wangzaiplus.test.common.ServerResponse;importcom.wangzaiplus.test.service.TokenService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/token")public class TokenController {@Autowired private TokenService tokenService;@GetMapping public ServerResponse token() {returntokenService.createToken(); }}
TestController, 注意 @ApiIdempotent注解, 在需要幂等性校验的方法上声明此注解即可, 不需要校验的无影响
packagecom.wangzaiplus.test.controller;importcom.wangzaiplus.test.annotation.ApiIdempotent;importcom.wangzaiplus.test.common.ServerResponse;importcom.wangzaiplus.test.service.TestService;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/test")@Slf4jpublic class TestController {@Autowired private TestService testService;@ApiIdempotent@PostMapping("testIdempotence") public ServerResponse testIdempotence() {returntestService.testIdempotence(); }}
获取 token
查看redis
测试接口安全性: 利用jmeter测试工具模拟50个并发请求, 将上一步获取到的token作为参数
header或参数均不传token, 或者token值为空, 或者token值乱填, 均无法通过校验, 如token值为"abcd"
8 注意点(非常重要)
上图中, 不能单纯的直接删除token而不校验是否删除成功, 会出现并发安全性问题, 因为, 有可能多个线程同时走到第46行, 此时token还未被删除, 所以继续往下执行, 如果不校验 jedisUtil.del(token)的删除结果而直接放行, 那么还是会出现重复提交问题, 即使实际上只有一次真正的删除操作, 下面重现一下
稍微修改一下代码:
再次请求
再看看控制台
虽然只有一个真正删除掉token, 但由于没有对删除结果进行校验, 所以还是有并发问题, 因此, 必须校验
9 总结
其实思路很简单, 就是每次请求保证唯一性, 从而保证幂等性, 通过拦截器+注解, 就不用每次请求都写重复代码, 其实也可以利用spring aop实现。
注:部分原文地址来源:
https://www.jianshu.com/p/6189275403ed,收集于网络。
https://mp.weixin.qq.com/s/OzJS01ElHUB3E8QwVzxyaw