第一步加入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
第二步:编写配置文件application.properties
spring.application.name=ribbon-hystrix
server.port=8787
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.metadata-map.zone=beijing
spring.cloud.loadbalancer.retry.enabled=true
#hystrix.command.default.execution.timeout.enabled=false
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
第三步:编写启动类
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringCloudApplication
public class EurekaClientRibbonHystrixApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(EurekaClientRibbonHystrixApplication.class, args);
}
}
第四步:测试
@RestController
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@Autowired
DiscoveryClient client;
@RequestMapping(value = "/add", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "fallback" )
public String add() throws InterruptedException {
return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
}
public String fallback(){
return "error";
}
}