Spring Cloud Circuit Breaker 使用示例

Spring Cloud Circuit Breaker 使用示例

作者: Grey

原文地址:

博客园:Spring Cloud Circuit Breaker 使用示例

CSDN:Spring Cloud Circuit Breaker 使用示例

说明

Spring Cloud Circuit breaker提供了一个跨越不同断路器实现的抽象。它提供了一个一致的API,可以在你的应用程序中使用,允许你的开发者选择最适合你的应用程序需求的断路器实现。

它还支持的实现有如下几种

Resilience4j

Hystrix

Sentinel

Spring Retry

完整代码

spring-cloud-circuit-breaker-usage

环境

  • JDK 1.8+

  • Maven 3.5+

  • Spring Boot 版本:2.7.5

  • Spring Cloud 版本:2021.0.5

项目结构和说明

  • spring-cloud-circuit-breaker-usage:父项目名称
    • server : 服务端端模块
      • src/
      • pom.xml
    • client : 客户端模块
      • src/
      • pom.xml
    • pom.xml:父项目 pom 配置

代码说明

服务端需要引入如下依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

然后暴露一个简单服务

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class BookController {
    @RequestMapping(value = "/recommended")
    public Mono<String> readingList() {
        return Mono.just("book1,book2,book3");
    }
}

暴露端口

server.port=8090

客户端的配置也很简单,核心在ReactiveCircuitBreaker的初始化,客户端的依赖如下

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class BookService {

    private static final Logger LOG = LoggerFactory.getLogger(BookService.class);


    private final WebClient webClient;
    private final ReactiveCircuitBreaker readingListCircuitBreaker;

    public BookService(ReactiveCircuitBreakerFactory circuitBreakerFactory) {
        this.webClient = WebClient.builder().baseUrl("//localhost:8090").build();
        this.readingListCircuitBreaker = circuitBreakerFactory.create("recommended");
    }

    public Mono<String> readingList() {
        return readingListCircuitBreaker.run(webClient.get().uri("/recommended").retrieve().bodyToMono(String.class), throwable -> {
            LOG.warn("Error making request to book service", throwable);
            return Mono.just("local store book");
        });
    }
}

如果需要配置一些熔断条件,则做如下设置即可

CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
  .failureRateThreshold(50)
  .waitDurationInOpenState(Duration.ofMillis(1000))
  .slidingWindowSize(2)
  .build();
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
  .timeoutDuration(Duration.ofSeconds(4))
  .build();

this.readingListCircuitBreaker = circuitBreakerFactory.configureDefault(
                id -> new Resilience4JConfigBuilder(id)
                .timeLimiterConfig(timeLimiterConfig)
                .circuitBreakerConfig(circuitBreakerConfig)

客户端暴露一个接口用于测试

@RestController
public class ReadingController {

    private final BookService bookService;

    public ReadingController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/to-read")
    public Mono<String> toRead() {
        return bookService.readingList();
    }
}

客户端设置端口

server.port=8080

接下来,启动服务端,然后启动客户端,用 Postman 或者其他相关工具访问: //localhost:8080/to-read

image

然后把服务端停止,模拟服务中断,再次访问: //localhost:8080/to-read

image

显示了降级后的内容。

参考文档

Spring Cloud Circuit Breaker

spring-cloud-circuitbreaker-demo

Spring Cloud Circuit Breaker Guide

Quick Guide to Spring Cloud Circuit Breaker

spring-retry