houdq / blog

java 学习笔记
0 stars 0 forks source link

熔断、降级、限流 #105

Open houdq opened 9 months ago

houdq commented 9 months ago

熔断(Circuit Breaker):熔断是一种防止故障扩散的策略。当一个服务出现故障或超时,熔断器会打开并快速失败,拒绝后续的请求,避免请求堆积和资源耗尽。熔断器会暂时屏蔽该服务,并在一段时间后尝试恢复。熔断器的状态变化可用于监控系统健康和提供告警信息。

限流(Rate Limiting):限流是一种控制系统请求流量的策略。通过设置一个请求速率阈值,限流可以限制每个客户端或用户在特定时间内的请求次数。这样可以防止过多的请求涌入系统,保护系统免受过载和压力冲击。限流可以平滑流量,避免系统突发流量的影响。

降级(Fallback):降级是一种在面对特殊业务或异常情况时保持系统可用的策略。当服务不可用时,降级服务会代替提供一些基本功能或返回预设的默认值,以确保系统依然能够提供有限的功能或服务;又或者某些特定活动场景(例如:双十一)下优先保障计算资源投入到 业务倾向的服务,降级边缘服务。

image

houdq commented 9 months ago

springcloud-resilience4j

核心代码


// 使用Resilience4j的熔断器
@CircuitBreaker(name = "myService", fallbackMethod = "fallbackMethod")
public String myService() {
    // 调用可能会失败的方法
}

// 降级方法
public String fallbackMethod(Throwable throwable) {
    return "Fallback response";
}

image

houdq commented 9 months ago

Hystix

依赖


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

代码示例


@SpringBootApplication
@RestController
@EnableHystrix
public class MyHystrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyHystrixApplication.class, args);
    }

    @Autowired
    HystrixClient hystrixClient;

    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        Thread.sleep(3000);

        String value = hystrixClient.get();
        return value;
    }

    String fallback() {
        System.out.println("fallback");
        return "fallback";
    }

}
houdq commented 9 months ago

Sentinel

官网下载 https://github.com/alibaba/Sentinel/releases

java -jar -Dserver.port=10086 app/sentinel-dashboard-2.0.0-alpha-preview.jar

访问 localhost:10086

image

添加 jar 依赖

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2021.1</version>
        </dependency>

配置文件

spring:
  application:
    name: my-sentinel-local
  cloud:
    sentinel:
      eager: true
      transport:
        dashboard: localhost:10086
#            port: 8719