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依赖配置文件,如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.4
         
    

    com.mindasoft
    spring-cloud-circuitbreaker-consumer
    0.0.1-SNAPSHOT
    spring-cloud-circuitbreaker-consumer
    Demo project for Spring Boot

    
        UTF-8
        UTF-8
        1.8
        2021.0.1
    

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-circuitbreaker-resilience4j
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

    
        
            nexus-aliyun
            Nexus aliyun
            https://maven.aliyun.com/repository/public
            default
            
                false
            
            
                true
            
        
    
    
        
            nexus-aliyun
            Nexus aliyun
            https://maven.aliyun.com/repository/public
            
                false
            
            
                true
            
        
    


比上个项目多了如下配置:

  
            org.springframework.cloud
            spring-cloud-starter-circuitbreaker-resilience4j
        

使用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 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 : 

" + providerMsg; } }

启动eureka server和本项目,访问http://127.0.0.1:9004/hello
页面打印如下:

Hello,I'm Customer! msg from provider :

CircuitBreaker fallback msg

说明进入到了断路throwable 处理逻辑。

你可能感兴趣的:(06-CircuitBreaker断路器)