Hystrix简介
在微服务架构中,通常有多层服务调用。
较低级别的服务中的服务故障可能导致用户级联故障。当对特定服务的呼叫达到一定阈值时(Hystrix中的默认值为5秒内的20次故障),电路打开,不进行通话。在错误和开路的情况下,开发人员可以提供后备。
开放式电路会停止级联故障,并允许不必要的或失败的服务时间来愈合。回退可以是另一个Hystrix保护的调用,静态数据或一个正常的空值。回退可能被链接,所以第一个回退使得一些其他业务电话又回到静态数据。
Ribbon引入Hystrix
pom.xml 引入 spring-cloud-starter-hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
启动主类加@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class EurekaClientRibbon2Application {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(EurekaClientRibbon2Application.class, args);
}
}
服务调用处加@HystrixCommand
@RestController
public class TestController {
@Autowired
public RestTemplate restTemplate;
@GetMapping("/test2")
@HystrixCommand(defaultFallback="test2Fallback")
public String test2() {
String str = restTemplate.getForObject("http://provide1/hello", String.class);
return str;
}
public String test2Fallback() {
return "接口不通";
}
@GetMapping("/test3")
@HystrixCommand(defaultFallback="test3Fallback")
public String test3() {
String str = restTemplate.getForObject("http://provide2/hello", String.class);
return str;
}
public String test3Fallback() {
return "接口不通";
}
}
此处示例表示 当方法调用失败时会返回“接口不通”错误
项目代码见 eureka-client-ribbon-hystrix
Feign 引入Hystrix
因为Feign已经深度结合了Hystrix,包含了Hystrix的核心包,所以Feign 的项目不需要再引入spring-cloud-starter-hystrix
方法1:在@FeignClient 设置 fallback
@FeignClient(name="provide1",configuration=MyFeignClientsConfiguration.class,fallback=HelloServiceFallback.class)
public interface HelloService {
@RequestLine("GET /say/{name}")
String sayHello(@Param(value = "name") String name) ;
}
HelloServiceFallback.java
@Component
public class HelloServiceFallback implements HelloService {
@Override
public String sayHello(String name) {
return "接口不通"+name;
}
}
项目代码见 eureka-client-feign-hystrix
方法2:在@FeignClient 设置 fallbackFactory
@FeignClient(name="provide1",configuration=MyFeignClientsConfiguration.class,fallbackFactory=HelloServiceFallbackFactory.class)
public interface HelloService {
@RequestLine("GET /say/{name}")
String sayHello(@Param(value = "name") String name) ;
}
HelloServiceFallbackFactory.java
@Component
public class HelloServiceFallbackFactory implements FallbackFactory<HelloService> {
@Override
public HelloService create(Throwable cause) {
return new HelloService() {
@Override
public String sayHello(String name) {
return name +" "+cause.getMessage();
}
};
}
}
如果需要访问导致回退触发的原因,可以使用方法2