面试题答案
一键面试#!/bin/bash
# API 列表
apis=(
"http://api1.example.com"
"http://api2.example.com"
"http://api3.example.com"
)
# 存储结果的数组
results=()
# 处理单个 API 请求的函数
process_api() {
local api=$1
local result=$(curl -s --connect-timeout 5 "$api")
if [ $? -ne 0 ]; then
echo "API $api 请求失败"
return 1
fi
results+=("$result")
return 0
}
# 并发处理 API 请求
for api in "${apis[@]}"; do
process_api "$api" &
done
# 等待所有进程完成
wait
# 整合并输出数据
for result in "${results[@]}"; do
echo "$result"
# 这里可以添加进一步整合处理的代码,例如拼接、解析JSON等操作
done
上述脚本使用curl
命令来发起 API 请求,并通过&
操作符在后台并发执行process_api
函数处理每个 API。如果某个 API 请求失败,会输出错误信息。最后将所有成功请求的结果整合输出,你可以根据实际需求在echo "$result"
之后添加进一步的数据整合处理代码。