azure多功能成像好用嗎
Authored with Steef-Jan Wiggers at Microsoft Azure
由Microsoft Azure的Steef-Jan Wiggers撰寫
With Durable Functions, you can program a workflow and instantiate tasks in sequential or parallel order, or you can build a watch or support a human interaction flow (approval workflow). You can chain functions to control your flow. You can use fan-in and fan-out scenarios, correlating events, flexible automation, and long-running processes, and human interaction patterns that are hard to put in place with only functions or with logic apps.
使用“耐用功能”,您可以對工作流程進行編程并按順序或并行順序實例化任務,或者可以構建手表或支持人機交互流程( 批準工作流程 )。 您可以鏈接函數來控制流程。 您可以使用扇入和扇出場景,關聯事件,靈活的自動化和長期運行的流程,以及僅通過功能或邏輯應用程序難以實現的人機交互模式。
鏈接功能 (Chaining functions)
The most natural and straightforward use of Durable Functions is chaining functions together. You have one orchestrator function that calls many functions in the order you desire. You can do this with functions alone and using Service Bus Queues, yet you will face some challenges:
持久功能最自然,最直接的用法是將功能鏈接在一起。 您擁有一個編排器函數,該函數以所需的順序調用許多函數。 您可以單獨使用功能并使用服務總線隊列來完成此操作,但是您將面臨一些挑戰:
- no visualization to show the relationship between functions and queues 沒有可視化顯示功能和隊列之間的關系
- middle queues are an implementation detail, with a conceptual overhead 中間隊列是一個實現細節,具有概念上的開銷
- error handling adds a lot more complexity 錯誤處理增加了更多的復雜性
Using Durable Functions, you will not run into those challenges. With an orchestrator you:
使用持久功能,您將不會遇到這些挑戰。 與協調器一起您可以:
- can have a central place to set the order of function calls (relations) 可以在中心位置設置函數調用(關系)的順序
- need no management of queues — under the hood, Durable Functions use and manage storage queues 無需管理隊列-持久功能在后臺使用和管理存儲隊列
- have central error handling — when an error occurs in one of the activity functions, the error propagates back to the orchestrator 具有集中的錯誤處理功能—當活動功能之一發生錯誤時,該錯誤會傳播回協調器
//calls functions in sequence
public static async Task<object> Run (DurableOrchestrationContext ctx)
{ try{var x = await ctx.CallFunctionAsync (“F1”);var y = await ctx.callFunctionAsync (“F2”, x);var z = await ctx.callFunctionAsync (“F3”, y);return = await ctx.CallFunctionAsync (“F4”, z);}catch (Exception ){//global error handling /compensation goes here}
}
扇出/扇入 (Fan-out/Fan-in)
Fan-out/fan-in can be used when you need to execute one or more functions in parallel and, based on the results, you run some other tasks. With functions, you cannot put in place such an approach. Moreover, you will also face the challenges mentioned in the previous section. But, with Durable Functions, you can achieve fan-out/fan-in:
當您需要并行執行一個或多個功能,并根據結果運行一些其他任務時,可以使用扇出/扇入。 使用函數,您將無法采用這種方法。 此外,您還將面臨上一節中提到的挑戰。 但是,通過耐用功能,您可以實現扇出/扇入:
public static async Task Run (Durableorchestrationcontext ctx)
{
var parallelTasks = new List<Task<int>>();
//get a list of N work items to process in parallel
object []workBatch = await ctx.CallFunctionAsync<object[]> (“F1”);
for (int i = 0; i < workBatch.Length; i++)
{
Task<int> task = ctx.CallFunctionAsync <int> (“F2”, workBatch [i]);
parallelTasks.Add (task);
}
await Task.WhenAll(parallelTasks);
//aggregate all N outputs and send result to F3
int sum = parallelTasks.Sum(t=> t.Result);
await ctx.CallFunctionAsync (“F3”, sum);
}
HTTP異步響應 (HTTP Async Response)
With functions, it is possible that when you call another API you do not know the amount of time it would take before a response is returned. For example, latency and volume can cause the time it would make the API to process the request and return a response to be unknown.
使用函數,當您調用另一個API時,您可能不知道返回響應之前所花費的時間。 例如,延遲和數量會導致使API處理請求并返回響應的時間變得未知。
A function can time-out when using a Consumption plan. The state needs to be maintained, which is undesirable for functions, as they need to be stateless. Durable Functions provide built-in APIs that simplify the code you write for interacting with long-running function executions. Furthermore, the state is managed by the Durable Functions run-time.
使用消耗計劃時,功能可能會超時。 需要保持狀態,這對于功能是不希望的,因為它們需要是無狀態的。 耐用函數提供了內置的API,這些API簡化了您編寫的代碼以與長時間運行的函數執行進行交互。 此外,狀態由“持久功能”運行時管理。
//HTTP-triggered function to start a new orchestrator function instance.
public static async Task<HttpResponseMessage> Run (
HttpReq uestMessage req, DurableOrchestrationClient starter,
string functionName,
Ilogger log)
{
//Function name comes from the request URL.
//Function input comes from the request content .
dynamic eventData await req.Content .ReadAsAsync<object>();
string instanceid = await starter.StartNewAsync (functionName , eventData);
log .Loginformation ($”Started orchestration with ID = ‘{instanceid} ‘.”);
return starter.CreateCheckStatusResponse (req, instanceid);
}
演員們 (Actors)
Another use is the watcher — a recurring process in a workflow such as a clean-up process. You can put this in place with a function. But, again, you will have some challenges:
觀察者的另一個用途是觀察者-工作流中的重復過程,例如清理過程。 您可以使用函數將其放置到位。 但是,再次,您將面臨一些挑戰:
- functions are stateless and short-lived 功能是無狀態的,且存在時間短
- read/write access to an external state needs to be synchronized 對外部狀態的讀/寫訪問需要同步
With Durable Functions, you can have flexible recurrence intervals, task lifetime management, and the ability to create many watch processes from a single orchestration.
使用耐用功能,您可以具有靈活的重復間隔,任務生命周期管理以及從單個業務流程創建許多監視流程的能力。
public static async Task Run(DurableOrchestrationContext ctx)
{
int counterState = ctx.Getinput<int>();
string operation = await ctx.WaitForExternalEvent<string>(“operation”);
if (operation == “incr”)
{
counterState++;
}
else if (operation == “decr”)
{
counterstate --;
}
ctx.ContinueAsNew(counterState);
}
人際交往 (Human interaction)
Within organizations, you will face processes that require some human interaction such as approvals. Interactions like approvals require the availability of the approver. Thus, the process needs to be active for some time, and needs a reliable mechanism when the process times out. For instance, when an approval doesn’t occur within 72 hours, an escalation process must start. With Durable Functions, you can support such a scenario.
在組織內部,您將面臨需要人工交互(例如批準)的流程。 諸如批準之類的交互需要批準者的可用性。 因此,該過程需要在一段時間內處于活動狀態,并且在過程超時時需要可靠的機制。 例如,如果72小時之內未獲得批準,則必須啟動升級程序。 使用持久功能,您可以支持這種情況。
public static async Task Run(DurableOrchestrationContext ctx)
{
await ctx.CallFunctionAsync<object []>(“RequestApproval”);
using (var timeoutCts = new CancellationTokenSource())
{
DateTime dueTime = ctx.CurrentUtcDateTime.AddHours(72);
Task durableTimeout = ctx.CreateTimer(dueTime, 0, cts.Token);
Task<bool > approvalEvent = ctx.WaitForExternalEvent< bool>(“ApprovalEvent”);
if (approvalEvent == await Task .WhenAny(approvalEvent, durableTimeout ))
{
timeoutCts.Cancel();
await ctx .CallFunctionAsync(“HandleApproval”, approvalEvent.Result);
}
else
{
await ctx.CallFunctionAsy nc(“Escalate” );
}
}
}
示例實現:使用持久函數進行鏈接 (Sample implementation: Chaining using Durable Functions)
The Orchestrator Client is a function that can be triggered when a message is sent. This Client, a function, will call the Orchestrator and pass the order message.
Orchestrator客戶端是可以在發送消息時觸發的功能。 該客戶端是一個函數,它將調用Orchestrator并傳遞訂單消息。
public static async Task<HttpResponseMessage> Run (
HttpReq uestMessage req, DurableOrchestrationClient starter, string functionName,
Ilogger log)
{
//Function name comes from the request URL.
//Function input comes from the request content .
dynamic eventData await req.Content .ReadAsAsync<object>();
string instanceid = await starter.StartNewAsync ( functionName , eventData);
log .Loginformation ($”Started orchestration with ID = ‘{instanceid} ‘.”);
return starter.CreateCheckStatusResponse (req, instanceid);
}
The Orchestrator will receive the order and call the activity functions.
協調器將接收訂單并調用活動功能。
public static async Task Run(DurableOrchestrationContext context, object order, ILogger log)
{
log.LogInformation($”Data = ‘{order}’.”);
var orderDetail = (OrderDetail) order;
try
{
bool x = await context.CallActivityAsync<bool>(“WriteToDatabase”, orderDetail);
log.LogInformation($”Data storage = ‘{x}’.”);
if (x == true)
{
await context.CallActivityAsync<OrderDetail>(“WriteToArchive”, orderDetail);
await context.CallActivityAsync<OrderDetail>(“SendNotification”, orderDetail);
}
}
catch (Exception)
{
//ErrorHandling
}
}
Each of the activity functions will perform a task — in this case, store the order in a document collection in a CosmosDB instance, archive the stored message, and send a message to the queue to send out a notification via a logic app.
每個活動功能都將執行一項任務-在這種情況下,將訂單存儲在CosmosDB實例中的文檔集中,將已存儲的消息存檔,然后將消息發送到隊列以通過邏輯應用程序發出通知。
最佳實踐 (Best practices)
With Durable Functions there are a few best practices to follow:
使用耐用功能,可以遵循一些最佳做法:
- use the Azure App Insights app to monitor running instances and health, including Azure Functions 使用Azure App Insights應用程序監視正在運行的實例和運行狀況,包括Azure功能
- the Durable Functions app also exposes the HTTP API for management. With the API methods, you can influence the course of action for your Durable Functions. 耐用功能應用程序還公開了HTTP API進行管理。 使用API??方法,您可以影響耐用功能的操作過程。
- use version control with your durable function 與持久功能一起使用版本控制
you can use side-by-side deployment, updating the name of your task hub on deployment. See Durable Functions Blue Green Deployment Strategies for more information.
您可以使用并行部署,在部署時更新任務中心的名稱。 有關更多信息,請參見持久功能藍綠色部署策略 。
結語 (Wrap-up)
In this blog post, we hope you have a better understanding of the use of Durable Functions, and what value they offer. Durable Functions give you the ultimate control over a workflow, not achievable with alternative technologies such as logic apps or functions alone. Together with some of the best practices we consolidated, you should now be able to build sustainable solutions with Durable Functions.
在本博客中,我們希望您對耐用功能的使用以及它們提供的價值有更好的了解。 耐用的功能為您提供了對工作流程的最終控制,這是僅使用邏輯應用程序或功能等替代技術無法實現的。 加上我們整合的一些最佳實踐,您現在應該能夠使用耐用功能構建可持續的解決方案。
This article was originally published at Serverless360.
本文最初在Serverless360上發布。
翻譯自: https://www.freecodecamp.org/news/an-introduction-to-azure-durable-functions-patterns-and-best-practices-b1939ae6c717/
azure多功能成像好用嗎