Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire and forget for HTTP in Java

We're implementing our own analytics for that we've exposed a web service which needs to be invoked which will capture the data in our DB.

The problem is that as this is analytics we would be making lot of calls (like for every page load, call after each js, CSS loads etc...) so there'll be many many such calls. So I don want the server to be loaded with lots of requests to be more precise pending for response. Because the response we get back will hardly be of any use to us.

So is there any way to just fire the web service request and forget that I've fired it?

I understand that every HTTP request will have as response as well.

So one thing that ticked my mind was what if we make the request timeout to zero second? But I'm pretty not sure if this is the right way of doing this.

Please provide me with more suggestions

like image 574
Gokul Kulkarni Avatar asked Jul 09 '16 01:07

Gokul Kulkarni


2 Answers

You might find following AsyncRequestDemo.java useful:

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;

/**
 * Following libraries have been used:
 * 
 * 1) httpcore-4.4.5.jar
 * 2) httpclient-4.5.2.jar
 * 3) commons-logging-1.2.jar
 * 4) fluent-hc-4.5.2.jar     * 
 *
 */

public class AsyncRequestDemo {
    public static void main(String[] args) throws Exception {
    URIBuilder urlBuilder = new URIBuilder()
                               .setScheme("http")
                               .setHost("stackoverflow.com")
                               .setPath("/questions/38277471/fire-and-forget-for-http-in-java");

    final int nThreads = 3; // no. of threads in the pool
    final int timeout = 0; // connection time out in milliseconds

    URI uri = null;
    try {
        uri = urlBuilder.build();
    } catch (URISyntaxException use) {
        use.printStackTrace();
    }

    ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
    Async async = Async.newInstance().use(executorService);
    final Request request = Request.Get(uri).connectTimeout(timeout);

        Future<Content> future = async.execute(request, new FutureCallback<Content>() {
            public void failed(final Exception e) {
                System.out.println("Request failed: " + request);
                System.exit(1);
            }

            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
                System.out.println(content.asString());
                System.exit(0);
            }

            public void cancelled() {
            }
        });

        System.out.println("Request submitted");

    }

}
like image 126
Sanjeev Saha Avatar answered Nov 03 '22 23:11

Sanjeev Saha


I used this:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

  URL url = new URL(YOUR_URL_PATH, "UTF-8")); 
               ExecutorService executor = Executors.newFixedThreadPool(1); 
               Future<HttpResponse> response = executor.submit(new HttpRequest(url));
               executor.shutdown();

for HttpRequest,HttpResponse

public class HttpRequest implements Callable<HttpResponse> {
        private URL url;

        public HttpRequest(URL url) {
            this.url = url;
        }

        @Override
        public HttpResponse call() throws Exception {
            return new HttpResponse(url.openStream());
        }
}

public class HttpResponse {
     private InputStream body;

        public HttpResponse(InputStream body) {
            this.body = body;
        }

        public InputStream getBody() {
            return body;
        }
}

that is.

like image 44
IbrahimAsad Avatar answered Nov 03 '22 22:11

IbrahimAsad