## 版本与环境校验


swift --version

确保使用支持并发模型的 Swift 5.7+ 工具链(macOS/iOS 原生;Linux 需兼容 Foundation)。


## 指数退避与可取消重试


import Foundation

struct Backoff: Sendable {
    let baseMS: UInt64 = 200
    func delay(for attempt: Int) -> UInt64 { // 毫秒→纳秒
        let ms = min(baseMS << attempt, 5_000) // 封顶 5s
        return ms * 1_000_000
    }
}

enum NetError: Error { case http(Int), transport(Error), cancelled }

func get(_ url: URL, maxAttempts: Int = 5) async throws -> Data {
    let backoff = Backoff()
    var attempt = 0
    while true {
        try Task.checkCancellation()
        do {
            var req = URLRequest(url: url)
            req.timeoutInterval = 10
            let (data, resp) = try await URLSession.shared.data(for: req)
            if let http = resp as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
                throw NetError.http(http.statusCode)
            }
            return data
        } catch is CancellationError {
            throw NetError.cancelled
        } catch {
            attempt += 1
            if attempt >= maxAttempts { throw error }
            try await Task.sleep(nanoseconds: backoff.delay(for: attempt)) // 指数退避
        }
    }
}

@main
struct App {
    static func main() async {
        let url = URL(string: "https://www.apple.com")!
        let t = Task {
            do {
                let d = try await get(url)
                print("length:", d.count)
            } catch {
                print("error:", error)
            }
        }
        // 演示取消:在 300ms 后取消任务
        try? await Task.sleep(nanoseconds: 300_000_000)
        t.cancel()
        _ = await t.result
    }
}

验证点:

  • 使用 `Task.checkCancellation()` 与 `CancellationError` 区分主动取消与网络/HTTP 错误。
  • 指数退避封顶,避免雪崩请求;`timeoutInterval` 控制单次请求上限。

## 并发聚合与错误传播(可选)


import Foundation

struct Endpoint: Sendable { let url: URL }

func fetchAll(_ endpoints: [Endpoint]) async throws -> [Data] {
    var results: [Data] = []
    try await withThrowingTaskGroup(of: Data.self) { group in
        for e in endpoints { group.addTask { try await get(e.url) } }
        for try await d in group { results.append(d) }
    }
    return results
}

验证点:

  • 任一子任务抛错会取消剩余子任务并向上传播错误,避免部分成功导致的资源泄漏。

## 注意事项


  • 对不可重试的错误(如 4xx)直接失败;对 5xx/网络超时进行退避重试。
  • 在移动端谨慎设置并发数与超时,避免后台刷新被系统限速。
  • 结合缓存策略与 ETag/If-None-Match 降低重复传输成本。

## 构建与运行(可验证)


swift build -c release
swift run -c release

在 `-c release` 下验证延迟与取消行为,记录 `p95/p99` 作为回归基线。


## 结语


通过指数退避、明确的错误分类与取消策略,可以在 Swift 的并发网络模型中获得稳定与可验证的行为,适合在生产环境中做聚合与后台同步。



点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部