同步异步

125 阅读1分钟
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(","); // 假设订单接口返回订单ID列表,以逗号分隔

        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();
    }
}