关于如何在项目接口保证幂等性的一点思考
生活随笔
收集整理的這篇文章主要介紹了
关于如何在项目接口保证幂等性的一点思考
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是接口冪等?
接口冪等就是無論客戶端調用服務端接口發起多少次請求,有且只有一次有效。
如何解決冪等問題呢?
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.客戶端在請求接口前先獲取冪等接口,然后在請求接口前寫入請求頭中.
| ldempotent_token | ba4b441e75f2449792fce5eb0ccfa2ab |
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();}} 復制代碼那么按照上述步驟則可以保證接口冪等性(這種方式除了可以處理接口冪等,還能處理其他問題嗎?哈哈哈哈哈哈)
總結
以上是生活随笔為你收集整理的关于如何在项目接口保证幂等性的一点思考的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SRM6.1安装配置指南
- 下一篇: ssh: connect to host