简体   繁体   中英

Asynchronous HTTP request in Coldfusion

How do I do Asynchronous HTTP requests using CFHTTP tag?

I am looping over a Query result and send some data to a URL via HTTP post. There are lots of records in the query so cfhttp takes lots of time.

Is it possible to send asynchronous HTTP request in ColdFusion? Somebody suggested to me that I can create a thread and call cfhttp inside that. Is there any other way than cfthread?

As @peter-boughton suggested, use threads.

In CF 9.0.1 there is a bug with http inside a thread.

So, here's a quick prototype I did:

// cf_sucks_workaround.cfc
component extends="com.adobe.coldfusion.base" {
  public function cacheScriptObjects() {

    local.tags = ["CFFTP", "CFHTTP", "CFMAIL", "CFPDF", "CFQUERY",
      "CFPOP", "CFIMAP", "CFFEED", "CFLDAP"];

    for(local.tag in local.tags) {
      getSupportedTagAttributes(local.tag);
    }
  }
}
// async_http.cfm
<cfscript>
lg('start');
main();
lg('done');

void function main() {
    CreateObject('component', 'cf_sucks_workaround').cacheScriptObjects();
    startThreads();
}

void function lg(required string txt) {
    WriteLog(file = 'threads', text = "t#threadNum()# #arguments.txt#");
}

void function sendRequest() {
    var httpService = new http(timeout = "3", url = "https://www.google.com");
    lg('send http req.');
    var httpResult = httpService.send().getPrefix();
    lg(httpResult.StatusCode);
}

void function startThreads() {
    for (local.i = 1; i LTE 3; i++) {
        thread action="run" name="thread_#i#" appname="derp" i="#i#" {
            lg("start");
            sendRequest();
            lg("end");
        }
    }
}

numeric function threadNum() {
    return (IsDefined('attributes') AND StructKeyExists(attributes, 'i')) ? attributes.i : 0;
}

</cfscript>

Produces log output:

t0 start
t0 done
t1 start
t2 start
t3 start
t3 send http req.
t1 send http req.
t2 send http req.
t3 200 OK
t3 end
t1 200 OK
t1 end
t2 200 OK
t2 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM