org.springframework.cloud
spring-cloud-starter-hystrix
- 在eureka-ribbon的主类
RibbonApplication
中使用@EnableCircuitBreaker
注解开启断路器功能:
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
- 改造原来的服务消费方式,新增
ComputeService
类,在使用ribbon消费服务的函数上增加@HystrixCommand
注解来指定回调方法。
@Service
public class ComputeService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = “addServiceFallback”)
public String addService() {
return restTemplate.getForEntity(“http://COMPUTE-SERVICE/add?a=10&b=20”, String.class).getBody();
}
public String addServiceFallback() {
return “error”;
}
}
- 提供rest接口的Controller改为调用ComputeService的addService
@RestController
public class ConsumerController {
@Autowired
private ComputeService computeService;
@Reques