|
| 1 | +package com.baeldung.hystrix; |
| 2 | + |
| 3 | +import com.netflix.hystrix.HystrixCommand; |
| 4 | +import com.netflix.hystrix.HystrixCommandGroupKey; |
| 5 | +import com.netflix.hystrix.HystrixCommandProperties; |
| 6 | +import org.apache.http.client.config.RequestConfig; |
| 7 | +import org.apache.http.client.methods.HttpGet; |
| 8 | +import org.apache.http.impl.client.HttpClientBuilder; |
| 9 | +import org.apache.http.message.BasicHeader; |
| 10 | +import org.apache.http.util.EntityUtils; |
| 11 | + |
| 12 | +import java.net.URI; |
| 13 | +import java.util.Collections; |
| 14 | + |
| 15 | +/** |
| 16 | + * @author aiet |
| 17 | + */ |
| 18 | +public class HystrixSyncHttpCommand extends HystrixCommand<String> { |
| 19 | + |
| 20 | + private URI uri; |
| 21 | + private RequestConfig requestConfig; |
| 22 | + |
| 23 | + HystrixSyncHttpCommand(URI uri, int timeoutMillis) { |
| 24 | + super(Setter |
| 25 | + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync")) |
| 26 | + .andCommandPropertiesDefaults(HystrixCommandProperties |
| 27 | + .Setter() |
| 28 | + .withExecutionTimeoutInMilliseconds(timeoutMillis))); |
| 29 | + requestConfig = RequestConfig |
| 30 | + .custom() |
| 31 | + .setSocketTimeout(timeoutMillis) |
| 32 | + .setConnectTimeout(timeoutMillis) |
| 33 | + .setConnectionRequestTimeout(timeoutMillis) |
| 34 | + .build(); |
| 35 | + this.uri = uri; |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + protected String run() throws Exception { |
| 40 | + HttpGet request = new HttpGet(uri); |
| 41 | + return EntityUtils.toString(HttpClientBuilder |
| 42 | + .create() |
| 43 | + .setDefaultRequestConfig(requestConfig) |
| 44 | + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) |
| 45 | + .build() |
| 46 | + .execute(request) |
| 47 | + .getEntity()); |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + protected String getFallback() { |
| 52 | + return "eugenp's sync fallback profile"; |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments