Spring Boot中断路器模式的简单实现

本文介绍了如何在Spring Boot应用中利用Spring Cloud Netflix Hystrix实现断路器模式。通过创建一个服务提供者和一个客户端,展示了当服务提供者不可用时,断路器如何触发回退方法,确保系统稳定。
摘要由CSDN通过智能技术生成

本文假定您已经了解Spring Boot的基础知识:)

断路器模式是一种防止由于远程调用另一个服务失败而导致软件系统故障的方法。 在本文中,我们将看到如何实现Spring Cloud Netflix HystrixSpring Boot中的库来演示这种模式。

首先,我们需要设置一个将由客户端调用的服务。 我们可以去start.spring.io使用Spring Web作为依赖项来引导Spring Boot项目。

现在,让我们下载项目并创建一个信息控制器类将具有我们的客户服务将调用的端点。

Alt Text

之后,让我们创建一个信息服务类,该类具有返回表示来自服务器的消息的字符串的方法。

Alt Text

At this point, we are basically done with the server implementation. If we start this service and hit http://localhost:8080/info in the browser, we see "Hi, this message is from a Spring Boot service." as the response.

好的,现在,我们需要创建一个客户端服务,以使用上述服务的端点响应。 与上述相同,让我们引导另一个Spring Boot服务,但是具有附加的依赖关系,Spring Cloud Netflix Hystrix。

让我们创建一个信息控制器同样在这里上课,如下所示:

Alt Text

另外,让我们创建一个信息服务类,如下所示。

Alt Text

如上所示,我们在“getServerInfo()方法。它将返回“嗨,此消息来自Spring Boot服务。”响应,如果该服务运行正常。但是,由于多种原因,如果该服务没有响应,我们定义了一个后备方法 ”getFallBackInfo()“。此方法在“getServerInfo()“借助“@HystrixCommand”注释。此注释是在服务器应用程序关闭时将触发的键。

我们需要做的另一件事是更改客户端应用程序的默认端口application.properties文件,如下所示。

Alt Text

我们这样做的原因是,我们最初构建的服务器应用程序已经在端口8080上运行。

要添加的另一项重要内容是“@EnableHystrix”在客户端应用程序的主类中,顾名思义,它将在我们的应用程序中启用hystrix后备。

Alt Text

To see the normal flow of our client-server system, let's start both of the applications, and hit http://localhost:8081/info endpoint in the browser. In this scenario, we will see "Hi, this message is from a Spring Boot service." as the response. Now, to see the Circuit Breaker in action, we need to stop the server application. Once we do this and call the above endpoint from the client, we will see "Hi, this is the fallback info from the server." as response, which is defined in our fallback method in the client application.

就这些! 这应该是来自Netflix的hystrix库的幼稚应用程序,因此我保持了所有项目结构的简单性。 希望本文对您有所帮助!

from: https://dev.to//mannik01/a-simple-implementation-of-circuit-breaker-pattern-in-spring-boot-140c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值