【发布时间】:2016-09-22 02:25:51
【问题描述】:
我已经为 Zuul 配置了到其他微服务的静态路由。有没有办法在调用其他服务时启用 CircuitBreaker?
【问题讨论】:
标签: spring-cloud netflix-zuul circuit-breaker
我已经为 Zuul 配置了到其他微服务的静态路由。有没有办法在调用其他服务时启用 CircuitBreaker?
【问题讨论】:
标签: spring-cloud netflix-zuul circuit-breaker
正如你所说,Zuul 会自动将每个路由包装在 Ribbon 和 Hystrix 中。但是在微服务之间集成Ribbon 和Hystrix 也很容易。您还可以使用Feign 来处理 REST 调用。
假设您有两个服务serviceA 和serviceB,并且您希望serviceA 使用Ribbon 和Hystrix 调用serviceB。假设您在 localhost 和默认端口 (8761) 上运行 Eureka 服务器
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceAapplication{
public static void main(String[] args) {
SpringApplication.run(ServiceAapplication.class, args);
}
}
@RestController()
@RequestMapping("/rest")
class DummyRestController{
@RequestMapping(method = RequestMethod.GET, path = "/hello")
String hello(){
return "Hello World!";
}
}
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableFeignClients
public class ServiceBapplication{
public static void main(String[] args) {
SpringApplication.run(ServiceBapplication.class, args);
}
}
@FeignClient(value = "serviceA") //must be same name as the service name in Eureka
@RibbonClient(name = "serviceA") //must be same name as the service name in Eureka
interface ServiceAClient {
@RequestMapping(method = RequestMethod.GET, value = "/rest/hello")
String helloFromServiceA();
}
@RestController()
@RequestMapping("/foo")
class DummyRestController{
private final ServiceAclient client;
@Autowired
DummyRestController(ServiceAclient client){
this.client = client;
}
@RequestMapping(method = RequestMethod.GET, path = "/bar")
String hello(){
return client.helloFromServiceA();
}
}
现在,如果您使用 foo/bar 在 serviceB 上执行 GET,它将使用:
serviceA 的主机和端口
serviceA 的多个实例之间进行负载平衡的功能区
Hystrix 命令中由于@EnableCircuitBreaker 注释,您的serviceB 将公开Hystrix 流。如果您运行HystrixDashboard 服务器,您可以连接到此流,您将在仪表板上看到helloFromServiceA 命令。
您可以在通常的配置文件中配置Ribbon 和Hystrix,也可以在@FeignClient 和@RibbonClient 注释中使用单独的配置类。你可以找到更多信息here
重要提示:如果您希望Ribbon 在超时期间重试不同的实例,请确保Hystrix 超时高于Ribbon 超时。见this answer
【讨论】: