提高查询速度的远程接口优化;
[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生成。
标签:web,asp,request,接口,shippingCostService,tasks,var,public From: https://www.cnblogs.com/Tpf386/p/18222720