Hystrix断路器

Hystrix断路器是什么呢?

Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。
在微服务I发生异常,请求阻塞,用户不会得到响应,则tomcat的这个线程不会释放,于是越来越多的用户请求到来,越来越多的线程会阻塞,服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,形成雪崩效应。

那么这个问题如何解决呢?来我们一起编写Hystrix

新建提供者cloud-provider-hystrix-payment8001模块
在这里插入图片描述
导入依赖,这里我们先把hystrix依赖注释掉,先模拟一下服务器发生超时的状况

 <dependencies>
        <!-- hystrix -->
            <!--<dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            </dependency>-->
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
            <groupId>org.example</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

编写配置文件
在这里插入图片描述
编写启动类在这里插入图片描述
来写service,因为我们只是模拟一下服务器连接超时,所有就不去连接数据库了在这里插入图片描述
编写controller
在这里插入图片描述
访问正常的方法
在这里插入图片描述
访问延迟的方法,现在都没有问题
在这里插入图片描述
接下来我们使用软件来模拟服务器在高并发的情况下会如何,设置一下线程数量
在这里插入图片描述
在这里插入图片描述
我们再来访问一下试试,可以看出在高并发的情况下一直在刷新,这样会让客户等的时间太长,客户体验极差,你们公司很有可能就凉凉了,就算没有访问到也应该给客户一个提示语句,不能一直瞎等下去,这里我们就需要用到Hystrix断路器了
在这里插入图片描述
把这个配置文件的注释解开

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

修改我们的启动类,这个注解里边包含了上边上个注解,这是开启断路器用的
在这里插入图片描述
service层修改一下,注:用户等待3000是毫秒
在这里插入图片描述
测试一下,这里是用户最多等待三秒,但是我们模拟的是让它休眠五秒在执行,所以也就超时了,调用了备选方案
在这里插入图片描述
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aspoil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值