import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import org.springframework.http.ResponseEntity
@Service
public class OrderService {
private final RestTemplate restTemplate
public OrderService(RestTemplate restTemplate) {
this.restTemplate = restTemplate
}
public void processOrders() {
// 同步请求登录接口
String loginUrl = "http://your-api/login"
ResponseEntity<String> loginResponse = restTemplate.getForEntity(loginUrl, String.class)
// 同步请求订单接口
String orderUrl = "http://your-api/orders"
ResponseEntity<String> ordersResponse = restTemplate.getForEntity(orderUrl, String.class)
// 异步获取订单详情
String orderDetailUrl = "http://your-api/orderDetails"
String[] orderIds = ordersResponse.getBody().split(",")
CompletableFuture<Void>[] futures = Arrays.stream(orderIds)
.map(orderId -> CompletableFuture.supplyAsync(() -> restTemplate.getForEntity(orderDetailUrl + "/" + orderId, String.class))
.thenApply(responseEntity -> {
// 处理订单详情数据
System.out.println(responseEntity.getBody())
return null
}))
.toArray(CompletableFuture[]::new)
CompletableFuture.allOf(futures).join()
}
}