Pergunta

Estou fazendo POSTs HTTP muito frequentemente (> = 1 / s) para um desfecho API e eu quero ter certeza que eu estou fazendo isso de forma eficiente. Meu objetivo é ter sucesso ou falhar, logo que possível, especialmente desde que eu tenho código separado para repetir pinos apresentaram falhas. Há uma página agradável de HttpClient dicas de desempenho , mas eu não sou certeza se exaustivamente implementar todos eles terão benefícios reais. Aqui está o meu código agora:

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;
  }
}

Será que faz sentido para desativar a verificação de conexões obsoletos? Devo estar a olhar para usando o MultiThreadedConnectionManager ? Claro, o benchmarking real ajudaria, mas eu queria verificar se o meu código está no caminho certo em primeiro lugar.

Foi útil?

Solução

Grande parte do desempenho atingido de conexões HTTP é estabelecer a conexão socket. Você pode evitar isso usando conexões 'keep-alive' http. Para fazer isso, é melhor usar HTTP 1.1 e certifique-se de que "Content-Length: xx" é sempre definido em solicitações e respostas, "Connecction: fechar" está corretamente definido quando apropriado e está devidamente postas em prática quando recebeu

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top