06-CircuitBreaker断路器
1、介绍
Spring Cloud Circuit breaker provides an abstraction across different circuit breaker implementations. It provides a consistent API to use in your applications allowing you the developer to choose the circuit breaker implementation that best fits your needs for your app.
Spring Cloud断路器提供了一个跨不同断路器的抽象实现。它提供了在您的应用程序中使用的一致的API,允许您的开发人员选择最适合您的应用程序需要的断路器实现。
支持断路器实现有以下几种
- Netfix Hystrix (Spring Cloud官方已经不予支持)
- Resilience4J (支持)
- Sentinel
- Spring Retry
2、快速开始
pom.xml
maven依赖配置文件,如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mindasoft</groupId>
<artifactId>spring-cloud-circuitbreaker-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-circuitbreaker-consumer</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
比上个项目多了如下配置:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
使用resilience4j 实现断路器。
application.properties
server.port=9004
# 服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
# 服务名称
spring.application.name=circuitbreaker-customer
SpringCloudCircuitBreakerConsumerApplication
package com.mindasoft;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@EnableDiscoveryClient // Eureka Discovery Client 标识
@SpringBootApplication
public class SpringCloudCircuitBreakerConsumerApplication {
// 开启负载均衡的功能
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(3)).build())
.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
.build());
}
public static void main(String[] args) {
SpringApplication.run(SpringCloudCircuitBreakerConsumerApplication.class, args);
}
}
ConsumerController
package com.mindasoft.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Created by huangmin on 2017/11/10 14:50.
*/
@RestController
public class ConsumerController {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerController.class);
@Autowired
private RestTemplate restTemplate; // HTTP 访问操作类
@Autowired
private CircuitBreakerFactory circuitBreakerFactory;
@RequestMapping("/hello")
public String hello() {
String providerMsg = circuitBreakerFactory.create("hello")
.run(() -> restTemplate.getForObject("http://PROVIDER-SERVICE/hello", String.class),
throwable -> "CircuitBreaker fallback msg");
return "Hello,I'm Customer! msg from provider : <br/><br/> " + providerMsg;
}
}
启动eureka server和本项目,访问http://127.0.0.1:9004/hello
页面打印如下:
Hello,I'm Customer! msg from provider :
CircuitBreaker fallback msg
说明进入到了断路throwable 处理逻辑。
06-CircuitBreaker断路器的更多相关文章
- CircuitBreaker断路器Fallback如何获取异常
在Spring Cloud 2020新版里, 可以使用新版的 CircuitBreaker 断路器, 可以配置Fallback, 可以是内部的, 也可以是外部的Fallback. 内部 Fallbac ...
- Go语言设计模式汇总
目录 设计模式背景和起源 设计模式是什么 Go语言模式分类 个人观点 Go语言从面世就受到了业界的普遍关注,随着区块链的火热Go语言的地位也急速蹿升,为了让读者对设计模式在Go语言中有一个初步的了解和 ...
- 重新整理 .net core 实践篇————熔断与限流[三十五]
前言 简单整理一下熔断与限流,跟上一节息息相关. 正文 polly 的策略类型分为两类: 被动策略(异常处理.结果处理) 主动策略(超时处理.断路器.舱壁隔离.缓存) 熔断和限流通过下面主动策略来实现 ...
- springcloud3(六) 服务降级限流熔断组件Resilience4j
代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-gateway/src/test/java/com/ ...
- Spring Cloud Gateway的断路器(CircuitBreaker)功能
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 断路器(CircuitBreaker)设计模式
断路器是电器时代的一个重要组成部分,后面总是有保险丝熔断或跳闸的断路器是安全的重要保障. 微服务最近几年成为软件架构的热门话题,其益处多多.但需要知道的是,一旦开始将单块系统进行分解,就上了分布式系统 ...
- 冷饭新炒:理解断路器CircuitBreaker的原理与实现
前提 笔者之前在查找Sentinel相关资料的时候,偶然中找到了Martin Fowler大神的一篇文章<CircuitBreaker>.于是花了点时间仔细阅读,顺便温习一下断路器Circ ...
- Circuit Breaker Pattern(断路器模式)
Handle faults that may take a variable amount of time to rectify when connecting to a remote service ...
- Spring Cloud入门教程-Hystrix断路器实现容错和降级
简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使 ...
- Spring Boot中使用断路器
断路器本身是电路上的一种过载保护装置,当线路中有电器发生短路时,它能够及时的切断故障电路以防止严重后果发生.通过服务熔断(也可以称为断路).降级.限流(隔离).异步RPC等手段控制依赖服务的延迟与失败 ...
随机推荐
- Vue 之 浏览本地图片功能
template <input type="file" ref="input_file" @change="fileChange" ...
- maven 中的工程依赖和层级依赖?
一.什么是工程依赖? 思考问题?1.1一旦开始分模块开发的时候,之前的所有包都会被拆分成一个一个的项目 model mapper service ... 其实mapper需要model的支持,怎么解决 ...
- Centos设置网络(固定IP)
简介 设置为桥接模式,即将虚拟机的虚拟网络适配器与主机的物理网络适配器进行交接,虚拟机中的虚拟网络适配器可通过主机中的物理网络适配器直接访问到外部网络. 配置 虚拟机设置为桥接模式 进入网络配置文件, ...
- Redis-46面试题
1.什么是 Redis?简述它的优缺点? Redis 的全称是:Remote Dictionary.Server,本质上是一个 Key-Value 类型的内存数据库,很像 memcached,整个数据 ...
- 第一个OC类
1.如何声明一个类 格式 注意: 1.必须以@interface开头,@end结尾 2.成员变量的声明,必须写在@interface与@end之间的大括号中 3.方法的声明必须在{}下面,不能写在{} ...
- 第10讲:Flink Side OutPut 分流
Flink系列文章 第01讲:Flink 的应用场景和架构模型 第02讲:Flink 入门程序 WordCount 和 SQL 实现 第03讲:Flink 的编程模型与其他框架比较 第04讲:Flin ...
- C# 实例解释面向对象编程中的开闭原则
在面向对象编程中,SOLID 是五个设计原则的首字母缩写,旨在使软件设计更易于理解.灵活和可维护.这些原则是由美国软件工程师和讲师罗伯特·C·马丁(Robert Cecil Martin)提出的许多原 ...
- Solution -「Gym 102956B」Beautiful Sequence Unraveling
\(\mathcal{Description}\) Link. 求长度为 \(n\),值域为 \([1,m]\) 的整数序列 \(\lang a_n\rang\) 的个数,满足 \(\not\ ...
- Spring高级特性之三:@Enable*注解的工作原理
Spring Boot中阐述热插拔技术的时候,简单地提及@Enable*注解.随着多种框架的应用及深入了解,@Enable*这个注解在各种框架中应用相当普及. 那么@Enable*注解工作原理是怎么样 ...
- 菜鸟到大神之多图预警——从 RAID 到分布式系统中的副本分布
我们知道,在面对大规模数据的计算和存储时,有两种处理思路: 垂直扩展(scale up):通过升级单机的硬件,如 CPU.内存.磁盘等,提高计算机的处理能力. 水平扩展(scale out):通过添加 ...