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等手段控制依赖服务的延迟与失败 ...
随机推荐
- ApacheCN JavaWeb 译文集 20211017 更新
使用 Spring5 构建 REST Web 服务 零.前言 一.一些基本知识 二.在 Spring5 中使用 Maven 构建 RESTfulWeb 服务 三.Spring 中的 Flux 和 Mo ...
- git 初始化本地项目并推送到远程
有一个新项目,开发了一些代码之后想推送到远程,具体的操作方式和命令如下: (使用 git bash) 1.切到项目目录中,例如 E:\git\smart-open 2.初始化git仓库并在本地提交 / ...
- SQL性能优化技巧
作者:IT王小二 博客:https://itwxe.com 这里就给小伙伴们带来工作中常用的一些 SQL 性能优化技巧总结,包括常见优化十经验.order by 与 group by 优化.分页查询优 ...
- Spring Cloud Alibaba Nacos路由策略之保护阈值!
在 Nacos 的路由策略中有 3 个比较重要的内容:权重.保护阈值和就近访问.因为这 3 个内容都是彼此独立的,所以今天我们就单独拎出"保护阈值"来详细聊聊. 保护阈值 保护阈值 ...
- appium填坑
首次使用appium web driver,不说搭建环境的麻烦,初次写完一个操作计算器的程序,但是运行一直报错:selenium.common.exceptions.WebDriverExceptio ...
- Spring系列11:@ComponentScan批量注册bean
回顾 在前面的章节,我们介绍了@Comfiguration和@Bean结合AnnotationConfigApplicationContext零xml配置文件使用Spring容器的方式,也介绍了通过& ...
- Spring IOC-基于XML配置的容器
Spring IOC-基于XML配置的容器 我们先分析一下AbstractXmlApplicationContext这个容器的加载过程. AbstractXmlApplicationContext的老 ...
- 编译安装&打包压缩&定时任务
内容概要 编译安装 打包压缩 定时任务 内容详细 一.编译安装 1.特点 使用源代码,编译打包软件. 1.可以自定制软件 2.按需构建软件啊 2.步骤 下载安装包 wget 下载网址 如果没有 ...
- Solution -「ZJOI 2016」「洛谷 P3352」线段树
\(\mathcal{Descrtiption}\) 给定 \(\{a_n\}\),现进行 \(m\) 次操作,每次操作随机一个区间 \([l,r]\),令其中元素全部变为区间最大值.对于每个 \ ...
- 【第二十四期】golang 一年经验开发 富途
他们家是按题目来的,从一个小题目慢慢延伸着问,由浅入深,问到你换题为止. 第一题 给了一个网址,解释一下浏览器填入这个网址后发生了什么? TCP为什么要三次握手四次挥手? 502是什么? 如果出现50 ...