Flutter package: retry

传送门

This package provides an easy way to retry asynchronous functions. This is often useful to avoid crashing on intermittent errors such as broken connections or temporarily overloaded servers.

这个包提供了一种重试异步函数的简单方法。这通常有助于避免因连接中断或服务器暂时过载等间歇性错误而崩溃。

其实就是当有异常抛出时重试

Google官方的库,但是主页又加了一句

Disclaimer: This is not an officially supported Google product.

免责声明:这不是官方支持的 Google 产品

......

直接使用

simple example:

final response = await retry(
// Make a GET request
() => http.get('https://google.com').timeout(Duration(seconds: 5)),
// Retry on SocketException or TimeoutException
retryIf: (e) => e is SocketException || e is TimeoutException,
);

访问https://google.com,如果报错且此错误为SocketException或者TimeoutException,则重试

一些主要参数

参数 描述
位置参数 需要调用的异步函数
retryIf 如果满足回调条件则重试,不传则只要是Exception就重试
maxAttempts 最大尝试次数
delayFactor 每次重试的延迟时间
randomizationFactor 每次重试的延迟随机浮动百分比

Using RetryOptions

    RetryOptions options = RetryOptions(
delayFactor: const Duration(milliseconds: 400),
randomizationFactor: 0.25,
maxAttempts: 4,
maxDelay: Duration(seconds: 20)); options.retry(
() async {
// Make a HTTP request and return the status code.
final HttpClientRequest request = await client
.getUrl(Uri.parse('https://www.google.cn'))
.timeout(const Duration(seconds: 5));
final HttpClientResponse response =
await request.close().timeout(const Duration(seconds: 5));
await response.drain();
return response.statusCode;
},
retryIf: (Exception e) => e is SocketException || e is TimeoutException,
);

也可以使用RetryOptions来配置参数

加上randomizationFactor每次重试的时间就会上下浮动,比如设置为0.25,maxAttempts设置为8

那么在第一次到第七次重试就会按照以下时间休眠

  • 400 ms +/- 25%
  • 800 ms +/- 25%
  • 1600 ms +/- 25%
  • 3200 ms +/- 25%
  • 6400 ms +/- 25%
  • 12800 ms +/- 25%
  • 25600 ms +/- 25%

完整示例:

Future<void> retryFunction() async {
// Create an HttpClient.
final HttpClient client = HttpClient(); try {
// Get statusCode by retrying a function
final int statusCode = await retry(
() async {
// Make a HTTP request and return the status code.
final HttpClientRequest request = await client
.getUrl(Uri.parse('https://www.google.cn'))
.timeout(const Duration(seconds: 5));
final HttpClientResponse response =
await request.close().timeout(const Duration(seconds: 5));
await response.drain();
return response.statusCode;
},
// Retry on SocketException or TimeoutException
retryIf: (Exception e) =>
e is SocketException || e is TimeoutException,
maxAttempts: 4,
delayFactor: const Duration(seconds: 1),
randomizationFactor: 0.5,
onRetry: (Exception e) {
log('onRetry');
},
maxDelay: const Duration(seconds: 20)); // Print result from status code
if (statusCode == 200) {
if (kDebugMode) {
print('google.com is running');
}
} else {
if (kDebugMode) {
print('google.com is not availble...');
}
}
} finally {
// Always close an HttpClient from dart:io, to close TCP connections in the
// connection pool. Many servers has keep-alive to reduce round-trip time
// for additional requests and avoid that clients run out of port and
// end up in WAIT_TIME unpleasantries...
client.close();
}
}

Flutter Package: retry的更多相关文章

  1. flutter package & pub publish

    flutter package & pub publish dart-library-package https://pub.dev/packages/dart_library_package ...

  2. Flutter 增加三方库卡在flutter package get 的解决办法

    修改 pubspec.yaml 文件增加第三方库之后,AndroidStudio 像往常一样提示 需要 package get. 然后一直卡在 Running "flutter packag ...

  3. Flutter 实现原理及在马蜂窝的跨平台开发实践

    一直以来,跨平台开发都是困扰移动客户端开发的难题. 在马蜂窝旅游 App 很多业务场景里,我们尝试过一些主流的跨平台开发解决方案, 比如 WebView 和 React Native,来提升开发效率和 ...

  4. flutter插件汇总2

    作者:知乎用户链接:https://www.zhihu.com/question/307594373/answer/568969429来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...

  5. Flutter 开发小技巧

    1.命令行运行flutter run之后iOS报错:Could not install build/ios/iphones/Runner.app on XXXXX. try lunching Xcod ...

  6. Flutter Plugin开发流程

    这篇文章主要介绍了Flutter Plugin开发流程,包括如何利用Android Studio开发以及发布等. 本文主要给大家介绍如何开发Flutter Plugin中Android的部分.有关Fl ...

  7. Flutter 不一样的跨平台解决方案

    本文主要介绍Flutter相关的东西,包括Fuchsia.Dart.Flutter特性.安装以及整体架构等内容. 1. 简介 Flutter作为谷歌最近推出的跨平台开发框架,一经推出便吸引了不少注意. ...

  8. 【Flutter】Flutter 一些常用库

    Flutter社区和资源传送门 新: 慕课网<Flutter入门与案例实战>   |   中文网<Flutter实战>电子书 字体图标生成 http://fluttericon ...

  9. Flutter的需要与原生交互的一些常用库

    [说明]由于这些库一直在更新,请自己选择合适的稳定版本下载. 另外如果发现有问题或者你有更好的库,欢迎留言告诉我. 谷歌官方的针对Dart语言的一些实用性的功能以及扩展的库 -- Quiver Qui ...

  10. 深入理解 Flutter 的编译原理与优化

    阿里妹导读:对于开发者而言,Flutter工程和我们的Android/iOS工程有何差别?Flutter的渲染和事件传递机制如何工作?构建缓慢或出错又如何去定位,修改和生效呢?凡此种种,都需要对Flu ...

随机推荐

  1. SpringBoot注解大全(详细)

    1. @ActiveProfiles 用来声明活动的profile–@ActiveProfiles("prod"(这个prod定义在配置类中)) @RunWith(SpringRu ...

  2. vector<char>转string的方法

    要将 std::vector<char> 转换为 std::string,可以通过 std::string 的构造函数直接从 vector 中构建字符串. 假设 std::vector&l ...

  3. pytorch: grad can be implicitly created only for scalar outputs

    运行这段代码 import torch import numpy as np import matplotlib.pyplot as plt x = torch.ones(2,2,requires_g ...

  4. day12-包机制

    包机制 为了更好地组织类,Java提供了包机制,用于区别类名的命名空间. 包语句的语法格式为: 包的本质就是文件夹  package pkg1[.pkg2[.pkg3...]]; 一般公司域名倒置作为 ...

  5. Redis实现幂等、防抖、限流等功能

    本文章主要讲述如何使用Redis实现幂等.防抖.限流等功能. 幂等组件 import lombok.RequiredArgsConstructor; import org.springframewor ...

  6. 如何在cnblogs的发文中使用自定义地址作为发文链接

    要知道在cnblogs中发表内容后其默认的链接地址都是一串数字的形式,比如本篇的默认地址:https://www.cnblogs.com/xyz/p/18461898 但是为了让发表的内容更有个性化, ...

  7. 使用ssh 通过ProxyCommand:利用跳板机让不在同一局域网的机器ssh直连

    打开~/.ssh/config文件,如果没有则新建一个 输入以下内容并保存: Host dxx.sxx-bastion # jumpserver name hostname 54.65.xx.2xx ...

  8. 1.Kubernetes简介

    Kubernetes简介 来源 bilibili尚硅谷K8S视频:https://www.bilibili.com/video/BV1GT4y1A756 中文官网:https://kubernetes ...

  9. WebService WCF 请求通道在等待 00:00:58.9616639 以后答复时超时。增加传递给请求调用的超时值,或者增加绑定上的 SendTimeout 值。分配给此操作的时间可能是更长超时的一部分。

    查看使用什么方式调用的接口 如果是使用的 HttpWebRequest 请检查Timeout属性,默认值是 100,000 毫秒(100 秒)如果超过便会返回超时错误.

  10. Redis性能优化的18招

    前言 Redis在我们的日常开发工作中,使用频率非常高,已经变成了必不可少的技术之一. Redis的使用场景也很多. 比如:保存用户登录态,做限流,做分布式锁,做缓存提升数据访问速度等等. 那么问题来 ...