Azure는 클라우드 환경에서 안정적인 메시징 서비스를 제공하는 Azure Service Bus를 지원합니다. 이를 활용하면 마이크로서비스 아키텍처에서 비동기 데이터 처리, 이벤트 기반 메시징, IoT 데이터 처리 등을 쉽게 구현할 수 있습니다.

이번 글에서는 Azure Service Bus를 사용하여 메시지를 송수신하는 구조를 설명하고, C#을 활용한 코드 예제까지 함께 제공하겠습니다.


 

1. Azure Service Bus란?

Azure Service Bus는 클라우드 기반 메시징 서비스로, 분산 애플리케이션 간 메시지를 안정적으로 주고받을 수 있도록 도와줍니다. 주요 특징은 다음과 같습니다.

비동기 통신 지원 – 프로세스 간 독립적인 데이터 전송 가능
메시지 큐 및 토픽 – 다양한 메시징 패턴 제공
높은 안정성과 확장성 – 장애 복구 기능 내장
IoT 및 이벤트 드리븐 시스템 지원


2. Azure Service Bus 아키텍처

Azure Service Bus는 크게 **Queue(큐)**와 **Topic(토픽)**을 지원합니다.

  • Queue(큐): 메시지를 하나의 수신자에게 전송 (Point-to-Point 방식)
  • Topic(토픽): 여러 구독자에게 메시지를 전달 (Publish-Subscribe 방식)

3. C#으로 Azure Service Bus 메시지 전송하기 (Queue 기반)

Azure Service Bus를 활용한 메시지 전송 코드 예제를 소개합니다.
이 코드는 QueueClient를 사용하여 데이터를 송신하는 방식입니다.

📌 사전 준비

  1. Azure Portal에서 Service Bus 네임스페이스 및 큐 생성
  2. Connection String 확보 (네임스페이스 → 공유 액세스 정책 → RootManageSharedAccessKey)

✅ C# 코드: 메시지 전송 및 수신

🔹 메시지 전송 코드

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json;

class Program
{
    private const string ServiceBusConnectionString = "Endpoint=sb://YOUR_NAMESPACE.servicebus.windows.net/;SharedAccessKeyName=YOUR_KEY_NAME;SharedAccessKey=YOUR_ACCESS_KEY";
    private const string QueueName = "my-queue";
    private static IQueueClient queueClient;

    static async Task Main(string[] args)
    {
        queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
        
        Console.WriteLine("Azure Service Bus 메시지 전송 시작...");
        
        var messageBody = new { DeviceId = "Sensor01", Value = 78.5, Timestamp = DateTime.UtcNow };
        string messageJson = JsonConvert.SerializeObject(messageBody);
        
        var message = new Message(Encoding.UTF8.GetBytes(messageJson));
        
        await queueClient.SendAsync(message);
        Console.WriteLine($"메시지 전송 완료: {messageJson}");

        await queueClient.CloseAsync();
    }
}

🔹 메시지 수신 코드

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

class Receiver
{
    private const string ServiceBusConnectionString = "Endpoint=sb://YOUR_NAMESPACE.servicebus.windows.net/;SharedAccessKeyName=YOUR_KEY_NAME;SharedAccessKey=YOUR_ACCESS_KEY";
    private const string QueueName = "my-queue";
    private static IQueueClient queueClient;

    static async Task Main(string[] args)
    {
        queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            MaxConcurrentCalls = 1,
            AutoComplete = false
        };

        queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

        Console.WriteLine("메시지 수신 대기 중...");
        Console.ReadKey();
    }

    static async Task ProcessMessagesAsync(Message message, CancellationToken token)
    {
        string receivedMessage = Encoding.UTF8.GetString(message.Body);
        Console.WriteLine($"수신된 메시지: {receivedMessage}");

        await queueClient.CompleteAsync(message.SystemProperties.LockToken);
    }

    static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
    {
        Console.WriteLine($"메시지 처리 중 오류 발생: {exceptionReceivedEventArgs.Exception}");
        return Task.CompletedTask;
    }
}

4. 실행 및 결과

위 코드를 실행하면 메시지 전송 프로그램에서 메시지를 큐에 넣고, 수신 프로그램이 이를 받아 출력하게 됩니다.

메시지 전송 결과

Azure Service Bus 메시지 전송 시작...
메시지 전송 완료: {"DeviceId":"Sensor01","Value":78.5,"Timestamp":"2025-02-20T12:00:00Z"}

메시지 수신 결과

메시지 수신 대기 중...
수신된 메시지: {"DeviceId":"Sensor01","Value":78.5,"Timestamp":"2025-02-20T12:00:00Z"}

5. 마무리 및 활용 사례

Azure Service Bus는 다양한 클라우드 애플리케이션에서 활용됩니다.

🔹 IoT 데이터 수집: 센서 데이터 처리
🔹 이벤트 기반 처리: 주문 및 결제 시스템
🔹 마이크로서비스 아키텍처: 독립적인 서비스 간 통신

💡 추가로 배우면 좋은 내용

  • Azure Service Bus Topic을 활용한 Pub/Sub 모델
  • Azure Functions와 연동하여 Serverless 메시지 처리

🔹 ServiceBusExplorer : 데이터 확인

https://github.com/paolosalvatori/ServiceBusExplorer/releases

 

Releases · paolosalvatori/ServiceBusExplorer

The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. The tool provides advanced features like import/export functionality...

github.com


https://www.youtube.com/watch?v=uEz5wNWF6-k

 

+ Recent posts