06-CircuitBreaker斷路器
阿新 • • 發佈:2022-03-10
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 處理邏輯。