分布式系统Spring Boot整合Netflix之Hystrix

在分布式环境中,服务之间交互的故障是不可避免的。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秒。因此返回:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值