1. 什么是断路器(Hystrix)
在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。
2. Ribbon下如何使用Hystrix
在之前的consumer-ribbon中进行修改,映入Hystrix依赖
spring-cloud-starter-netflix-hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动类上添加注解
@EnableHystrix
,表示开启断路器功能
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class ConsumerRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
修改HelloService类的方法,在调用服务的方法上添加
@HystrixCommand(fallbackMethod = "fail")
,表示如果服务调用失败则访问fail方法,所有也许在该类中创建一个fail方法。
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fail")
public String sayHello(String name){
String forObject = restTemplate.getForObject("http://PROVIDER/hello?name={name}", String.class, name);
return forObject;
}
public String fail(String name){
return "hello "+name+", Access failure.";
}
}
测试:
1.启动eureka服务
2.启动两个provider服务,端口分别是8081,8082
3.启动consumer-ribbon
4.调用
http://localhost:8083/hello
5.关闭8081的服务,再次访问,8082可以正常访问,8081访问失败调用了fail方法
3. Feign中如何使用Hystrix
修改consumer-feign工程,同样加入依赖
spring-cloud-starter-netflix-hystrix
,然后在配置文件中开启feign的hystrix
spring:
application:
name: consumer-feign
server:
port: 8084
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka
feign:
hystrix:
enabled: true #开启hystrix
修改HelloService,在
@FeignClient
注解中添加
fallback
属性值,
@FeignClient(value = "provider",fallback = HelloServiceHystrix.class)
@FeignClient(value = "provider",fallback = HelloServiceHystrix.class)
public interface HelloService {
@GetMapping("/hello")
String sayHello(@RequestParam("name") String name);
}
所有还需要创建一个HelloServiceHystrix类,实现断路器功能,该类需要继承HelloService接口,实现其中方法,作为断路处理方法,并将该类注入到spring容器中
@Component
public class HelloServiceHystrix implements HelloService {
@Override
public String sayHello(String name) {
return "hello "+name+", Access failure.";
}
}
测试:
1.启动eureka服务
2.启动consumer-feign
3.访问
http://localhost:8084/hello?name=xinfeng
我们并没有开启provider项目,所有访问不到它提供的服务,这时就执行了断路执行的断路器的方法。