asp.net web api 接口内调用多个远程接口优化

提高查询速度的远程接口优化;

[ApiController]
[Route("[controller]")]
public class ShippingCostController : ControllerBase
{
    private readonly ShippingCostService _shippingCostService;

    public ShippingCostController(ShippingCostService shippingCostService)
    {
        _shippingCostService = shippingCostService;
    }

    [HttpPost("compare")]
    public async Task<ActionResult<List<ShippingCost>>> CompareShippingCosts([FromBody] ShippingRequest request)
    {
        // Create named tasks for each API call
        var upsTask = _shippingCostService.GetUPSShippingCost(request);
        var fedexTask = _shippingCostService.GetFedExShippingCost(request);
        var ryderTask = _shippingCostService.GetRyderShippingCost(request);
        var tntTask = _shippingCostService.GetTNTShippingCost(request);
        var expeditorsTask = _shippingCostService.GetExpeditorsShippingCost(request);
        var panalpinaTask = _shippingCostService.GetPanalpinaShippingCost(request);
        var unisTask = _shippingCostService.GetUnisShippingCost(request);

        // Add tasks to a list
        var tasks = new List<Task<ShippingCost>>
        {
            upsTask,
            fedexTask,
            ryderTask,
            tntTask,
            expeditorsTask,
            panalpinaTask,
            unisTask
        };

        // Execute all API calls concurrently
        var results = await Task.WhenAll(tasks);

        // Return the aggregated results
        return Ok(results.ToList());
    }
}

如果接口内,需要调用多个远程接口,可以让它们并发执行,提高查询效率;

 该代码由ai生成。

posted on 2024-05-30 16:53  荆棘人  阅读(11)  评论(0编辑  收藏  举报

导航