一、概念
冪等性, 通俗的說就是一個接口, 多次發起同一個請求, 必須保證操作只能執行一次
比如:
訂單接口, 不能多次創建訂單
支付接口, 重複支付同一筆訂單隻能扣一次錢
支付寶回調接口, 可能會多次回調, 必須處理重複回調
普通表單提交接口, 因爲網絡超時等原因多次點擊提交, 只能成功一次
等等
二、常見解決方案
唯一索引 -- 防止新增髒數據
token機制 -- 防止頁面重複提交
悲觀鎖 -- 獲取數據的時候加鎖(鎖表或鎖行)
樂觀鎖 -- 基於版本號version實現, 在更新數據那一刻校驗數據
分佈式鎖 -- redis(jedis、redisson)或zookeeper實現
狀態機 -- 狀態變更, 更新數據時判斷狀態
三、本文實現
本文采用第2種方式實現, 即通過redis + token機制實現接口冪等性校驗。
四、實現思路
爲需要保證冪等性的每一次請求創建一個唯一標識token, 先獲取token, 並將此token存入redis, 請求接口時, 將此token放到header或者作爲請求參數請求接口, 後端接口判斷redis中是否存在此token:
如果存在, 正常處理業務邏輯, 並從redis中刪除此token, 那麼, 如果是重複請求, 由於token已被刪除, 則不能通過校驗, 返回請勿重複操作提示
如果不存在, 說明參數不合法或者是重複請求, 返回提示即可。
五、項目簡介
springboot
redis
@ApiIdempotent註解 + 攔截器對請求進行攔截
@ControllerAdvice全局異常處理
壓測工具: jmeter
說明:
本文重點介紹冪等性核心實現, 關於springboot如何集成redis、ServerResponse、ResponseCode等細枝末節不在本文討論範圍之內。
六、代碼實現
pom
<!-- Redis-Jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!--lombok 本文用到@Slf4j註解, 也可不引用, 自定義log即可--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency>
JedisUtil
@Component @Slf4j 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) { log.error("set key:{} value:{} error", key, value, e); return null; } finally { close(jedis); } } ..... }
自定義註解@ApiIdempotent
/** * 在需要保證 接口冪等性 的Controller的方法上使用此註解 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface ApiIdempotent { }
ApiIdempotentInterceptor攔截器
/** * 接口冪等性攔截器 */ 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) { check(request);// 冪等性校驗, 校驗通過則放行, 校驗失敗則拋出異常, 並通過統一異常處理返回友好提示 } return true; } private void check(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 { } }
TokenServiceImpl
@Service public class TokenServiceImpl implements TokenService { private static final String TOKEN_NAME = "token"; @Autowired private JedisUtil jedisUtil; @Override public ServerResponse createToken() { String str = RandomUtil.UUID32(); 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()); } } }
TestApplication
@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, 目前爲止, 校驗代碼準備就緒, 接下來測試驗證
七、測試驗證
獲取token的控制器TokenController
@RestController @RequestMapping("/token") public class TokenController { @Autowired private TokenService tokenService; @GetMapping public ServerResponse token() { return tokenService.createToken(); } }
TestController, 注意@ApiIdempotent註解, 在需要冪等性校驗的方法上聲明此註解即可, 不需要校驗的無影響。
@RestController @RequestMapping("/test") @Slf4j public class TestController { @Autowired private TestService testService; @ApiIdempotent @PostMapping("testIdempotence") public ServerResponse testIdempotence() { return testService.testIdempotence(); } }
3. 獲取token
查看redis
4. 測試接口安全性: 利用jmeter測試工具模擬50個併發請求, 將上一步獲取到的token作爲參數。
5. header或參數均不傳token, 或者token值爲空, 或者token值亂填, 均無法通過校驗, 如token值爲"abcd"
八、注意點(非常重要)
上圖中, 不能單純的直接刪除token而不校驗是否刪除成功, 會出現併發安全性問題, 因爲, 有可能多個線程同時走到第46行, 此時token還未被刪除, 所以繼續往下執行, 如果不校驗jedisUtil.del(token)的刪除結果而直接放行, 那麼還是會出現重複提交問題, 即使實際上只有一次真正的刪除操作, 下面重現一下。
稍微修改一下代碼:
再次請求
再看看控制檯
雖然只有一個真正刪除掉token, 但由於沒有對刪除結果進行校驗, 所以還是有併發問題, 因此, 必須校驗。
九、總結
其實思路很簡單, 就是每次請求保證唯一性, 從而保證冪等性, 通過攔截器+註解, 就不用每次請求都寫重複代碼, 其實也可以利用spring aop實現, 無所謂。
如果小夥伴有什麼疑問或者建議歡迎提出。