Spring Boot中使用断路器模式实现弹性微服务

Circuitbraker-example
由于多个独立服务在微服务设计中相互交互,保持系统弹性变得非常重要。管理因服务中断或高延迟而可能出现的故障是一个典型问题。称为断路器模式的设计模式通过提供回退并防止级联故障来解决此问题。在本博客中,我们将了解 Spring Boot 应用程序的断路器模式。

了解断路器模式:
电气中断路器和断路器模式起着类似的作用。它密切关注故障,并在达到预定阈值时打开电路以停止对故障服务的更多调用。这使得系统能够优雅地发生故障,并在出现故障的服务恢复并运行时重新启动。

SpringBoot实现:

<!-- Add Resilience4j dependency in pom.xml -->
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
</dependency>

<!-- Add Resilience4j dependency in build.gradle -->
dependencies {
    implementation 'io.github.resilience4j:resilience4j-spring-boot2:1.7.1'
}

现在让我们构建一个使用 Resilience4j 断开电路的基本 Spring Boot 应用程序。

1.创建Spring Boot应用程序:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CircuitBreakerTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(CircuitBreakerTestApplication.class, args);
    }
}

2. 创建带有断路器的服务:

创建服务类并将其命名为 TestService,它将有一个我们想要用断路器保护的方法:

import org.springframework.stereotype.Service;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;

@Service
public class TestService {

    @CircuitBreaker(name = "testService", fallbackMethod = "fallbackMethod")
    public String invokeExternalService() {
        // Here you can simulate a call to an external service
        // In a real-world scenario, this could be an HTTP call, database query, etc.
        if (Math.random() > 0.5) {
            throw new RuntimeException("Service failure");
        }
        return "External service response";
    }

    public String fallbackMethod(Exception e) {
        return "Fallback response";
    }
}

在CircuitBreaker注释中,name是断路器的标识符,fallbackMethod是电路打开时要调用的方法。

3. 编写一个控制器类来调用TestService:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/invokeService")
    public String invokeService() {
        return testService.invokeExternalService();
    }
}

4. 启用 Resilience4j 配置

您可以将以下属性添加到application.properties或application.yml文件中以配置 Resilience4j:
resilience4j.circuitbreaker.configs.default.failureRateThreshold=50
resilience4j.circuitbreaker.configs.default.slidingWindowSize=5

5:监控断路器状态(非必须)

为了监控断路器的状态,还可以为Micrometer和Prometheus添加以下依赖:


<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

implementation 'io.micrometer:micrometer-registry-prometheus'

现在可以通过http://localhost:8080/actuator/Circuitbreakers访问 Resilience4j Circuit Breaker 仪表板。

6:测试断路器
运行 Spring Boot 应用程序时,利用/api/invokeService端点提交请求。更改callExternalService 方法中的Math.random()条件以模拟失败。

观察断路器仪表板的状态如何根据服务调用的成功或失败而变化。

结论
上面的示例展示了如何以基本方式在 Spring Boot 应用程序中设置 Resilience4j 的断路器。根据您独特的用例以及与外部服务的交互,可以根据需要进行调整。