假设我正在调用一个API,它响应产品的以下JSON:
{
"id": 123,
"name": "The Best Product",
"brand": {
"id": 234,
"name": "ACME Products"
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用Jackson注释来映射产品ID和名称:
public class ProductTest {
private int productId;
private String productName, brandName;
@JsonProperty("id")
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
@JsonProperty("name")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
} …Run Code Online (Sandbox Code Playgroud) 我正在使用Guzzle 6发送这样的并发请求:
public function sendConcurrentRequests() {
$client = new Client(['timeout' => 5]);
$promises[] = $client->getAsync('http://example.com/1');
$promises[] = $client->getAsync('http://example.com/2');
$promises[] = $client->getAsync('http://example.com/3');
$results = Promise\unwrap($promises);
return $results;
}
Run Code Online (Sandbox Code Playgroud)
每个请求可能需要1到10秒,但我不希望任何请求等待超过5秒(这就是我设置超时的原因).我希望会发生的是:
这是实际发生的事情: - 请求1,2和3启动 - 请求2需要超过3秒,因此解包函数抛出一个ConnectException,我无法从请求1和3获得响应.
我如何才能完成这项工作,以便能够及时获得有效回复?