美文网首页
Spring Cloud 熔断器

Spring Cloud 熔断器

作者: Tinyspot | 来源:发表于2023-01-01 20:57 被阅读0次

1. Hystrix

  • 避免请求阻塞,雪崩效应
  • 避免连锁故障,可通过 fallback 返回固定值
  • 风控

2. Ribbon 中增加熔断器

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

启动类增加 @EnableHystrix

Service 类增加 @HystrixCommand

@Component
public class AdminService {

    @Resource
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "invokeError")
    public String invoke(String message) {
        // 去调用 Eureka 的服务提供者 concrete-config
        return restTemplate.getForObject("http://concrete-config/show?message=" + message, String.class);
    }

    public String invokeError(String message) {
        return String.format("your message is %s, but request bad", message);
    }
}

3. Feign 中使用熔断器

3.1 配置文件

Feign 中自带熔断器,默认是关闭的
Spring Cloud 2020之前的版本 feign.hystrix.enabled=true
Spring Cloud 2020之后的版本 feign.circuitbreaker.enabled=true

feign:
  circuitbreaker: # 配置断路器
    enabled: true

Spring Cloud2020之后,需要引入 spring-cloud-starter-netflix-hystrix 依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

3.2 Service 设置 fallback 类

@FeignClient(value = "concrete-config", fallback = AdminServiceHystrix.class)
public interface AdminService {

    @RequestMapping("/show")
    String invoke(@RequestParam(value = "message") String message);
}

// 回调类
@Component
public class AdminServiceHystrix implements AdminService {
    @Override
    public String invoke(String message) {
        return String.format("your message is %s, but request error", message);
    }
}

测试熔断器:
关闭服务提供者,再次请求,浏览器会显示:your message is hello, but request bad

4. 熔断器仪表盘

4.1 配置

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
hystrix:
  dashboard:
    proxy-stream-allow-list: "*"

启动类增加 @EnableHystrixDashboard

SpringBoot 2.x 版本需要增加一个 HystrixMetricsStreamServlet

@Configuration
public class HystrixDashboardConfiguration {

    // 没有 web.xml 文件,通过注解来配置
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

熔断器地址:http://localhost:8020/hystrix

image.png

相关文章

网友评论

      本文标题:Spring Cloud 熔断器

      本文链接:https://www.haomeiwen.com/subject/rrjrxdtx.html