Spring Cloud 断路器(Hystrix)的使用

Netflix开源了Hystrix组件,实现了断路器模式,SpringCloud对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的。

hystrix主要是用来防止服务雪崩效应的。

服务雪崩效应:是一种因服务提供者的不可用导致服务调用者的不可用,并将不可用逐渐放大的过程。

如图一个API可能同时调用多个微服务:

较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。

三、在ribbon使用断路器

改造serice-ribbon 工程的代码,首先在pox.xml文件中加入spring-cloud-starter-hystrix的起步依赖:

<dependency> 

    <groupId>org.springframework.cloud</groupId> 

    <artifactId>spring-cloud-starter-hystrix</artifactId> 

</dependency>

Service方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串。

在程序的启动类ServiceRibbonApplication 加@EnableHystrix注解开启Hystrix:

@SpringBootApplication 
@EnableDiscoveryClient 
@EnableHystrix 
public class ServiceRibbonApplication { 
    public static void main(String[] args) {             
       SpringApplication.run(ServiceRibbonApplication.class, args); 
    } 
    @Bean 
    @LoadBalanced 
    RestTemplate restTemplate() { 
        return new RestTemplate(); 
    } 
}

改造HelloService类,在hiService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,

熔断方法直接返回了一个字串,字符串为”hi,”+name+”,sorry,error!”,代码如下:

@Service 
public class HelloService { 

  @Autowired RestTemplate restTemplate; 

  @HystrixCommand(fallbackMethod = "hiError") 
  public String hiService(String name) { 
     return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class); 
  } 

  public String hiError(String name) { 
     return "hi,"+name+",sorry,error!"; 
  } 
}

四、Feign中使用断路器

Feign是自带断路器的,在D版本的Spring Cloud中,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:

feign.hystrix.enabled=true

基于service-feign工程进行改造,只需要在FeignClient的SchedualServiceHi接口的注解中加上fallback的指定类就行了:

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class) 
public interface SchedualServiceHi { 

  @RequestMapping(value = "/hi",method = RequestMethod.GET) 
  String sayHiFromClientOne(@RequestParam(value = "name") String name); 
}

SchedualServiceHiHystric需要实现SchedualServiceHi 接口,并注入到Ioc容器中,代码如下:

@Component 
public class SchedualServiceHiHystric implements SchedualServiceHi { 
 
  @Override
  public String sayHiFromClientOne(String name) { 
     return "sorry "+name; 
  } 

}

猜你喜欢

转载自blog.csdn.net/qq_756589808/article/details/83011428