.NET ヘルプ

NServiceBus C# (開発者のための仕組み)

更新済み 8月 13, 2024
共有:

イントロダクション

NServiceBusは、.NET Framework用に設計された強力で適応性の高いサービスバスで、分散システム開発を効率化します。 強力なメッセージング・パターンを提供することで、複数のマイクロサービスやアプリケーション間での信頼性の高いメッセージ処理と配信が保証される。 NServiceBusは、基盤となるメッセージング・アーキテクチャを抽象化することで、開発者は分散システム構築の複雑さではなく、ビジネス・ロジックに集中することができます。

対照的に、IronPDFはPDFファイルを生成、閲覧、修正するためのよく知られた.NETライブラリです。 使いやすく、ASPXファイルやHTMLなどの様々なソースからPDFを作成するのに非常に効率的であることでよく知られています。

開発者はNServiceBus cとIronPDFを組み合わせることで、信頼性、拡張性、保守性に優れた、PDFドキュメントを生成・管理するソフトウェアシステムを構築することができます。

この記事では、シンプルなC# NServiceBusプロジェクトをセットアップし、IronPDFと統合する方法を見ていく。 この入門チュートリアルを読めば、この2つの効果的な技術がどのように連携して、分散環境におけるPDF関連のタスクを簡素化できるかを正確に理解できるはずです。

NServiceBus](https://docs.particular.net/)C#とは

NServiceBusは、分散システムとサービス指向.NETアーキテクチャを簡単に作成できる、強力で適応性の高いフレームワークです。 NServiceBusを利用することで、様々なメッセージタイプを簡単に管理し、信頼性の高い通信を確保することができます。 これは、特にシームレスなメッセージ・ルーティングと処理が不可欠なウェブ・アプリケーションや同様のアーキテクチャでは極めて重要である。 NServiceBusのメッセージハンドラは、メッセージの受信を効果的に処理し、すべての論理コンポーネントがスムーズに相互作用するようにする。 NServiceBusには次のような重要な機能がある:

NServiceBus C#(開発者のための仕組み):図1 - NServiceBus C#

NServicebusの特徴

メッセージベースのコミュニケーション

NServiceBusは、システム内の異なるサービスやコンポーネント間のメッセージベースの通信を促進する。 コンポーネントを切り離すことで、この方法は拡張と管理が容易な設計を生み出す。

信頼性の高いメッセージング

リトライ、デッドレターキュー、その他のフォールトトレランス技術を自動的に管理することで、信頼できるメッセージ配信を保証する。 ネットワーク停止やその他の障害問題が頻発する分散システムでは、この信頼性が不可欠だ。

パブリッシュ/サブスクライブ・モデル

NServiceBusではパブリッシュ/サブスクライブパターンがサポートされており、サービスがイベントをパブリッシュし、他のサービスがこれらのイベントをサブスクライブできるようになっている。 これによりイベント駆動型アーキテクチャが可能になり、システムのあるコンポーネントで発生したイベントに変更を加えると、他のコンポーネントで反応が発生するようになる。

佐賀マネジメント

NServiceBusは、サーガを統合的にサポートしているため、長期的なビジネスプロセスを管理することができます。 サガは、サービス・プラットフォームが状態を管理し、複数のサービス間の複雑なオペレーションを調整することを可能にする。

拡張性とカスタマイズ

卓越したレベルの拡張性を提供し、開発者はメッセージの取り扱い、処理、輸送プロセスをパーソナライズすることができる。 その適応性の高さから、さまざまなシーンで使用することができる。

様々なメッセージング・プラットフォームとの統合

MSMQ、RabbitMQ、Azure Service Bus、Amazon SQSなど、数多くのメッセージングシステムをNServiceBusと統合することができる。 これにより、開発者は要件に最も適した通信インフラ・ソリューションを選択することができる。

C&num で NServiceBus を作成し、設定する;

C#プロジェクトでNServiceBusを使い始める前に、まず開発環境をセットアップし、基本的なプロジェクトを作成し、基本的なメッセージングサービスとシナリオを構築する必要があります。 ステップ・バイ・ステップのガイドをご覧ください。

新しいVisual Studioプロジェクトを作成する

Visual Studioでは、コンソール・プロジェクトの作成は簡単です。 Visual Studio環境では、以下の簡単な手順でコンソールアプリケーションを起動できます:

使用する前にパソコンにVisual Studioをインストールしていることを確認してください。

新しいプロジェクトを開始

ファイル]をクリックし、[新規]を選択し、最後に[プロジェクト]を選択する。

NServiceBus C#(開発者のための仕組み):図2 - New" をクリックします;

コンソールアプリ」または「コンソールアプリ」を選択できます。 (.NET Core(ドットネット コア))"テンプレートは、以下のプロジェクト・テンプレート・リファレンスのリストから選択してください。

「名前」フィールドにプロジェクト名を入力してください。

NServiceBus C#(開発者のための仕組み):図3 - プロジェクトの名前と場所を指定する

プロジェクトの保管場所を選ぶ。

Create "をクリックすると、コンソールアプリケーションのプロジェクトが開始されます。

NServiceBus C#(開発者のための仕組み):図4 - create"をクリックする;

NServiceBusパッケージのインストール

Tools > NuGet Package Manager > Package Manager Consoleに移動して、NuGet Package Manager Consoleを開きます。

以下のコマンドを実行して、NServiceBus NuGetパッケージをインストールします。

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

輸送手段を選ぶ

トランスポートは、NServiceBusがメッセージを送受信するために必要です。 ラーニング・トランスポートは使いやすく、テストや開発に適しているので、このまま使い続けるつもりだ。

を実行して、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:こんにちは、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に変換。 メディアクエリーとレスポンシブデザインという2つの最新ウェブ標準をサポートしている。 HTMLとCSSを使用して、動的にスタイル設定されたPDF文書、請求書、レポートを作成するのに便利です。

**PDF編集

すでに存在するPDFに、テキストや写真、その他の素材を追加します。 PDFファイルからテキストや画像を取り出します。 複数のPDFを1つのファイルに結合します。PDFファイルを複数のドキュメントに分割します。 注釈、フッター、ヘッダー、透かしを入れる。

**PDF変換

Word、Excel、画像、その他のファイル形式をPDFに変換します。 PDFから画像への変換 (PNG、JPEGなど。).

**性能と信頼性

高い性能と信頼性は、生産現場における設計目標である。 巨大なドキュメントを効率的に管理。

IronPDFのインストール

NuGetパッケージマネージャーコンソールを開いて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プロジェクト内に、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#

Sender プロジェクトと Receiver プロジェクトの両方に、Messages プロジェクトへの参照を含めます。

メッセージ配信にRabbitMQを使用するように、Senderプロジェクトで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");
    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 "という名前で初期化される。("送信者エンドポイント").

endpointConfigurationはトランスポート設定である。 ローカルのRabbitMQインスタンスに接続することで、メソッドUseTransport() NServiceBus がトランスポートメカニズムとして RabbitMQ を使用するように設定します。

監査キューとエラー・キュー 失敗したメッセージと監査処理されたメッセージをどこに送るかは、 SendFailedMessagesTo を使って設定します。(「エラー) およびAuditProcessedMessagesTo(監査)それぞれ

メッセージ送信: endpointInstance.A GeneratePdfMessageは、Sendを介して "ReceiverEndpoint "に送信される。("ReceiverEndpoint"、メッセージ) 関数

PDFを生成するための受信機の設定

RabbitMQ経由でメッセージを受け取り、IronPDFを使ってPDFを生成するために、ReceiverプロジェクトでNServiceBusエンドポイントを設定します。

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 "レシーバーエンドポイントのこの設定は、センダーの設定と同等である。

メッセージハンドラ

Receiverプロジェクトで、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#

IHandleMessages InterfaceHandlerを使用するGeneratePdfMessageは、以下のタイプのメッセージを処理することを示します。 Pdfメッセージの生成 IHandleMessagesのインターフェイスを実装する。

NServiceBus C#(開発者のための仕組み):図8 - コンソール出力の例

Manage Approach:メッセージを受け取った後、Handle関数はIronPDFを使ってPDFを作成します。 メッセージ内のHTMLコンテンツは、HtmlToPdfレンダラー・コードによってPDFに変換され、指定された出力パスに保存されます。

NServiceBus C#(開発者のための仕組み):図9 - NServiceBusとRabbitMQをIronPDFfと共に使用した場合のPDF出力

結論

NServiceBusはC#でRabbitMQやIronPDFと統合することができ、PDFをダイナミックかつ確実に生成する必要がある分散システムにスケーラブルで安定したソリューションを提供します。 この組み合わせは、NServiceBusのメッセージ処理機能、RabbitMQのメッセージブローカーとしての信頼性と適応性、IronPDFの堅牢なPDF編集ツールを利用します。 その結果、サービス間のデカップリングがアーキテクチャによって保証され、自律的な進化とスケーラビリティが可能になる。

また、RabbitMQはネットワークやアプリケーションに障害が発生した場合でも、確実にメッセージを配信します。 NServiceBusはメッセージのルーティングと処理をよりシンプルにし、IronPDFはHTMLテキストを高品質のPDFドキュメントに変換することを可能にする。 この統合は、システムの保守性と信頼性を向上させるだけでなく、高度で大規模なアプリケーションを開発するための柔軟なフレームワークを提供する。

最後に、.NETプログラミングのツールキットにIronPDFとIron Softwareを加えることで、バーコード、PDFの生成、OCRの実行、Excelとのリンクを効果的に行うことができます。 IronPDFの性能、互換性、使いやすさをシームレスに融合させている。 アイアンソフトウェアのフレキシブルなスイートは、ウェブアプリケーションと機能を追加し、より効率的な開発を提供する。

プロジェクト固有の要件に合わせてカスタマイズされたライセンスオプションが明確に定義されていれば、開発者は自信を持って最適なモデルを選択できる。 これらの利点により、開発者はさまざまな困難に効果的かつ透過的に対処することができる。

< 以前
Flurl C# (開発者のための仕組み)
次へ >
C# 参照渡し(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >