Skip to content

Instantly share code, notes, and snippets.

@DirkLachowski
Created August 9, 2015 12:28
Show Gist options
  • Save DirkLachowski/288edb8d28ed3dfd7120 to your computer and use it in GitHub Desktop.
Save DirkLachowski/288edb8d28ed3dfd7120 to your computer and use it in GitHub Desktop.
// Base command handling REST-template setup
package net.lacho.es.adminapi.hystrix;
import io.cobai.commons.middletier.CommandResponse;
import java.io.IOException;
import java.util.Arrays;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class BaseCommand implements InitializingBean {
@Autowired private LoadBalancerInterceptor interceptor;
private final RestTemplate restTemplate = new RestTemplate();
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void afterPropertiesSet() throws Exception {
restTemplate.setInterceptors(Arrays.asList(interceptor));
restTemplate.setErrorHandler(new CobaiResponseErrorHandler());
}
protected RestTemplate getRestTemplate() {
return restTemplate;
}
private class CobaiResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (HttpStatusCodeException responseException) {
try {
CommandResponse error = mapper.readValue(responseException.getResponseBodyAsString(), CommandResponse.class);
throw new RestException(responseException.getStatusCode(), error);
} catch (IOException mappingException) {
throw responseException;
}
}
}
}
}
// Later...
package net.lacho.es.adminapi.hystrix;
import net.lacho.es.adminapi.domain.CustomerSearchResult;
import org.springframework.stereotype.Component;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Component
public class GetCustomersCommand extends BaseCommand {
@HystrixCommand(
fallbackMethod = "fallbackCommand",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000")})
public CustomerSearchResult getCustomers(String query, int page, int limit) {
return getRestTemplate().getForObject("http://platform-contracts/customers?query={query}&page={page}&limit={limit}", CustomerSearchResult.class, query, page, limit);
}
public CustomerSearchResult fallbackCommand(String query, int page, int limit) {
return CustomerSearchResult.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment