Spring Cloud Hystrix
定义:当线程调用服务时,因为服务的故障而出现长时间的等待的情况时,hystrix会返回一个错误响应,防止该线程长时间挂起而影响其他线程的性能。我们将之称为断路器。
1 快速开始
首先启动一个Eureka服务,端口为7001,服务名叫做sb-eureka
然后启动两个provider服务,端口为7011和7021,服务名都叫做sb-provider,都注册到sb-eureka服务注册中心上,两个服务的controller都有Provider.getName()方法,且一个返回“张三”,一个返回“李四”。
最后编写hystrix服务,端口为7041,服务名叫做sb-hystrix,也注册到sb-eureka服务注册中心上。通过RestTemplate启动了默认的线性轮询均衡负载。
接下俩详细看一下hystrix的代码,另外两部分代码请自行编写。
配置文件application.yml;
spring:
application:
name: sb-hystrix
server:
port: 7041eureka:
client:
register-with-eureka: true
service-url:
defaultZone: http://root:root@localhost:7001/eureka
pom文件:<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--Hystrix依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
入口启动类:HystrixApplication;
@SpringBootApplication
@EnableEurekaClient
/*注释开启断路器功能*/
@EnableCircuitBreaker
public class HystrixApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
Controller类HystrixController;
@RestController
@RequestMapping("Hystrix")
public class HystrixContreoller {
@Autowired
private RestTemplate restTemplate;
@GetMapping("getName")
//该注解指定断路器返回的错误响应方法为errorBack()
@HystrixCommand(fallbackMethod = "errorBack")
public Object hystixController(){
return restTemplate.getForObject("http://sb-provider/Provider/getName",String.class);
}
String errorBack(){
return "服务器挂啦";
}
}
此时进入localhost:7001的注册中心界面,可以看到此时有两个sb-providre和一个sb-hystrix服务已经注册到该注册中心上。
当我们访问localhost:7041/Hystrix/getName时,会依次返回“张三”和“李四”。
此时的sb-provider服务都健壮的运行着,无法触发断路器。
现在我们将sb-provider中的一个服务关闭,依然访问localhost:7041/Hystrix/getName时,就会经常返回“服务器挂啦”,说明此时的断路器起作用了。