OkHttp源码学习之retryOnConnectionFailure属性

retryOnConnectionFailure的作用

在OKHTTP中,retryOnConnectionFailure 是一个配置选项,它用于控制当网络连接失败时是否应该重试请求。这个选项通常在 OkHttpClient 的配置中设置,用于决定在网络连接失败的情况下,是否应该自动重试请求。

retryOnConnectionFailure 控制的是 连接失败 时是否自动重试请求。具体来说,如果设置为 true,当请求连接失败时,OkHttp 会尝试重新建立连接并重试该请求;如果设置为 false,则在连接失败时不会重试请求,而是直接返回失败。

默认值:

默认情况下,retryOnConnectionFailure 的值为 true,这意味着如果请求的连接发生故障,OkHttp 会自动进行重试,直到请求成功或遇到最大重试次数(通常是无穷次,具体依赖于操作系统和网络环境)。

配置方式:

可以在创建 OkHttpClient 时,通过 OkHttpClient.Builder 配置 retryOnConnectionFailure。比如:

kotlin 复制代码
val client = OkHttpClient.Builder()
    .retryOnConnectionFailure(true) // 设置为 true 表示启用重试
    .build()

如果你希望禁用自动重试,可以将其设置为 false

kotlin 复制代码
val client = OkHttpClient.Builder()
    .retryOnConnectionFailure(false) // 设置为 false 表示禁用重试
    .build()

适用场景:

/**

  • Configure this client to retry or not when a connectivity problem is encountered. By default,this client silently recovers from the following problems:
  • Unreachable IP addresses. If the URL's host has multiple IP addresses, failure to reach any individual IP address doesn't fail the overall request. This canincrease availability of multi-homed services.
  • Stale pooled connections. The [ConnectionPool] reuses sockets to decrease request latency, but these connections will occasionally time out.
  • Unreachable proxy servers. A [ProxySelector] can be used to attempt multiple proxy servers in sequence, eventually falling back to a direct connection.
  • Set this to false to avoid retrying requests when doing so is destructive. In this case the calling application should do its own recovery of connectivity failures.

*/

通过上面的源码注释,可以看到retryOnConnectionFailure主要适用下面的三个场景,

  1. 自动重试连接
    例如,如果请求的服务器出现短暂的网络问题或连接问题(如服务器不可达、TCP 连接超时等),启用重试可以增加请求成功的机会,避免因临时网络问题导致请求失败。
  2. 防止短暂的网络波动导致请求失败
    在某些情况下,网络环境可能出现短暂的波动或丢包,如果不进行重试,请求可能会立即失败,影响用户体验。启用重试可以提高网络请求的成功率。
  3. 避免服务器压力过大
    如果某个请求失败并立即重试,可能会导致服务器在高负载下变得更加拥堵。对于某些高并发应用场景,避免重试可能是一个合理的选择。
相关推荐
码界奇点1 天前
基于Java GUI和Access数据库的图书馆管理系统设计与实现
java·开发语言·数据库·毕业设计·源代码管理
Moshow郑锴1 天前
JAVA JDK26新特性分析 - 一个注重性能优化、生产就绪和前瞻性安全的版本
java·开发语言·jvm
非凡ghost1 天前
proDAD ReSpeedr:专业视频变速编辑的利器
java·网络·windows·python·音视频·软件需求
aq55356001 天前
Spring Boot中的404错误:原因、影响及处理策略
java·spring boot·后端
zhougl9961 天前
maven 插件
java·maven
进击的cc1 天前
Activity 生命周期是如何被调度的?(从源码到实战全链路拆解)
android
weixin_704266051 天前
SpringMVC基础了解
java·spring·mvc
BUG?不,是彩蛋!1 天前
AI智慧社区--从0到1开发柱状图数据接口
java·spring boot·后端·intellij-idea·mybatis
sp42a1 天前
将 NativeScript 项目升级到 Android API 35 级别
android·nativescript
arvin_xiaoting1 天前
OpenClaw Agent与Sub-agent架构深度分析:关系、通信与权限隔离
java·linux·架构·多智能体·ai agent·openclaw·sub-agent