Share via


구독 필터 설정(Azure Service Bus)

이 문서에서는 Service Bus 항목에 대한 구독에 대한 필터 설정에 대한 몇 가지 예를 제공합니다. 필터에 대한 개념적 설명은 필터를 참조하세요.

시스템 속성의 필터

필터에서 시스템 속성을 참조하려면 sys.<system-property-name> 형식을 사용합니다.

sys.label LIKE '%bus%'
sys.messageid = 'xxxx'
sys.correlationid like 'abc-%'

참고 항목

메시지 속성의 필터

다음은 필터에서 애플리케이션 또는 사용자 속성을 사용하는 예제입니다. 구문을 property-nameuser.property-name 사용하여 Azure.Messaging.ServiceBus.ServiceBusMessage.ApplicationProperties(최신) 또는 Microsoft.Azure.ServiceBus.ServiceBusMessage(사용되지 않음)에서 설정한 사용자 속성을 사용하여 설정된 애플리케이션 속성에 액세스할 수 있습니다.

MessageProperty = 'A'
user.SuperHero like 'SuperMan%'

2026년 9월 30일에 Azure SDK 지침을 따르지 않는 Azure Service Bus SDK 라이브러리 WindowsAzure.ServiceBus, Microsoft.Azure.ServiceBus 및 com.microsoft.azure.servicebus를 사용 중지합니다. 또한 SBMP 프로토콜에 대한 지원이 종료되므로 2026년 9월 30일 이후에는 더 이상 이 프로토콜을 사용할 수 없습니다. 해당 날짜 마이그레이션에 중요한 보안 업데이트와 개선된 기능을 제공하는 최신 Azure SDK 라이브러리로 마이그레이션합니다.

이전 라이브러리는 2026년 9월 30일 이후에도 계속 사용할 수 있지만 더 이상 Microsoft로부터 공식 지원 및 업데이트를 받을 수 없습니다. 자세한 내용은 사용 중지 공지 지원을 참조하세요.

특수 문자가 있는 메시지 속성의 필터

메시지 속성 이름에 특수 문자가 있으면 큰따옴표(")를 사용하여 속성 이름을 묶습니다. 예를 들어 속성 이름이 "http://schemas.microsoft.com/xrm/2011/Claims/EntityLogicalName"이면 필터에서 다음 구문을 사용합니다.

"http://schemas.microsoft.com/xrm/2011/Claims/EntityLogicalName" = 'account'

숫자 값이 있는 메시지 속성의 필터

다음 예제는 필터에 숫자 값이 있는 속성을 사용하는 방법을 보여 줍니다.

MessageProperty = 1
MessageProperty > 1
MessageProperty > 2.08
MessageProperty = 1 AND MessageProperty2 = 3
MessageProperty = 1 OR MessageProperty2 = 3

매개 변수 기반 필터

다음은 매개 변수 기반 필터를 사용하는 몇 가지 예제입니다. 이 예제에서 DataTimeMpDateTime 형식의 메시지 속성이고, @dtParamDateTime 개체로 필터에 전달되는 매개 변수입니다.

DateTimeMp < @dtParam
DateTimeMp > @dtParam

(DateTimeMp2-DateTimeMp1) <= @timespan //@timespan is a parameter of type TimeSpan
DateTimeMp2-DateTimeMp1 <= @timespan

IN 및 NOT IN 사용

StoreId IN('Store1', 'Store2', 'Store3')

sys.To IN ('Store5','Store6','Store7') OR StoreId = 'Store8'

sys.To NOT IN ('Store1','Store2','Store3','Store4','Store5','Store6','Store7','Store8') OR StoreId NOT IN ('Store1','Store2','Store3','Store4','Store5','Store6','Store7','Store8')

C# 샘플은 GitHub의 토픽 필터 샘플을 참조하세요.

상관관계 필터

CorrelationID를 사용하는 상관 관계 필터

new CorrelationFilter("Contoso");

CorrelationIDContoso로 설정된 메시지를 필터링합니다.

참고 항목

.NET의 CorrelationRuleFilter 클래스는 Azure.Messaging.ServiceBus.Administration 네임스페이스에 있습니다. 일반적으로 .NET을 사용하여 필터를 만드는 방법을 보여 주는 샘플 코드는 GitHub의 이 코드를 참조하세요.

시스템 및 사용자 속성을 사용한 상관 관계 필터

var filter = new CorrelationRuleFilter();
filter.Label = "Important";
filter.ReplyTo = "johndoe@contoso.com";
filter.Properties["color"] = "Red";

sys.ReplyTo = 'johndoe@contoso.com' AND sys.Label = 'Important' AND color = 'Red'와 동등합니다.

구독 필터 생성을 위한 .NET 예제

다음 Service Bus 엔터티를 만드는 .NET C# 예제는 다음과 같습니다.

  • topicfiltersampletopic이라는 Service Bus 토픽
  • True Rule 필터가 있는 AllOrders라는 토픽에 대한 구독으로, 1=1 식이 있는 SQL 규칙 필터와 동일합니다.
  • SQL 필터 식 color='blue' AND quantity=10가 있는 ColorBlueSize10Orders라는 구독
  • SQL 필터 식 color='red' 및 작업이 있는 ColorRed라는 구독
  • 상관 관계 필터 식 Subject = "red", CorrelationId = "high"가 있는 HighPriorityRedOrders라는 구독

자세한 내용은 인라인 코드 주석을 참조하세요.

namespace CreateTopicsAndSubscriptionsWithFilters
{
    using Azure.Messaging.ServiceBus.Administration;
    using System;
    using System.Threading.Tasks;

    public class Program
    {
        // Service Bus Administration Client object to create topics and subscriptions
        static ServiceBusAdministrationClient adminClient;

        // connection string to the Service Bus namespace
        static readonly string connectionString = "<YOUR SERVICE BUS NAMESPACE - CONNECTION STRING>";

        // name of the Service Bus topic
        static readonly string topicName = "topicfiltersampletopic";

        // names of subscriptions to the topic
        static readonly string subscriptionAllOrders = "AllOrders";
        static readonly string subscriptionColorBlueSize10Orders = "ColorBlueSize10Orders";
        static readonly string subscriptionColorRed = "ColorRed";
        static readonly string subscriptionHighPriorityRedOrders = "HighPriorityRedOrders";

        public static async Task Main()
        {
            try
            {

                Console.WriteLine("Creating the Service Bus Administration Client object");
                adminClient = new ServiceBusAdministrationClient(connectionString);
                
                Console.WriteLine($"Creating the topic {topicName}");
                await adminClient.CreateTopicAsync(topicName);

                Console.WriteLine($"Creating the subscription {subscriptionAllOrders} for the topic with a True filter ");
                // Create a True Rule filter with an expression that always evaluates to true
                // It's equivalent to using SQL rule filter with 1=1 as the expression
                await adminClient.CreateSubscriptionAsync(
                        new CreateSubscriptionOptions(topicName, subscriptionAllOrders), 
                        new CreateRuleOptions("AllOrders", new TrueRuleFilter()));


                Console.WriteLine($"Creating the subscription {subscriptionColorBlueSize10Orders} with a SQL filter");
                // Create a SQL filter with color set to blue and quantity to 10
                await adminClient.CreateSubscriptionAsync(
                        new CreateSubscriptionOptions(topicName, subscriptionColorBlueSize10Orders), 
                        new CreateRuleOptions("BlueSize10Orders", new SqlRuleFilter("color='blue' AND quantity=10")));

                Console.WriteLine($"Creating the subscription {subscriptionColorRed} with a SQL filter");
                // Create a SQL filter with color equals to red and a SQL action with a set of statements
                await adminClient.CreateSubscriptionAsync(topicName, subscriptionColorRed);
                // remove the $Default rule
                await adminClient.DeleteRuleAsync(topicName, subscriptionColorRed, "$Default");
                // now create the new rule. notice that user. prefix is used for the user/application property
                await adminClient.CreateRuleAsync(topicName, subscriptionColorRed, new CreateRuleOptions 
                                { 
                                    Name = "RedOrdersWithAction",
                                    Filter = new SqlRuleFilter("user.color='red'"),
                                    Action = new SqlRuleAction("SET quantity = quantity / 2; REMOVE priority;SET sys.CorrelationId = 'low';")

                                }
                );

                Console.WriteLine($"Creating the subscription {subscriptionHighPriorityRedOrders} with a correlation filter");
                // Create a correlation filter with color set to Red and priority set to High
                await adminClient.CreateSubscriptionAsync(
                        new CreateSubscriptionOptions(topicName, subscriptionHighPriorityRedOrders), 
                        new CreateRuleOptions("HighPriorityRedOrders", new CorrelationRuleFilter() {Subject = "red", CorrelationId = "high"} ));

                // delete resources
                //await adminClient.DeleteTopicAsync(topicName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

수신 메시지를 보내기 위한 .NET 예제

namespace SendAndReceiveMessages
{
    using System;
    using System.Text;
    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;
    using Newtonsoft.Json;
    
    public class Program 
    {
        const string TopicName = "TopicFilterSampleTopic";
        const string SubscriptionAllMessages = "AllOrders";
        const string SubscriptionColorBlueSize10Orders = "ColorBlueSize10Orders";
        const string SubscriptionColorRed = "ColorRed";
        const string SubscriptionHighPriorityOrders = "HighPriorityRedOrders";

        // connection string to your Service Bus namespace
        static string connectionString = "<YOUR SERVICE BUS NAMESPACE - CONNECTION STRING>";

        // the client that owns the connection and can be used to create senders and receivers
        static ServiceBusClient client;

        // the sender used to publish messages to the topic
        static ServiceBusSender sender;

        // the receiver used to receive messages from the subscription 
        static ServiceBusReceiver receiver;

        public async Task SendAndReceiveTestsAsync(string connectionString)
        {
            // This sample demonstrates how to use advanced filters with ServiceBus topics and subscriptions.
            // The sample creates a topic and 3 subscriptions with different filter definitions.
            // Each receiver will receive matching messages depending on the filter associated with a subscription.

            // Send sample messages.
            await this.SendMessagesToTopicAsync(connectionString);

            // Receive messages from subscriptions.
            await this.ReceiveAllMessageFromSubscription(connectionString, SubscriptionAllMessages);
            await this.ReceiveAllMessageFromSubscription(connectionString, SubscriptionColorBlueSize10Orders);
            await this.ReceiveAllMessageFromSubscription(connectionString, SubscriptionColorRed);
            await this.ReceiveAllMessageFromSubscription(connectionString, SubscriptionHighPriorityOrders);
        }


        async Task SendMessagesToTopicAsync(string connectionString)
        {
            // Create the clients that we'll use for sending and processing messages.
            client = new ServiceBusClient(connectionString);
            sender = client.CreateSender(TopicName);

            Console.WriteLine("\nSending orders to topic.");

            // Now we can start sending orders.
            await Task.WhenAll(
                SendOrder(sender, new Order()),
                SendOrder(sender, new Order { Color = "blue", Quantity = 5, Priority = "low" }),
                SendOrder(sender, new Order { Color = "red", Quantity = 10, Priority = "high" }),
                SendOrder(sender, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
                SendOrder(sender, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
                SendOrder(sender, new Order { Color = "blue", Quantity = 5, Priority = "high" }),
                SendOrder(sender, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
                SendOrder(sender, new Order { Color = "red", Quantity = 5, Priority = "low" }),
                SendOrder(sender, new Order { Color = "red", Quantity = 10, Priority = "low" }),
                SendOrder(sender, new Order { Color = "red", Quantity = 5, Priority = "low" }),
                SendOrder(sender, new Order { Color = "yellow", Quantity = 10, Priority = "high" }),
                SendOrder(sender, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
                SendOrder(sender, new Order { Color = "yellow", Quantity = 10, Priority = "low" })
                );

            Console.WriteLine("All messages sent.");
        }

        async Task SendOrder(ServiceBusSender sender, Order order)
        {
            var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order)))
            {
                CorrelationId = order.Priority,
                Subject = order.Color,
                ApplicationProperties =
                {
                    { "color", order.Color },
                    { "quantity", order.Quantity },
                    { "priority", order.Priority }
                }
            };
            await sender.SendMessageAsync(message);

            Console.WriteLine("Sent order with Color={0}, Quantity={1}, Priority={2}", order.Color, order.Quantity, order.Priority);
        }

        async Task ReceiveAllMessageFromSubscription(string connectionString, string subsName)
        {
            var receivedMessages = 0;

            receiver = client.CreateReceiver(TopicName, subsName, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete } );
            
            // Create a receiver from the subscription client and receive all messages.
            Console.WriteLine("\nReceiving messages from subscription {0}.", subsName);

            while (true)
            {
                var receivedMessage = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(10));
                if (receivedMessage != null)
                {
                    foreach (var prop in receivedMessage.ApplicationProperties)
                    {
                        Console.Write("{0}={1},", prop.Key, prop.Value);
                    }
                    Console.WriteLine("CorrelationId={0}", receivedMessage.CorrelationId);
                    receivedMessages++;
                }
                else
                {
                    // No more messages to receive.
                    break;
                }
            }
            Console.WriteLine("Received {0} messages from subscription {1}.", receivedMessages, subsName);
        }

       public static async Task Main()
        {
            try
            {
                Program app = new Program();
                await app.SendAndReceiveTestsAsync(connectionString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

    class Order
    {
        public string Color
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public string Priority
        {
            get;
            set;
        }
    }
}

다음 단계

다음 샘플을 참조하세요.

선택한 언어로 샘플을 사용하여 Azure Service Bus 기능을 살펴봅니다.