性能优化和最佳实践能显著提升 cURL 的使用效率和可靠性。掌握这些技巧对于生产环境至关重要。
超时设置
bash# 连接超时(秒) curl --connect-timeout 10 https://api.example.com # 最大传输时间(秒) curl --max-time 30 https://api.example.com # 组合使用 curl --connect-timeout 5 --max-time 30 https://api.example.com # 毫秒级超时(7.68.0+) curl --connect-timeout 3.5 --max-time 10.5 https://api.example.com
重试机制
bash# 自动重试 curl --retry 3 https://api.example.com # 重试延迟(秒) curl --retry 3 --retry-delay 2 https://api.example.com # 指数退避重试 curl --retry 3 --retry-delay 1 --retry-max-time 10 https://api.example.com # 特定错误码重试 curl --retry 5 --retry-connrefused https://api.example.com
连接复用
bash# 保持连接(HTTP Keep-Alive) curl --keepalive-time 60 https://api.example.com # 限制连接数 curl --limit-rate 100K https://api.example.com # 并发请求(使用 xargs) cat urls.txt | xargs -P 5 -I {} curl -s {} -o /dev/null
压缩传输
bash# 请求压缩响应 curl --compressed https://api.example.com # 手动指定压缩 curl -H "Accept-Encoding: gzip, deflate" https://api.example.com
性能分析
bash# 详细性能指标 curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nSSL: %{time_appconnect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\nSize: %{size_download}B\nSpeed: %{speed_download}B/s\n" \ -o /dev/null -s https://api.example.com # 保存性能报告 curl -w "@perf-format.txt" -o /dev/null -s https://api.example.com > perf.log
批量处理优化
bash# 批量下载(并行) #!/bin/bash urls=( "https://api.example.com/users" "https://api.example.com/products" "https://api.example.com/orders" ) for url in "${urls[@]}"; do curl -s "$url" -o "$(basename $url).json" & done wait # 使用 GNU Parallel cat urls.txt | parallel -j 4 curl -s {} -o {/}.json # 连接池复用 curl -K - <<EOF url = "https://api.example.com/users" output = "users.json" url = "https://api.example.com/products" output = "products.json" EOF
内存和资源优化
bash# 限制下载速度 curl --limit-rate 1M https://example.com/large-file.zip -O # 分块下载 curl -r 0-1024000 https://example.com/large-file.zip -o part1.zip curl -r 1024001-2048000 https://example.com/large-file.zip -o part2.zip # 断点续传 curl -C - -O https://example.com/large-file.zip # 流式处理(不保存到内存) curl -s https://api.example.com/stream | jq '.[] | .name'
最佳实践清单
1. 安全性
bash# 始终验证 SSL 证书 curl https://api.example.com # 使用最新 TLS 版本 curl --tlsv1.2 --tls-max tls1.3 https://api.example.com # 不在命令行暴露密码 curl -u "username" https://api.example.com # 让 cURL 提示输入密码 # 使用环境变量 curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com
2. 可靠性
bash# 设置合理的超时 curl --connect-timeout 10 --max-time 60 https://api.example.com # 启用重试机制 curl --retry 3 --retry-delay 2 --retry-max-time 30 https://api.example.com # 错误处理 curl -f https://api.example.com || echo "Request failed" # 检查退出码 curl -s https://api.example.com if [ $? -ne 0 ]; then echo "Error occurred" fi
3. 可维护性
bash# 使用配置文件 # ~/.curlrc verbose connect-timeout = 10 max-time = 60 retry = 3 # 使用变量和函数 #!/bin/bash API_BASE="https://api.example.com/v1" TOKEN="your_token" api_call() { curl -s -H "Authorization: Bearer $TOKEN" "$API_BASE/$1" } api_call "users" api_call "products"
4. 日志和监控
bash# 记录请求日志 curl -v https://api.example.com 2>&1 | tee request.log # 结构化日志 curl -w "$(date '+%Y-%m-%d %H:%M:%S') | URL: %{url_effective} | Status: %{http_code} | Time: %{time_total}s\n" \ -o /dev/null -s https://api.example.com >> api.log # 监控脚本 #!/bin/bash while true; do STATUS=$(curl -w "%{http_code}" -o /dev/null -s https://api.example.com/health) echo "$(date): $STATUS" [ "$STATUS" != "200" ] && echo "Alert: API unhealthy!" | mail -s "API Alert" admin@example.com sleep 60 done
性能对比表
| 优化项 | 优化前 | 优化后 | 提升 |
|---|---|---|---|
| 连接复用 | 每次新建连接 | Keep-Alive | 30-50% |
| 压缩传输 | 原始大小 | Gzip 压缩 | 60-80% |
| 并发请求 | 串行执行 | 并行处理 | 3-5倍 |
| DNS 缓存 | 每次解析 | 缓存结果 | 10-20% |
| 断点续传 | 重新下载 | 续传 | 节省带宽 |
完整优化示例
bash#!/bin/bash # 生产级 API 调用脚本 # 配置 API_URL="https://api.example.com/v1/data" TOKEN="${API_TOKEN:-$(cat ~/.api_token)}" TIMEOUT=30 RETRY=3 # 调用函数 optimized_call() { curl -s -S \ --connect-timeout 10 \ --max-time "$TIMEOUT" \ --retry "$RETRY" \ --retry-delay 2 \ --compressed \ --tlsv1.2 \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "User-Agent: MyApp/1.0" \ -w "\n{\"status\":${http_code},\"time\":${time_total},\"size\":${size_download}}\n" \ "$@" } # 执行 response=$(optimized_call "$API_URL") # 处理响应 if [ $? -eq 0 ]; then echo "Success: $response" | jq '.' else echo "Error: Request failed" exit 1 fi