springcloud hystrix容断器

hystrix容断器简介

在分布式系统中,服务与服务之间的依赖错综复杂, 一种不可避免的情况就是某些服务出现故障,导致依赖于它们的其他服务出现远程调度的线程阻塞, Hystrix 是Netflix 公司开源的 一个项目,它提供了熔断器功能,能够阻止分布式系统中出现联动故障 ,Hystrix 是通过隔离服务的访问点阻止联动故障的,并提供了故障的解决方案,从而提 了整个分布式系统的弹性。

在RestTemplate上使用熔断器

在eureka-ribbon-client工程的基础上进行修改

引入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

启动类添加注解

@EnableHystrix

添加发生熔断时调用的方法

@Service
public class RibbonService {

    @Autowired
    RestTemplate restTemplate;
    
    @HystrixCommand(fallbackMethod = "hiError")
    public String hi(String name) {
        return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
    }
    
    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }
}

测试

在浏览器上输入地址  http://localhost:8765/hi,如果停止eureka-client服务,则显示

在feign上使用熔断器

由于feign起步依赖已经引入了熔断器,所以在feign中使用hystrix熔断器不需要引用任何依赖

修改配置文件

修改配置文件 application.yml

feign:
  hystrix:
    enabled: true

修改服务调用接口

修改EurekaClientFeign类,添加fallback = HiHystrix.class,如图:

添加熔断器返回器

添加HiHystrix类,并继承sayHiFromClientEureka接口

@Component
public class HiHystrix implements EurekaClientFeign {
    @Override
    public String sayHiFromClientEureka(String name) {
           return "hi,"+name+",sorry,error!";
    }
}

测试

在浏览器上输入地址  http://localhost:8766/hi,如果停止eureka-client服务,则显示

猜你喜欢

转载自www.cnblogs.com/tanouou/p/12324318.html