基于接口幂等性解决方案

接口幂等性是指无论调用接口的次数是一次还是多次,对于同一资源的操作都只会产生一次结果。换句话说,多次重复调用相同的接口请求应该具有与单次请求相同的效果,不会导致不一致或副作用的发生。
今天我们使用ai帮我们去创建一个自定义 注解 ,可以防止接口30秒内的重复请求,并采用redis作为缓存。
提问话不多说,直接提问:
等待数分钟后。。。
1.创建自定义注解 其中包括接口保护时长,开启防止重复提交保护等。
2.然后创建拦截器
这里我们贴出拦截器的核心代码:
@override public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { if (handler instanceof handlermethod) { handlermethod handlermethod = (handlermethod) handler; repeatsubmit annotation = handlermethod.getmethodannotation(repeatsubmit.class); if (annotation != null && annotation.enable()) { string key = buildkey(request); if (stringutils.hastext(redistemplate.opsforvalue().get(key))) { response.getwriter().write(repeat request, please try again later!); return false; } else { redistemplate.opsforvalue().set(key, arrays.tostring(request.getinputstream().readallbytes()), annotation.timeout(), timeunit.seconds); } } } return true; } //创建redis 缓存key private string buildkey(httpservletrequest request) throws ioexception, nosuchalgorithmexception { string key = userequestmd5 ? hashrequest(request) : request.getrequesturi(); return repeat-submit: + key; } //对请求做hash运算 private string hashrequest(httpservletrequest request) throws ioexception, nosuchalgorithmexception { byte[] hashbytes = messagedigest.getinstance(md5).digest(request.getinputstream().readallbytes()); stringbuilder sb = new stringbuilder(); for (byte b : hashbytes) { sb.append(string.format(%02x, b)); } return sb.tostring(); }3.注册拦截器
最后给出的解释与使用方法。
上面就是最关键的代码了。
接入redis下面我们接入redis。最精简的配置版本
spring: data: redis: host: 127.0.0.1 port: 6379接口使用注解@restcontrollerpublic class repeattestcontroller { @repeatsubmit @getmapping(/hello/mono1) public mono mono(){ return mono.just(hello mono - java north); } @repeatsubmit @postmapping (/hello/mono1) public mono mono1(@requestbody user user){ return mono.just(hello mono - java north-+user.getname()); }}本地起一个redis,然后启动本地的springboot项目进行测试,
本地接口测试:30秒内重复请求会需要直接被拦截
redis中缓存的key如下:
以上就是利用ai为我们生成的一个简单的接口短时间内防止重复提交的注解代码!
相关代码在文章末尾,需要的话可以白嫖哈!
接口幂等性解决方案下面问一下接口幂等性解决方案,
关于这个回答,大家觉得怎么样?

无源滤波和有源滤波讲解
云计算领域的发展可以分为哪三个阶段?
三相交流电源的输送方式
小米11标准版用户可申请一分钱包邮充电器套装
陕西电信携手产业各方一起打造天翼超高清/云VR生态圈
基于接口幂等性解决方案
中国网约车市场总体呈现快速反弹态势,已恢复至6成
高通骁龙855正式发布多项技术领先行业对手
聚飞光电上半年营收11.26亿,背光和照明稳定增长
工信部公布:4G用户总数已达10.8亿户,使用手机上网的用户达12.2亿户
福晶科技:主要向华为销售光学类产品,未参与芯片研发
吸尘器排行榜,用科技开启洁净生活
搜索和推荐的区别与联系
RealWear推出一款防爆型工业头戴平板电脑
安卓进化到牛轧糖(Android 7.0) 是否能摆脱卡顿跟碎片化问题再见
如何合理安装行星齿轮减速电机?
凌力尔特发布隔离型单片反激式稳压器LT3512MP
Micro LED迎来两大增长机遇 巨量转移成Micro LED产业化“拦路虎”
NVIDIA云游戏正式支持苹果M1
安森美行业首创的云联接平台Strata Developer Studio简化并加快您的研发、评估和设计