SpringBoot + Redis實現接口的冪等性


SpringBoot + Redis實現接口的冪等性

 

簡介:

冪等性, 通俗的說就是一個接口, 多次發起同一個請求, 必須保證操作只能執行一次。

比如:

  • 訂單接口, 不能多次創建訂單。
  • 支付接口, 重復支付同一筆訂單只能扣一次錢。

產生原因:

  • 1) 點擊提交按鈕兩次;
  • 2) 點擊刷新按鈕;
  • 3) 使用瀏覽器后退按鈕重復之前的操作,導致重復提交表單;
  • 4) 使用瀏覽器歷史記錄重復提交表單;
  • 5) 瀏覽器重復的HTTP請求;
  • 6) nginx重發等情況;

開發過程使用場景

對於數據庫<mysql> 的新增(insert) 和 修改(update)操作需要實現冪等的,因為多次操作會導致結果不一致或者數據重復。而查詢(select)、刪除(delete) 操作是天然冪等的

常用解決方案

1、Mysql 唯一索引,防止新增臟數據
    唯一索引或唯一組合索引來防止新增數據存在臟數據 (當表存在唯一索引,並發新增會報錯)

2、Mysql悲觀鎖(用在修改操作)
獲取數據的時候加鎖獲取, 悲觀鎖使用時一般伴隨事務一起使用,數據鎖定時間可能會很長,根據實際情況選用。

# 注意:id字段一定是主鍵或者唯一索引,不然是鎖表,會死人的 select * from table_xxx where id='xxx' for update; 

3、樂觀鎖(用在修改操作時)
樂觀鎖只是在更新數據那一刻鎖表,其他時間不鎖表,所以相對於悲觀鎖,效率更高。
樂觀鎖的實現方式多種多樣可以通過version或者其他狀態條件:

update table_xxx set name={name},version=version+1 where version={version} 

4、 分布式鎖(修改操作)
redis(jedis、redisson)或zookeeper實現。

5、 select + insert(先查詢再新增,用在新增時)
並發不高的后台系統,或者一些任務JOB,為了支持冪等,支持重復執行,簡單的處理方法是,先查詢下一些關鍵數據,判斷是否已經執行過,在進行業務處理,就可以了。
注意:核心高並發流程不要用這種方法

6、token機制 (SpringBoot + Redis實現)
業務要求: 頁面的數據只能被點擊提交一次
發生原因: 由於重復點擊或者網絡重發,或者nginx重發等情況會導致數據被重復提交
解決辦法:

  • 集群環境:采用token加redis(redis單線程的,處理需要排隊)
  • 單JVM環境:采用token加redis或token加jvm內存

SpringBoot + Redis實現接口冪等,防止重復提交

 

實現原理:

 

 完整代碼:

1: Redis配置,這里就不講了,請參考: https://www.cnblogs.com/dw3306/p/9520741.html

2: 自定義注解 @ApiIdempotent

/** * @Author dw * @ClassName ApiIdempotent * @Description 自定義注解實現接口的冪等性 * @Date 2021/1/30 13:06 * @Version 1.0 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ApiIdempotent { }

 

3: 定義Token接口用於創建、驗證Token

/** * @Author dw * @ClassName ITokenService * @Description 創建Token的接口,主要是生成接口的唯一Token、並且校驗Token * @Date 2021/1/30 13:10 * @Version 1.0 */
public interface ITokenService { /** * 創建Token * @return
     */ String createToken(); /** * 效驗Token * @param request * @return
     */
    boolean checkToken(HttpServletRequest request); }

 

4、定義Token的實現類

/** * @Author dw * @ClassName TokenServiceImpl * @Description * @Date 2021/1/30 13:14 * @Version 1.0 */ @Service public class TokenServiceImpl implements ITokenService { @Autowired RedisUtils redisUtils; @Override public String createToken() { String token = UUID.randomUUID().toString().replaceAll("-", ""); redisUtils.set(token, token, 10000L); return token; } @Override public boolean checkToken(HttpServletRequest request) { // 檢查請求信息是否攜帶Token
        String token = request.getHeader("token"); if (StringUtils.isEmpty(token)) { // head中不存在檢查parameter
            token = request.getParameter("token"); if(StringUtils.isEmpty(token)){ throw new RuntimeException("沒有獲取到訪問接口的Token字段"); } } // 檢查redis中是否存在key,如果不存在說明之前該接口已經請求過了
        if (!redisUtils.hasKey(token)) { throw new RuntimeException("重復請求"); } // 效驗成功,刪除Token
        boolean remove = redisUtils.del(token); /** * 這里要注意:不能單純的直接刪除token而不校驗token是否刪除成功,會出現並發安全問題 * 在多線程情況下,此時token還未被刪除,繼續向下執行 */
        if (!remove) { throw new RuntimeException("token delete fail"); } return true; } }

 

RedisUtil

/** * 刪除緩存,支持批量刪除 * * @param key */
    public boolean del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { return redisTemplate.delete(key[0]); } else { Long delete = redisTemplate.delete(Arrays.asList(key)); if(delete > 0){ return true; } return false; } } return false; } /** * 設置值並設置過期時間(單位秒) * * @param key * @param value * @param time 過期時間 * @return
     */
    public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { log.error(e.getMessage()); return false; } }

 

5、自定義攔截器

/** * @Author dw * @ClassName ApiIdempotentInterceptor * @Description 接口冪等性攔截器 * @Date 2021/1/30 21:52 * @Version 1.0 */ @Component public class ApiIdempotentInterceptor implements HandlerInterceptor { @Autowired private TokenServiceImpl tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); ApiIdempotent apiIdempotent = method.getAnnotation(ApiIdempotent.class); if (apiIdempotent != null) { // 冪等性校驗,通過則放行;失敗拋出異常,統一異常處理返回友好提示
 tokenService.checkToken(request); } // 這里必須返回true,否則會攔截一切請求
        return true; } }

 

6、注冊攔截器

/** * @Author dw * @ClassName MyWebMvcConfig * @Description * @Date 2021/1/30 22:16 * @Version 1.0 */ @Configuration public class MyWebMvcConfig extends WebMvcConfigurationSupport { @Autowired private ApiIdempotentInterceptor apiIdempotentInterceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(apiIdempotentInterceptor); super.addInterceptors(registry); } }

 

7、測試

/** * @Author dw * @ClassName TestApiIdempotentController * @Description 測試接口冪等性 * @Date 2021/1/30 22:21 * @Version 1.0 */ @RestController public class TestApiIdempotentController { @Resource private ITokenService tokenService; @GetMapping("/getToken") public String getToken() { String token = tokenService.createToken(); return token; } @ApiIdempotent @PostMapping("/testIdempotent") public String testIdempotent() { try { // 模擬業務執行耗時
            Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } return "SUCCESS"; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM