日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于如何在项目接口保证幂等性的一点思考

發布時間:2025/3/17 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于如何在项目接口保证幂等性的一点思考 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是接口冪等?

接口冪等就是無論客戶端調用服務端接口發起多少次請求,有且只有一次有效。

如何解決冪等問題呢?

1.暴露獲取冪等token接口,且在此時存儲redis、mysql、本地內存等(可根據具體業務場景選擇token存儲方式)

@Autowired private RedissonClient redissonClient;private String createToken(){return UUID.randomUUID().toString().replace("-",""); }@GetMapping("/getLdempotentToken")public Response<String> getLdempotentToken(){RMapCache<String,String> rMapCache = redissonClient.getMapCache(LdempotentAspect.LDEMPOTENT_TONE);String token = createToken();rMapCache.put(token,token);return Response.ok(token);} 復制代碼

2.客戶端在請求接口前先獲取冪等接口,然后在請求接口前寫入請求頭中.

keyvalue
ldempotent_tokenba4b441e75f2449792fce5eb0ccfa2ab

3.利用spring aop技術代碼需要處理冪等接口。在執行接口之前驗證客戶端請求頭中的冪等token,驗證成功則刪除token,驗證失敗則直接返回錯誤信息.

@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Ldempotent {} 復制代碼@Slf4j @Component @Aspect public class LdempotentAspect {public static final String LDEMPOTENT_TONE = "ldempotent_token";@Autowiredprivate RedissonClient redissonClient;@Pointcut("@annotation(com.fast.family.framework.core.redis.ldempotent.Ldempotent)")public void pointcut(){}@Around("pointcut()")public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {String token = Optional.ofNullable(WebUtils.getRequestHeader(LDEMPOTENT_TONE)).orElseThrow(() -> new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode(),ResponseCode.LDEMPOTENT_ERROR.getMsg()));RMapCache<String,String> rMapCache = redissonClient.getMapCache(LDEMPOTENT_TONE);Optional.ofNullable(rMapCache.get(token)).orElseThrow(() -> new LdempotentException(ResponseCode.LDEMPOTENT_ERROR.getCode(),ResponseCode.LDEMPOTENT_ERROR.getMsg()));rMapCache.remove(rMapCache.get(token));//token一次有效,所以在驗證完后需刪除return proceedingJoinPoint.proceed();}} 復制代碼

那么按照上述步驟則可以保證接口冪等性(這種方式除了可以處理接口冪等,還能處理其他問題嗎?哈哈哈哈哈哈)

總結

以上是生活随笔為你收集整理的关于如何在项目接口保证幂等性的一点思考的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。