当前位置:网站首页>What is the "asynchronous request reply" mode? How to realize programming?
What is the "asynchronous request reply" mode? How to realize programming?
2022-07-22 14:25:00 【Dotnet cross platform】
In some cases ,WEB API It may take a long time to process the request , It is not feasible for the client to wait for the work to be completed , For example, connection timeout, etc .
At this time , have access to “ asynchronous Request-Reply Pattern ”.
asynchronous Request-Reply Pattern
asynchronous Request-Reply Pattern means : When the back-end processing needs to be asynchronous, but the front-end still needs a clear response , Separate the back-end processing from the front-end .
The overall process is as follows :
Client applications for business API To call , Trigger long-running operations on the back end ;
API Return the response immediately . return HTTP 202 Accepted ( Accept ) Status code , Confirm that the request has been received for processing , The response contains a header , Contains the status that the client can poll API Address , To check the results of long-running operations ;;
The client polls this status API, If the operation is not completed , Then return to HTTP 202, Otherwise return to HTTP 200, And include the actual response data .
Now let's demonstrate how to do it in ASP.NET Core To realize .
Demo
We use waiting 20 Second simulates a long time API operation :
[HttpGet]
[Route("get")]
public async Task<IEnumerable<WeatherForecast>> Get()
{
await Task.Delay(20000);
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
First , We create a new API operation :
[HttpGet]
[Route("async/get")]
public async Task<IActionResult> AsyncGet()
{
string id = Guid.NewGuid().ToString();
string responseValue = [email protected]"/status/{id}";
_cache.SetString(id, responseValue);
Task.Factory.StartNew(() =>
{
var result = Get().Result;
_cache.SetString(id + "_result", JsonConvert.SerializeObject(result));
});
return Accepted(responseValue);
}
The specific function is to hand over a long time to Task perform , The execution results will be put into the distributed cache , Then return to HTTP 202 Accepted.
The client no longer accesses the original request address , Instead, use this new address :
then , We create a state API For polling :
[HttpGet]
[Route("/status/{id}")]
public IActionResult Status(string id)
{
var result = _cache.GetString(id + "_result");
if (!string.IsNullOrEmpty(result))
{
return Ok(result);
}
return Accepted(_cache.GetString(id));
}
Client according to ID Poll .
When the operation is not completed , Keep going back HTTP 202:
When the operation is complete , Return the results in the distributed cache :
Conclusion
If your API There are long-running operations , The polling information should be returned to the caller as soon as possible , So that they can check the progress .
Want to know more about , Please pay attention to my official account ”My IO“
边栏推荐
- DOM -- event broker
- 7. ZABBIX auto discovery automatic logon
- Grpc MagicOnion库 之 客户端和服务端 (案例版)
- Meituan two sides: redis five basic data structures?
- 7种 实现web实时消息推送的方案
- 字节跳动测试岗,前面都过了,最后一面HR天坑...跟我说这话
- Kuzaobao: summary of Web3 encryption industry news on July 21
- 英国天气过热导致谷歌云、Oracle云服务中断
- 51 MCU peripherals: LED dot matrix
- 多线程与高并发—— Synchronized 加锁解锁流程
猜你喜欢
Advanced C language: string function and Simulation Implementation
With an annual salary of 30W, the growth path of software testers, at which stage are you?
Meituan two sides: redis five basic data structures?
Ardunio开发——水泵操作过程
The development of raspberry pie - the Internet cable connects raspberry pie and laptop directly - records the bitter process
每日刷题记录 (三十)
Redis data structure analysis (I)
Advanced C language: data storage (floating point)
Développement d'ardunio - processus de fonctionnement des pompes
ByteDance test post, the front has passed, and the last HR sinkhole Tell me that
随机推荐
Add Chinese and other fonts to R plot [showtext]
微波雷达人体感应器,即时存在感知方案,智能家居人体感应交互
Async function and await expression in ES6
51 MCU peripherals: Keys
22张图带你深入剖析前缀、中缀、后缀表达式以及表达式求值
接口自动化测试---如何提高接口自动化脚本的稳定性?
Go语言 Go命令行工具
职场3道坎:年薪30万、50万、100万
[shutter component] expanded detailed explanation
ABAP grammar foundation 4
Ardunio開發——水泵操作過程
ABAP语法基础4
YOLOv7实验测试之二:遥感图像检测应用(yolov7-tiny-silu.yaml)
Design of consumption system of unmanned Supermarket Based on stm32
AttributeError: ‘str‘ object has no attribute ‘param_ group‘
字节跳动测试岗,前面都过了,最后一面HR天坑...跟我说这话
2022年中国第三方支付市场专题分析
Raspberry pie - Cloud Server Deployment - intranet penetration - use of cpolar tool
暑期沉淀web学习——SQL注入(布尔盲注&时间盲注)
通讯录(文件版本)