pom.xml中添加Hystrix的引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
启动类添加注解@EnableCircuitBreaker
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
修改在ribbon测试中的类添加service
@Service
public class ConsumerService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="helloFallBack")
public String consumerService() {
return restTemplate.getForEntity("http://HELLO-SERVER/provider", String.class).getBody();
}
public String helloFallBack() {
return "error";
}
}
controller类
@RestController
public class ConsumerController {
@Autowired
ConsumerService consumerService;
@RequestMapping("/ribbon-consumer")
public String hello() {
return consumerService.consumerService();
}
}