Sto facendo HTTP POST molto frequentemente (> = 1/sec) a un endpoint API e voglio assicurarmi che lo stia facendo in modo efficiente. Il mio obiettivo è riuscire o fallire il prima possibile, soprattutto perché ho un codice separato per riprovare i POST falliti. C'è una bella pagina di HttpClient performance tips, ma non sono sicuro che l'implementazione esaustiva di tutti avrà reali benefici. Ecco il mio codice adesso:Come posso riutilizzare una connessione HttpClient in modo efficiente?
public class Poster {
private String url;
// re-use our request
private HttpClient client;
// re-use our method
private PostMethod method;
public Poster(String url) {
this.url = url;
// Set up the request for reuse.
HttpClientParams clientParams = new HttpClientParams();
clientParams.setSoTimeout(1000); // 1 second timeout.
this.client = new HttpClient(clientParams);
// don't check for stale connections, since we want to be as fast as possible?
// this.client.getParams().setParameter("http.connection.stalecheck", false);
this.method = new PostMethod(this.url);
// custom RetryHandler to prevent retry attempts
HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
// For now, never retry
return false;
}
};
this.method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
}
protected boolean sendData(SensorData data) {
NameValuePair[] payload = {
// ...
};
method.setRequestBody(payload);
// Execute it and get the results.
try {
// Execute the POST method.
client.executeMethod(method);
} catch (IOException e) {
// unable to POST, deal with consequences here
method.releaseConnection();
return false;
}
// don't release so that it can be reused?
method.releaseConnection();
return method.getStatusCode() == HttpStatus.SC_OK;
}
}
Avrebbe senso disattivare il controllo per connessioni stantie? Dovrei guardare usando lo MultiThreadedConnectionManager? Ovviamente, il benchmarking effettivo mi sarebbe d'aiuto ma volevo verificare se il mio codice fosse sulla strada giusta.
È ironico che ho ottenuto il badge Domanda popolare (oltre 1000 visualizzazioni) nonostante non ci siano state risposte. Se hai qualche suggerimento, rispondere a questo potrebbe essere un buon modo per guadagnare un po 'di reputazione. ;-) – pr1001
https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html –