ColdFusion非预期并发CFHTTP调用问题排查
ColdFusion应用在Apache环境下出现非预期API并发调用,触发第三方API限制
问题描述
我正在开发一个从第三方服务拉取数据的ColdFusion应用,需要获取超过5000条记录。第三方API有明确的调用限制,且通过分页返回数据,但我的代码在开发环境中出现了非预期的并发调用,触发了API限制并导致数据库重复数据。
API限制说明
- 同一API用户账户不允许并发调用同一端点
- 分页机制:每次调用最多返回500条结果,通过响应中的
nextPageUrl获取下一页数据,直到nextPageUrl为null时停止拉取
代码实现
数据拉取函数
<cffunction name="getAPIdata" access="public" returntype="boolean" output="yes"> <cfset local.result = false> <cfset local.apiUrl = "[INITIAL API CALL URL HERE]"> <cfset local.apiCallComplete = false> <cfloop condition="local.apiCallComplete IS FALSE"> <cfhttp url="#local.apiUrl#" method="get" result="local.res" throwOnError="no"> <cfhttpparam type="header" name="Content-Type" value="application/json"> <cfhttpparam type="header" name="Credentials" value="[API USER CREDENtIALS HERE]"> </cfhttp> <cfset local.data = deserializeJSON(local.res.fileContent)> <cfquery> <!--- Loop over local.data array and insert into db ---> </cfquery> <!--- Write call results to log file and increment count (for testing) ---> <cfif isDefined("local.data.nextPageUrl")> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="Count: #count#"> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="Next page: #urlDecode(local.data.nextPageUrl)#"> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="-------------------------------------------------------------------------------------------"> <cfset count++> <cfset local.apiUrl = urlDecode(local.data.nextPageUrl)> <cfelse> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="Count: #count#"> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="Next page: NONE"> <cffile action="append" addnewline="true" file="#expandpath('../log.txt')#" output="-------------------------------------------------------------------------------------------"> <cfset local.result = true> <cfset local.apiCallComplete = true> </cfif> </cfloop> <cfreturn local.result> </cffunction>
函数调用代码
<cfset count = 1> <cfset getAPIdata()>
问题现象
- 日志文件中重复出现相同的
count值和nextPageUrl记录,表明存在多个并发的API调用序列 - 触发第三方API的并发调用限制警告
- 数据库中出现重复插入的记录
- 尝试用
cflock包裹循环内的代码后,问题未解决,日志仍会出现新的调用序列从头开始的情况
环境信息
- 开发环境:ColdFusion 2018 + Apache 2.4 + MySQL
- 生产环境:ColdFusion 2018 + IIS + MySQL
最新进展
在生产环境(IIS)中测试原代码完全正常,推测问题出在Apache的配置(比如URL重写规则)或开发环境的其他设置上,而非ColdFusion代码本身。
内容的提问来源于stack exchange,提问作者amac828
相关产品推荐
相关产品推荐

