Java Code Examples for org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setReadTimeout()

The following examples show how to use org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setReadTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestTemplateConfig.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * httpRequestFactory.
 * 
 * @return
 */
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(
            30, TimeUnit.SECONDS);
    // max connection
    pollingConnectionManager.setMaxTotal(constants.getRestTemplateMaxTotal());

    pollingConnectionManager.setDefaultMaxPerRoute(constants.getRestTemplateMaxPerRoute());
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // add Keep-Alive
    httpClientBuilder
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
            new HttpComponentsClientHttpRequestFactory(httpClient);
    clientHttpRequestFactory.setReadTimeout(constants.getHttp_read_timeOut());
    clientHttpRequestFactory.setConnectTimeout(constants.getHttp_connect_timeOut());
    return clientHttpRequestFactory;
}
 
Example 2
Source File: DefaultAppValidationServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private static boolean dockerCheck() {
	boolean result = true;
	try {
		CloseableHttpClient httpClient
				= HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		requestFactory.setConnectTimeout(10000);
		requestFactory.setReadTimeout(10000);

		RestTemplate restTemplate = new RestTemplate(requestFactory);
		System.out.println("Testing access to " + DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "springcloudstream/log-sink-rabbit/tags");
		restTemplate.getForObject(DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "/springcloudstream/log-sink-rabbit/tags", String.class);
	}
	catch(Exception ex) {
		System.out.println("dockerCheck() failed. " + ex.getMessage());
		result = false;
	}
	return result;
}
 
Example 3
Source File: WxApiHttpRequestFactory.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 获取连接工厂
 *
 * @return the result
 */
private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpClient httpClient = getHttpClient();
    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(wxProperties.getInvoker().getConnectTimeout());
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(wxProperties.getInvoker().getReadTimeout());
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(wxProperties.getInvoker().getConnectionRequestTimeout());
    return clientHttpRequestFactory;
}
 
Example 4
Source File: ClientConfig.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Bean
KioOperations kioOperations() {
    final StupsOAuth2RestTemplate restTemplate = new StupsOAuth2RestTemplate(new StupsTokensAccessTokenProvider("kio", accessTokens));
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setConnectTimeout(4 * 1000);
    requestFactory.setReadTimeout(4 * 1000);
    restTemplate.setRequestFactory(requestFactory);
    restTemplate.setErrorHandler(new KioClientResponseErrorHandler());
    return new RestTemplateKioOperations(
            restTemplate,
            kioBaseUrl);
}
 
Example 5
Source File: RESTFacade.java    From zstack with Apache License 2.0 5 votes vote down vote up
static TimeoutRestTemplate createRestTemplate(int readTimeout, int connectTimeout) {
    HttpComponentsClientHttpRequestFactory factory = new TimeoutHttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(readTimeout);
    factory.setConnectTimeout(connectTimeout);

    SSLContext sslContext = DefaultSSLVerifier.getSSLContext(DefaultSSLVerifier.trustAllCerts);

    if (sslContext != null) {
        factory.setHttpClient(HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(sslContext)
                .build());
    }

    TimeoutRestTemplate template = new TimeoutRestTemplate(factory);

    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
    stringHttpMessageConverter.setWriteAcceptCharset(true);
    for (int i = 0; i < template.getMessageConverters().size(); i++) {
        if (template.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
            template.getMessageConverters().remove(i);
            template.getMessageConverters().add(i, stringHttpMessageConverter);
            break;
        }
    }

    return template;
}
 
Example 6
Source File: PdfServerClientConfig.java    From vics with MIT License 5 votes vote down vote up
@Bean
public RestTemplate pdfServerClient() {
    HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    httpRequestFactory.setConnectionRequestTimeout(CONNECT_TIMEOUT);
    httpRequestFactory.setReadTimeout(READ_TIMEOUT);
    httpRequestFactory.setConnectTimeout(CONNECT_TIMEOUT);

    return new RestTemplate(httpRequestFactory);
}
 
Example 7
Source File: RestTemplateFactory.java    From apollo with Apache License 2.0 5 votes vote down vote up
public void afterPropertiesSet() throws UnsupportedEncodingException {
  CloseableHttpClient httpClient = HttpClientBuilder.create().build();

  restTemplate = new RestTemplate(httpMessageConverters.getConverters());
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(httpClient);
  requestFactory.setConnectTimeout(portalConfig.connectTimeout());
  requestFactory.setReadTimeout(portalConfig.readTimeout());

  restTemplate.setRequestFactory(requestFactory);
}
 
Example 8
Source File: ITTracingClientHttpRequestInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
ClientHttpRequestFactory configureClient(ClientHttpRequestInterceptor interceptor) {
  HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
  factory.setReadTimeout(1000);
  factory.setConnectTimeout(1000);
  this.interceptor = interceptor;
  return factory;
}
 
Example 9
Source File: ITTracingClientHttpRequestInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
ClientHttpRequestFactory configureClient(ClientHttpRequestInterceptor interceptor) {
  HttpComponentsClientHttpRequestFactory factory =
    new HttpComponentsClientHttpRequestFactory(httpClient);
  factory.setReadTimeout(1000);
  factory.setConnectTimeout(1000);
  this.interceptor = interceptor;
  return factory;
}
 
Example 10
Source File: CloudControllerRestClientHttpRequestFactory.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
public void increaseReadTimeoutForStreamedTailedLogs(int timeout) {
    // May temporary increase read timeout on other unrelated concurrent
    // threads, but per-request read timeout don't seem easily
    // accessible
    if (delegate instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = (HttpComponentsClientHttpRequestFactory) delegate;

        if (timeout > 0) {
            httpRequestFactory.setReadTimeout(timeout);
        } else {
            httpRequestFactory.setReadTimeout(defaultSocketTimeout);
        }
    }
}
 
Example 11
Source File: RestTemplateFakeReactiveFeign.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <T> ReactiveFeign.Builder<T> builder(ReactiveOptions options) {
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(
          HttpClientBuilder.create().build());
  if (options.getConnectTimeoutMillis() != null) {
    requestFactory.setConnectTimeout(options.getConnectTimeoutMillis());
  }
  if (options.getReadTimeoutMillis() != null) {
    requestFactory.setReadTimeout(options.getReadTimeoutMillis());
  }
  return builder(new RestTemplate(requestFactory),
      options.isTryUseCompression() != null && options.isTryUseCompression());
}
 
Example 12
Source File: BaseApplicationStarter.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Bean
RestTemplate restTemplateNoneLB() {
	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	factory.setConnectTimeout(3000);
	factory.setReadTimeout(30000);
	return new RestTemplate(factory);
}
 
Example 13
Source File: TeamUpAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean(name = EVENT_REST_OPERATIONS)
public RestOperations eventRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(30000);
    factory.setReadTimeout(30000);
    return getRestOperations(factory);
}
 
Example 14
Source File: BackupStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
protected void exceptionIfImageSizeGreaterThanAvailableCapacity(String url) {
    if (CoreGlobalProperty.UNIT_TEST_ON) {
        return;
    }

    url = url.trim();
    if (!url.startsWith("http") && !url.startsWith("https")) {
        return;
    }

    HttpHeaders header;
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT);
    factory.setConnectTimeout(CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
    factory.setHttpClient(HttpClients.createDefault());
    RestTemplate template = new RestTemplate(factory);
    try {
        header = template.headForHeaders(URI.create(url));
        logger.debug(String.format("get header from %s: %s", url, header));
    } catch (Exception e) {
        throw new OperationFailureException(operr("failed to get header of image url %s: %s", url, e.toString()));
    }

    if (header == null) {
        throw new OperationFailureException(operr("failed to get header of image url %s", url));
    }

    long size = header.getContentLength();
    if (size == -1) {
        logger.error(String.format("failed to get image size from url %s, but ignore this error and proceed", url));
    } else if (size < ImageConstant.MINI_IMAGE_SIZE_IN_BYTE) {
        throw new OperationFailureException(operr("the image size get from url %s is %d bytes, " +
                "it's too small for an image, please check the url again.", url, size));
    } else if (size > self.getAvailableCapacity()) {
        throw new OperationFailureException(operr("the backup storage[uuid:%s, name:%s] has not enough capacity to download the image[%s]." +
                        "Required size:%s, available size:%s", self.getUuid(), self.getName(), url, size, self.getAvailableCapacity()));
    }
}
 
Example 15
Source File: ChatbotAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean
@Primary
public RestOperations messageRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(1000);
    factory.setReadTimeout(1000);
    return getRestOperations(factory);
}
 
Example 16
Source File: PromqlTest.java    From promql_java_client with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
	HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
	httpRequestFactory.setConnectTimeout(1000);
	httpRequestFactory.setReadTimeout(2000);
	HttpClient httpClient = HttpClientBuilder.create()
	 .setMaxConnTotal(100)
	 .setMaxConnPerRoute(10)
	 .build();
	httpRequestFactory.setHttpClient(httpClient);
	
	template = new RestTemplate(httpRequestFactory);
}
 
Example 17
Source File: RestTemplateConfig.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@Bean
@LoadBalanced
RestTemplate restTemplate() {
    HttpComponentsClientHttpRequestFactory httpRequestFactory =  new HttpComponentsClientHttpRequestFactory();
    httpRequestFactory.setReadTimeout(3000);
    httpRequestFactory.setConnectTimeout(3000);
    return new RestTemplate(httpRequestFactory);
}
 
Example 18
Source File: HelperImpl.java    From heimdall with Apache License 2.0 4 votes vote down vote up
private HttpComponentsClientHttpRequestFactory httpClientRequestFactory() {
	HttpComponentsClientHttpRequestFactory httpClient = new HttpComponentsClientHttpRequestFactory();
	httpClient.setConnectTimeout(zuulProperty.getHost().getConnectTimeoutMillis());
	httpClient.setReadTimeout(zuulProperty.getHost().getSocketTimeoutMillis());
	return httpClient;
}
 
Example 19
Source File: RestTemplateConfig.java    From LicenseDemo with Apache License 2.0 4 votes vote down vote up
/**
 * ClientHttpRequestFactory接口的另一种实现方式(推荐使用),即:
 * HttpComponentsClientHttpRequestFactory:底层使用Httpclient连接池的方式创建Http连接请求
 * @return HttpComponentsClientHttpRequestFactory
 */
@Bean
public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory(){
	//Httpclient连接池,长连接保持30秒
	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
	
	//设置总连接数
	connectionManager.setMaxTotal(1000);
	//设置同路由的并发数
	connectionManager.setDefaultMaxPerRoute(1000);
	
	//设置header
	List<Header> headers = new ArrayList<Header>();
	headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04"));
	headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
	headers.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"));
	headers.add(new BasicHeader("Connection", "keep-alive"));
	
	//创建HttpClient
       HttpClient httpClient = HttpClientBuilder.create()
               .setConnectionManager(connectionManager)
               .setDefaultHeaders(headers)
               .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) //设置重试次数
               .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) //设置保持长连接
               .build();
	
       //创建HttpComponentsClientHttpRequestFactory实例
       HttpComponentsClientHttpRequestFactory requestFactory = 
			new HttpComponentsClientHttpRequestFactory(httpClient);
	
       //设置客户端和服务端建立连接的超时时间
       requestFactory.setConnectTimeout(5000);
	//设置客户端从服务端读取数据的超时时间
       requestFactory.setReadTimeout(5000);
       //设置从连接池获取连接的超时时间,不宜过长
       requestFactory.setConnectionRequestTimeout(200);
       //缓冲请求数据,默认为true。通过POST或者PUT大量发送数据时,建议将此更改为false,以免耗尽内存
       requestFactory.setBufferRequestBody(false);
       
       return requestFactory;
}
 
Example 20
Source File: TraceRestTemplateInterceptorIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
private ClientHttpRequestFactory clientHttpRequestFactory() {
	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	factory.setReadTimeout(100);
	factory.setConnectTimeout(100);
	return factory;
}