在分布式环境中,服务之间交互的故障是不可避免的。Hystrix是Netflix的一个库。Hystrix隔离了服务之间的访问点,阻止了它们之间的级联故障并提供了后备选项。
在本文章中,您将看到如何在Spring Boot应用程序中实现Hystrix。
Maven用户可以在pom.xml文件中添加以下依赖项
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
将@EnableHystrix注释添加到主Spring Boot应用程序类文件中;用于将Hystrix功能启用到Spring Boot应用程序中。
@SpringBootApplication
@EnableHystrix
public class HystrixappApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixappApplication.class, args);
}
}
编写一个简单的Rest Controller,Thread.sleep(3000);这里我们假设服务之间的调用延迟或者业务处理耗时,使其在请求的时间3秒后返回String。
@RequestMapping(value = "/")
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
现在,为Rest API添加@Hystrix命令和@HystrixProperty,并以毫秒为单位定义超时值1000毫秒。
@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value="1000")})
@RequestMapping(value = "/")
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
fallbackMethod = "fallback_hello"指定了请求超时的回调方法;新建回调方法:
private String fallback_hello() {
return "Request fails. It takes long time to response";
}
此处显示包含REST API和Hystrix属性的完整Rest Controller类文件 -
@SpringBootApplication
@EnableHystrix
@RestController
public class HystrixappApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixappApplication.class, args);
}
@RequestMapping(value = "/")
@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value =
"1000")})
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
private String fallback_hello() {
return "Request fails. It takes long time to response";
}
}
启动HystrixappApplication 后;从Web浏览器中点击URL http:// localhost:8080 /,然后查看Hystrix响应。API需要3秒钟才能响应,但Hystrix超时为1秒。因此返回: