.NET 幫助

NServiceBus C#(如何為開發人員工作)

發佈 2024年8月13日
分享:

介紹

NServiceBus 是一款強大且可調整的服務總線,專為 .NET Framework 設計,用於簡化分散式系統的開發。它提供的強大訊息模式保證了在多個微服務和應用程式之間可靠的訊息處理和傳遞。NServiceBus 可以抽象出底層的訊息架構,使開發人員能夠專注於業務邏輯,而不是構建分散式系統的複雜性。

相較之下,IronPDF 是一款流行的 .NET 程式庫,用於生成、查看和修改 PDF 文件。它因易於使用並且在從各種來源(如 ASPX 文件和 HTML)創建 PDF 文件方面效能卓越而聞名。

開發人員可以通過結合 NServiceBus 和 IronPDF 來構建可靠、可擴展並且可維護的軟體系統,這些系統可以在其業務運營中生成和管理 PDF 文件。

在本文中,我們將探討如何設置一個簡單的 C# NServiceBus 專案並將其與 IronPDF 整合,從而構建一個簡化的工作流程來在分散式應用程式架構中管理和生成 PDF 文件。在閱讀這篇介紹教程之後,您應該會清楚如何將這兩種有效的技術結合起來,簡化您在分散式環境中與 PDF 相關的任務。

什麼是 NServiceBus c#?

NServiceBus 是一個強大且適應性高的框架,使得建立分佈式系統和面向服務的 .NET 架構變得容易。通過使用 NServiceBus,您可以輕鬆管理各種消息類型,並確保可靠的通信。這在網絡應用程序及類似架構中尤其重要,因為無縫的消息路由和處理是必不可少的。NServiceBus 的消息處理器有效地處理接收消息,確保每個邏輯組件順暢交互。NServiceBus 具有以下重要功能:

NServiceBus C#(開發人員如何使用):圖1 - NServiceBus C#

NServicebus的功能

基於訊息的通訊

NServiceBus 鼓勵系統中不同服務或元件之間的基於訊息的通訊。通過解耦元件,此方法可創建更易於擴展和管理的設計。

可靠的消息傳遞

透過自動管理重試、死信佇列和其他容錯技術,保證了可靠的消息傳遞。在分佈式系統中,網絡中斷和其他失敗問題經常發生,這種可靠性是至關重要的。

發佈/訂閱模式

NServiceBus 支援發佈/訂閱模式,使服務能夠發佈事件並讓其他服務訂閱這些事件。這使事件驅動的架構成為可能,其中對系統中某一組件中的事件所做的修改可以導致其他組件中的響應。

Saga 管理

由於 NServiceBus 的內建支持,長期運行的業務流程可通過 Saga 進行管理。Saga 使服務平台能夠管理狀態並協調多個服務之間的複雜操作。

擴展性和定制化

它提供了卓越的擴展性,使開發人員能夠個性化消息的處理、處理和傳輸過程。由於其適應性強,可用於各種場景。

整合各種訊息平台

包括 MSMQ、RabbitMQ、Azure Service Bus、Amazon SQS 等在內的許多訊息系統都可以與 NServiceBus 整合。這使得開發人員能夠選擇最適合他們需求的通信基礎設施解決方案。

在C#中建立和配置NServiceBus

你必須首先設置你的開發環境,創建一個基本項目,並建立基本的消息服務和場景,然後才能在C#項目中開始使用NServiceBus。這裡有一個逐步指南供你參考。

建立新的 Visual Studio 專案

在 Visual Studio 中,創建控制台專案的過程很簡單。使用以下簡單的步驟在 Visual Studio 環境中啟動控制台應用程式:

在使用之前,請確保您已在電腦上安裝 Visual Studio。

開始一個新專案

點擊「文件」,然後選擇「新建」,最後選擇「專案」。

NServiceBus C#(如何為開發人員運作):圖 2 - 點擊「新增」

您可以選擇「Console App」或「Console App (.NET Core)"從以下的專案範本參考清單中選擇範本。

在“名稱”欄位中為您的專案提供一個名稱。

NServiceBus C# (開發人員使用方式): 圖 3 - 提供專案名稱和位置

選擇專案的存儲位置。

點擊 "Create" 將啟動 Console 應用程式專案。

NServiceBus C#(開發人員如何運作):圖 4 - 點擊「建立」

安裝 NServiceBus 套件

導航到工具 > NuGet 套件管理員 > 套件管理控制台 以打開 NuGet 套件管理控制台。

運行以下命令來安裝 NServiceBus NuGet 套件。

Install-Package NServiceBus
Install-Package NServiceBus
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

選擇傳輸

NServiceBus 需要傳輸來接收和發送消息。我們將使用 Learning Transport,因為它易於使用且非常適合測試和開發。

通過執行以下命令安裝 Learning Transport 的軟件包。

Install-Package NServiceBus.RabbitMQ
Install-Package NServiceBus.RabbitMQ
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

配置 NServiceBus

設置端點

在您的 Program.cs 文件中設置 NServiceBus 端點配置:

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();
        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message)
            .ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();
        // Send a message
        var message = new MyMessage
        {
            Content = "Hello, NServiceBus with RabbitMQ!"
        };
        await endpointInstance.Send("ReceiverEndpoint", message)
            .ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

NServiceBus C#(對開發人員的工作原理):圖5 - 示例控制台輸出

建立訊息

要表示訊息,添加一個新類別。

public class MyMessage : IMessage
{
    public string Content { get; set; }
}
public class MyMessage : IMessage
{
    public string Content { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

建立訊息處理程序

要處理訊息,請新增一個類別。

using NServiceBus;
using System.Threading.Tasks;
public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
using NServiceBus;
using System.Threading.Tasks;
public class MyMessageHandler : IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message: {message.Content}");
        return Task.CompletedTask;
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

發送訊息

從端點發送訊息。使用處理器幫助來適應發送訊息的主要方式。

using NServiceBus;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
    Console.Title = "Receiver";
    var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");
    endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
    // Use RabbitMQ Transport
    var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
    transport.UseConventionalRoutingTopology(QueueType.Quorum);
    transport.ConnectionString("host=localhost");
    // Set up error queue
    endpointConfiguration.SendFailedMessagesTo("error");
    // Set up audit queue
    endpointConfiguration.AuditProcessedMessagesTo("audit");
    endpointConfiguration.EnableInstallers();
    // Start the endpoint
    var endpointInstance = await Endpoint.Start(endpointConfiguration)
                .ConfigureAwait(false);
    Console.WriteLine("Press Enter to exit...");
    Console.ReadLine();
    // Stop the endpoint
    await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
    Console.Title = "Receiver";
    var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");
    endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
    // Use RabbitMQ Transport
    var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
    transport.UseConventionalRoutingTopology(QueueType.Quorum);
    transport.ConnectionString("host=localhost");
    // Set up error queue
    endpointConfiguration.SendFailedMessagesTo("error");
    // Set up audit queue
    endpointConfiguration.AuditProcessedMessagesTo("audit");
    endpointConfiguration.EnableInstallers();
    // Start the endpoint
    var endpointInstance = await Endpoint.Start(endpointConfiguration)
                .ConfigureAwait(false);
    Console.WriteLine("Press Enter to exit...");
    Console.ReadLine();
    // Stop the endpoint
    await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

NServiceBus C#(適用於開發者的運作方式):圖6 - 範例控制台輸出

啟動應用程式並建置專案。控制台應顯示訊息 "Received message: Hello, NServiceBus"!請提供您想要翻譯的內容。

開始指南

在 C# 專案中,將 NServiceBus 與 RabbitMQ 和 IronPDF 整合需要配置 NServiceBus 與 RabbitMQ 之間的消息以及使用 IronPDF 創建 PDF。以下是一個詳細的操作指南,讓您順利開始:

什麼是 IronPDF

IronPDF 是一個專為創建、閱讀、編輯和轉換 PDF 文件而設計的 .NET 庫。使用它,程式設計師可以在 C# 或 VB.NET 應用程式中使用強大且直觀的工具來處理 PDF 文件。IronPDF 的特點和功能如下所述:

NServiceBus C#(開發人員如何使用):圖7 - IronPDF:C# PDP庫首頁

IronPDF的功能

從HTML生成PDF

將JavaScript、HTML和CSS轉換為PDF。支持媒體查詢和響應式設計,這兩個當代網頁標準。可用於使用HTML和CSS生成動態樣式的PDF文檔、發票和報告。

PDF編輯

在已有的PDF中添加文本、圖片和其他素材。從PDF文件中提取文本和圖片。將多個PDF合併成一個文件。將PDF文件拆分為多個文檔。包含註釋、頁腳、頁眉和水印。

PDF轉換

將Word、Excel、圖像和其他文件格式轉換為PDF。PDF轉圖像轉換 (PNG,JPEG 等。).

效能與可靠性

高效能和可靠性是生產環境中的設計目標。能高效地處理龐大文件。

安裝 IronPDF

通過打開 NuGet Package Manager Console 安裝 IronPDF。

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

配置發送者與消息

Messages 是一個共享的項目 (類別庫) 發送者和接收者都將使用這個專案。在 Messages 專案中定義消息類別。創建一個名為 Messages 的新類別庫專案,並將其添加到解決方案中。

定義消息

在 Messages 專案中,創建一個名為 GeneratePdfMessage.cs 的新類別:

using NServiceBus;
public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
using NServiceBus;
public class GeneratePdfMessage : IMessage
{
    public string Content { get; set; }
    public string OutputPath { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在發送者和接收者項目中,都包含對 Messages 項目的引用。

在發送者項目中設置 NServiceBus 端點以使用 RabbitMQ 傳遞訊息。

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
    endpointConfiguration.EnableInstallers();
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();
        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message)
            .ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
class Program
{
    static async Task Main()
    {
        Console.Title = "Sender";
        var endpointConfiguration = new EndpointConfiguration("SenderEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
    endpointConfiguration.EnableInstallers();
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to send a message...");
        Console.ReadLine();
        // Send a message
        var message = new GeneratePdfMessage
        {
            Content = "<h1>Hello, NServiceBus with RabbitMQ and IronPDF!</h1>",
            OutputPath = "output.pdf"
        };
        await endpointInstance.Send("ReceiverEndpoint", message)
            .ConfigureAwait(false);
        Console.WriteLine("Message sent. Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

端點配置: 透過呼叫 new EndpointConfiguration,端點會被初始化為 "SenderEndpoint"。("SenderEndpoint")エンドポイントペアt配は傳輸設定。透過連接至本地的 RabbitMQ 實例,這個方法 UseTransport() 設置 NServiceBus 使用 RabbitMQ 做為傳輸機制。

審核和錯誤佇列 使用 SendFailedMessagesTo 配置將失敗訊息和審核處理過的訊息發送到何處。(「錯誤」) 和AuditProcessedMessagesTo(審計), 分別。

消息已發送: endpointInstance.A GeneratePdfMessage 經由 Send 發送到 "ReceiverEndpoint"("ReceiverEndpoint",訊息) 函數。

配置接收器以生成 PDF

在接收器项目中設定 NServiceBus 端點,以透過 RabbitMQ 接受訊息並使用 IronPDF 生成 PDF。

using NServiceBus;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
        Console.Title = "Receiver";
        var endpointConfiguration = new EndpointConfiguration("ReceiverEndpoint");
        // Use RabbitMQ Transport
        var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
        transport.ConnectionString("host=localhost");
        // Set up error queue
        endpointConfiguration.SendFailedMessagesTo("error");
        // Set up audit queue
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        // Start the endpoint
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();
        // Stop the endpoint
        await endpointInstance.Stop()
            .ConfigureAwait(false);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

此設定與發送方配置類似,針對的是 "ReceiverEndpoint" 接收端點。

訊息處理程式

在接收器專案中,建立一個名為 GeneratePdfMessageHandler.cs 的新類別。

using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;
public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");
        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");
        return Task.CompletedTask;
    }
}
using NServiceBus;
using System;
using System.Threading.Tasks;
using Messages;
using IronPdf;
public class GeneratePdfMessageHandler : IHandleMessages<GeneratePdfMessage>
{
    public Task Handle(GeneratePdfMessage message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Received message to generate PDF with content: {message.Content}");
        // Generate PDF
        var renderer = new HtmlToPdf();
        var pdf = renderer.RenderHtmlAsPdf(message.Content);
        pdf.SaveAs(message.OutputPath);
        Console.WriteLine($"PDF generated and saved to: {message.OutputPath}");
        return Task.CompletedTask;
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

GeneratePdfMessage 使用 IHandleMessages 介面處理器表明它將處理 類型的消息 生成 Pdf 訊息 通過實作 IHandleMessages 介面。

NServiceBus C#(對開發者的工作方式):圖 8 - 範例控制台輸出

管理方法:在接收到消息後,Handle 函數使用 IronPDF 創建 PDF。消息中的 HTML 內容由 HtmlToPdf 渲染器代碼轉換為 PDF,然後將其保存到指定的輸出路徑。

NServiceBus C# (它對開發人員的運作方式): 圖9 - 使用NServiceBus結合RabbitMQ和IronPDF的PDF輸出

結論

NServiceBus 可以與 RabbitMQ 和 IronPDF 在 C# 中整合,提供一個可擴展且穩定的解決方案,適用於需要動態和可靠生成 PDF 的分佈式系統。這種組合利用了 NServiceBus 的消息處理能力、RabbitMQ 作為消息代理的可靠性和適應性,以及 IronPDF 強大的 PDF 編輯工具。所產生的架構確保了服務之間的解耦,使得自主演進和可擴展性成為可能。

RabbitMQ 也確保了即使在網絡或應用程序故障的情況下也能交付消息。NServiceBus 簡化了消息路由和處理,而 IronPDF 使得將 HTML 文本轉換為高品質的 PDF 文件成為可能。這種整合為開發複雜的、大規模的應用程序提供了一個靈活的框架,並提高了系統的維護性和可靠性。

最後,通過將 IronPDF 和 Iron Software 添加到您的 .NET 編程工具包中,您可以有效處理條碼、生成 PDF、執行 OCR 並連接 Excel。 IronPDF其起售价为$749,無縫融合其功能與性能、相容性及易用性 IronSoftware為了提供額外的 Web 應用程式和功能,以及更高效的開發,靈活的套件。

如果有針對專案的特定需求而定制的明確授權選項,開發人員可以自信地選擇最佳模型。這些好處使開發人員能夠有效且透明地處理各種困難。

< 上一頁
Flurl C#(它如何為開發人員工作)
下一個 >
C# 引用传递(對開發者的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >