簡體   English   中英

如何將 Akka.Net Streams 與 AspNet 核心或 giraffe 集成

[英]How to Integrate Akka.Net Streams with AspNet core, or giraffe

通常,當我使用 Giraffe 或 ASP.Net Core 時,我可以創建一個角色系統,將其添加為服務,然后將其視為請求處理程序選擇任何角色並詢問/告知消息。

無論是使用 Cluster.Sharding 還是普通user/actor我知道它將是整個系統中處理多條消息的參與者的單個實例。

如何與 Streams 進行相同的通信? 它們似乎不是路由器中的引用,也不是作為演員路徑的演員系統:演員引用、路徑和地址。

這應該以不同的方式做嗎?

從 IO 部分復制,我可以具體化一個圖來處理每個請求,但總的來說,我與“Singleton”(如域驅動設計聚合根)進行通信來處理域邏輯(這就是分片模塊的原因),我不確定如何做可以在請求處理程序的新物化圖中使用的單例接收器,因為所有請求必須只有一個接收器。

有很多方法可以將 akka 流與外部系統集成 使接收者變得容易的一個是Source.queue (有點類似於 System.Threading.Channels 並早於它們)。 您可以在初始化點實現流,然后在 Giraffe DI 中注冊隊列端點 - 這樣您就不必為每個請求支付相同的流初始化成本:

open Akka.Streams
open Akkling
open Akkling.Streams
open FSharp.Control.Tasks.Builders

let run () = task {
    use sys = System.create "sys" <| Configuration.defaultConfig()
    use mat = sys.Materializer()
    
    // construct a stream with async queue on both ends with buffer for 10 elements
    let sender, receiver =
        Source.queue OverflowStrategy.Backpressure 10
        |> Source.map (fun x -> x * x)
        |> Source.toMat (Sink.queue) Keep.both
        |> Graph.run mat
        
    // send data to a queue - quite often result could be just ignored
    match! sender.OfferAsync 2 with
    | :? QueueOfferResult.Enqueued -> () // successfull
    | :? QueueOfferResult.Dropped -> () // doesn't happen in OverflowStrategy.Backpressure 
    | :? QueueOfferResult.QueueClosed -> () // queue has been already closed
    | :? QueueOfferResult.Failure as f -> eprintfn "Unexpected failure: %O" f.Cause
    
    // try to receive data from the queue
    match! receiver.AsyncPull() with
    | Some data -> printfn "Received: %i" data
    | None -> printfn "Stream has been prematurelly closed"
        
    // asynchronously close the queue
    sender.Complete()
    do! sender.WatchCompletionAsync()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM