Spring Cloud——Hystrix断路器
(本文只作为学习记录)
使用前文的工程,运行 服务注册中心 ,运行两个 服务提供者 ,运行 服务消费者 。当我们不断的刷新 服务消费者的链接 时,可以看到URL在不断的变化。当我们关闭其中一个服务提供者的时候,再次不断刷新服务消费者,我们会发现其中一个服务不可用从而出错。
改造 服务消费者,在pom.xml文件中加入以下依赖:
<!--断路器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
在启动类中添加注解
@EnableCircuitBreaker
。新建service层HelloService类,加入以下代码
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
//指定出错方法
@HystrixCommand(fallbackMethod = "helloServiceFallback")
public String helloService() {
return restTemplate.getForEntity("http://HELLO/hello", String.class).getBody();
}
public String helloServiceFallback() {
return "error";
}
}
- web层ConsumerController修改如下:
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
@GetMapping(value = "/ribbonService")
public String helloConsumer() {
return helloService.helloService();
}
}
- 启动两个服务提供者和一个服务消费者,看到服务注册中心已经有三个注册的服务实例。不断刷新服务消费者链接,可以看到请求URL在不断的变化,关闭其中一个服务提供者,再次不断刷新服务消费者链接,看到会执行指定的出错方法。