• 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.bootgroupId>
                <artifactId>spring-boot-starter-webfluxartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4

    然后暴露一个简单服务

    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");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    暴露端口

    server.port=8090
    
    • 1

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

            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4jartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webfluxartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    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("http://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");
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

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

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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

    @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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    客户端设置端口

    server.port=8080
    
    • 1

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

    image

    然后把服务端停止,模拟服务中断,再次访问: http://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

  • 相关阅读:
    目标检测——Faster RCNN
    GitLab 管理 NuGet 包
    第6节-PhotoShop基础课程-认识选区
    护眼灯真的可以保护眼睛吗?2022买什么护眼灯不伤孩子眼睛
    C语言——扫雷小游戏
    webpack基础教程
    IDEA--tomcat日志乱码
    Cobalt Strike常用方法操作
    语雀P0级故障复盘,有9个字亮了
    计算机毕业设计springboot基于开源工作流的自来水业扩报装系统2j2yi源码+系统+程序+lw文档+部署
  • 原文地址:https://blog.csdn.net/hotonyhui/article/details/127920509