Spring Cloud Circuit Breaker 使用示例

spring,cloud,circuit,breaker,使用,示例 · 浏览次数 : 488

小编点评

**Spring Cloud Circuit Breaker 示例** **作者:Grey** **简介:** Spring Cloud Circuit Breaker 是一个跨越不同断路器的抽象,可用于实现一致的 API 在您的应用程序中使用。它支持的实现有 Resilience4jHystrixSentinelSpring Retry 和 Spring Cloud Circuit Breaker,提供各种配置选项,以适应您的应用程序需求。 **代码示例:** **父项目 pom.xml:** ```xml org.springframework.boot spring-boot-starter-webflux 2.7.5 ``` **子项目 pom.xml:** ```xml org.springframework.cloud spring-cloud-starter-circuitbreaker-reactor-resilience4j 3.5.2 org.springframework.boot spring-boot-starter-webflux 2.7.5 ``` **配置:** 1. 编写一个 `BookController` 和 `BookService` 类。 2. 使用 `ReactiveCircuitBreakerFactory` 创建一个 `recommended` 命名的分布器。 3. 在 `BookService` 中创建 `readingList` 方法,使用 `ReactiveCircuitBreaker` 来配置熔断条件和时间限制器。 4. 在 `ReadingController` 中创建 `toRead` 方法,使用 `bookService` 获取内容并返回。 5. 在启动服务端之前,设置端口。 6. 使用 Postman 或其他工具访问服务端,并模拟服务中断。 **运行:** 1. 启动服务端。 2. 启动客户端。 3. 在终端中访问 `http://localhost:8080/to-read` 和 `http://localhost:8080/to-read`,检查内容。 **结果:** 访问 `http://localhost:8080/to-read` 将显示原始内容,因为服务端尚未启动。访问 `http://localhost:8080/to-read` 后,内容将变为 "book1,book2,book3"。

正文

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("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");
        });
    }
}

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

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 或者其他相关工具访问: 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

与Spring Cloud Circuit Breaker 使用示例相似的内容:

Spring Cloud Circuit Breaker 使用示例

Spring Cloud Circuit Breaker 使用示例 作者: Grey 原文地址: 博客园:Spring Cloud Circuit Breaker 使用示例 CSDN:Spring Cloud Circuit Breaker 使用示例 说明 Spring Cloud Circuit

Spring Cloud微服务核心架构分析

Spring Cloud是一个相对比较成熟的微服务框架。虽然,Spring Cloud于2016年才推出1.0的release版本, 时间最短, 但是相比Dubbo等RPC框架, Spring Cloud提供的全套的分布式系统解决方案。 Spring Cloud是一系列框架的有序集合。它利用Spri

Spring Cloud 部署时如何使用 Kubernetes 作为注册中心和配置中心

一、Spring Cloud 支持的常见注册中心和配置中心。 Spring Cloud 自带的注册中心Eureka以及config配置中心 Nacos,支持注册中心和配置中心等,可以参考:https://www.cnblogs.com/laoqing/p/17797759.html Zookeepe

聊聊Spring Cloud Alibaba Sentinel的限流

Spring Cloud Alibaba Sentinel限流功能概览,目前先整理一版,东西有点多,想慢慢打开;后续继续更新......

聊聊Spring Cloud Gateway

Spring Cloud Gateway是基于Spring Boot 2.0、Spring WebFlux和Project Reactor等技术开发的网关,它不仅提供了统一的路由请求的方式,还基于过滤链的方式提供了网关最基本的功能;解决了Spring Cloud Zuul的性能问题。

[转帖]Spring Cloud Alibaba Nacos 注册中心使用教程

一. 什么是Nacos Nacos是一个更易于构建云原生应用的动态服务发现(Nacos Discovery )、服务配置(Nacos Config)和服务管理平台,集注册中心+配置中心+服务管理于一身,基本特性如下: 服务发现和服务健康监测; 动态配置服务; 动态 DNS 服务; 服务及其元数据管理

[转帖]Spring Cloud 整合 SkyWalking

https://www.jianshu.com/p/e81e35dc6406 Java Agent 服务器探针 探针,用来收集和发送数据到归集器。参考官网给出的帮助 Setup java agent,我们需要使用官方提供的探针为我们达到监控的目的,按照实际情况我们需要实现三种部署方式 IDEA 部署

Spring Cloud Gateway 使用示例

Spring Cloud Gateway 使用示例 作者: Grey 原文地址: 博客园:Spring Cloud Gateway 使用示例 CSDN:Spring Cloud Gateway 使用示例 说明 Spring Cloud Gateway 用于构建 API 网关,基于 Spring We

Spring Cloud Gateway编码实现任意地址跳转

面对同样的客户端请求,SpringCloud Gateway可以转发给不同的服务去处理,掌握这个技能,让请求从微服务入口处被掌控,被调度

【Spring Cloud】Eureka缓存机制

Eureka分为Client端和Server端,Client端向Server端注册自己的服务信息,并且拉取所有服务的注册信息,Server端作为注册中心,负责接收Client端的注册信息,维护所有服务的注册信息,Server端也可以开启集群模式,相互之间同步服务的注册信息。 与缓存相关的三个变量 1