QsMessaging
1.0.0
QsMessaging是一個 .NET 8 函式庫,設計用於使用RabbitMQ在應用程式的服務或元件之間傳送和接收訊息。它支援水平可擴展性,允許同一服務的多個實例有效地處理訊息。
可在 NuGet 上實現無縫整合:
適用於分散式系統的簡單、可擴展的訊息傳遞解決方案。
使用以下命令安裝軟體包:
dotnet add package QsMessaging
註冊庫很簡單。將以下兩行程式碼加入您的Program.cs
:
// Add QsMessaging (use the default configuration)...
builder . Services . AddQsMessaging ( options => { } ) ;
.. .
await host . UseQsMessaging ( ) ;
RabbitMQ
localhost
guest
guest
5672
定義訊息契約:
public class RegularMessageContract
{
public required string MyTextMessage { get ; set ; }
}
將IQsMessaging
注入到您的類別中:
public YourClass ( IQsMessaging qsMessaging ) { }
然後,用它來發送訊息:
await qsMessaging . SendMessageAsync ( new RegularMessageContract { MyTextMessage = "My message." } ) ;
若要處理該訊息,請建立一個處理程序:
public class RegularMessageContractHandler : IQsMessageHandler < RegularMessageContract >
{
public Task < bool > Consumer ( RegularMessageContract contractModel )
{
// Process the message here
return Task . FromResult ( true ) ;
}
}
您也可以使用請求/回應模式發送請求並等待回應。當您需要在服務之間進行通訊並期望得到回應時,這非常有用。
定義請求和回應合約:
public class MyRequestContract
{
public required string RequestMessage { get ; set ; }
}
public class MyResponseContract
{
public required string ResponseMessage { get ; set ; }
}
若要傳送請求並等待回應,請使用RequestResponse<TRequest, TResponse>
:
public class MyService
{
private readonly IQsMessaging _qsMessaging ;
public MyService ( IQsMessaging qsMessaging )
{
_qsMessaging = qsMessaging ;
}
public async Task < MyResponseContract > SendRequestAsync ( MyRequestContract request )
{
var response = await _qsMessaging . SendRequestResponseAsync < MyRequestContract , MyResponseContract > ( request ) ;
return response ;
}
}
若要處理要求,請實作IQsRequestResponseHandler<TRequest, TResponse>
介面:
public class MyRequestHandler : IQsRequestResponseHandler < MyRequestContract , MyResponseContract >
{
public Task < MyResponseContract > Handle ( MyRequestContract request )
{
// Process the request and create a response
return Task . FromResult ( new MyResponseContract { ResponseMessage = "Response to: " + request . RequestMessage } ) ;
}
}
就這樣,夥計們!
有關詳細文檔,請訪問 QsMessaging Wiki。