8 个版本 (4 个稳定版)

1.3.0 2024 年 7 月 5 日
1.2.0 2022 年 8 月 22 日
1.1.0 2021 年 7 月 17 日
1.0.0 2020 年 8 月 17 日
0.1.0 2018 年 9 月 3 日

#38 in 异步

Download history 53991/week @ 2024-05-03 60101/week @ 2024-05-10 61292/week @ 2024-05-17 64824/week @ 2024-05-24 77451/week @ 2024-05-31 79326/week @ 2024-06-07 65765/week @ 2024-06-14 69355/week @ 2024-06-21 75304/week @ 2024-06-28 75098/week @ 2024-07-05 79161/week @ 2024-07-12 75701/week @ 2024-07-19 79658/week @ 2024-07-26 71328/week @ 2024-08-02 92437/week @ 2024-08-09 90076/week @ 2024-08-16

350,108 次每月下载
8 软件包中(直接使用 5 个)

MIT 许可证

75KB
1.5K SLoC

Failsafe

Сrate Вocumentation CircleCI Appveyor

一种用于检测故障并封装防止故障持续发生的逻辑的实现,这发生在维护期间、临时外部系统故障或意外系统困难时。

特性

  • Fn() -> ResultFuture (通过默认的 futures-support 功能可选)一起工作。
  • 退避策略:constantexponentialequal_jitteredfull_jittered
  • 故障检测策略:consecutive_failuressuccess_rate_over_time_window
  • 最低 Rust 版本:1.59

使用方法

将此添加到您的 Cargo.toml 中

failsafe = "1.3.0"

示例

使用默认退避策略和故障累积策略。

use failsafe::{Config, CircuitBreaker, Error};

// A function that sometimes failed.
fn dangerous_call() -> Result<(), ()> {
  if thread_rng().gen_range(0, 2) == 0 {
    return Err(())
  }
  Ok(())
}

// Create a circuit breaker which configured by reasonable default backoff and
// failure accrual policy.
let circuit_breaker = Config::new().build();

// Call the function in a loop, after some iterations the circuit breaker will
// be in a open state and reject next calls.
for n in 0..100 {
  match circuit_breaker.call(|| dangerous_call()) {
    Err(Error::Inner(_)) => {
      eprintln!("{}: fail", n);
    },
    Err(Error::Rejected) => {
       eprintln!("{}: rejected", n);
       break;
    },
    _ => {}
  }
}

或配置自定义退避和策略

use std::time::Duration;
use failsafe::{backoff, failure_policy, CircuitBreaker};

// Create an exponential growth backoff which starts from 10s and ends with 60s.
let backoff = backoff::exponential(Duration::from_secs(10), Duration::from_secs(60));

// Create a policy which failed when three consecutive failures were made.
let policy = failure_policy::consecutive_failures(3, backoff);

// Creates a circuit breaker with given policy.
let circuit_breaker = Config::new()
  .failure_policy(policy)
  .build();

依赖项

~0.6–5.5MB
~19K SLoC