1、pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、application.yml
eureka:
client:
serviceUrl: #注册中心的注册地址
defaultZone: http://127.0.0.1:7001/eureka/
server:
port: 9003 #服务端口号
spring:
application:
name: service-consumer #服务名称--调用的时候根据名称来调用该服务的方法
3、EurekaConsumer_hystrix_9003
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker//该注解是开启断路器功能
public class EurekaConsumer_hystrix_9003 {
@Bean
@LoadBalanced //启用负载均衡机制
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(EurekaConsumer_hystrix_9003.class, args);
}
}
4、TestController
@RestController
public class TestController {
private final String url = "http://service-provider";
@Autowired
RestTemplate restTemplate;
@RequestMapping("/get")
@HystrixCommand(fallbackMethod = "getFallbackMethod", commandKey = "get")//熔断器指定操作的方法
public String getUser() {
return restTemplate.getForObject(url + "/get", String.class);
}
//熔断器方法 建议把熔断方法放在service中去处理
public String getFallbackMethod() {
return "error";
}
}