Asynchronous HTTP request in Coldfusion

How do I make asynchronous HTTP requests using the CFHTTP tag?

I am looping over the result of the request and posting some data to the url via an HTTP post. There are many entries in the request, so cfhttp takes a long time.

Can I make an asynchronous HTTP request in ColdFusion? Someone suggested to me that I can create a stream and call cfhttp inside it. Is there any other way than cfthread?

+3


source to share


1 answer


As @ peter-boughton suggested, use streams.

CF 9.0.1 has a bug with http inside a stream.

So, here's a quick prototype I made:



// 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

      

+1


source







All Articles