设置订阅筛选器(Azure 服务总线)

本文提供了一些示例,说明如何为服务总线主题订阅设置筛选器。 有关筛选器的概念性信息,请参阅筛选器。

使用 Azure 门户

若要在 Azure 门户中设置订阅筛选器,请使用“服务总线订阅”页面的“筛选器”部分。

显示“服务总线订阅”页的屏幕截图,其中突出显示了“筛选器”部分。

使用 Azure CLI

使用 az servicebus topic subscription rule create 创建规则或按订阅筛选。

使用 Azure PowerShell

使用 Set-AzServiceBusRule 创建规则或按订阅筛选。

注意

订阅规则由筛选器和操作组成。 可以使用 CLI 和 PowerShell(但不能使用 Azure 门户)指定操作。

按系统属性筛选

若要在筛选器中引用系统属性,请使用以下格式:sys.<system-property-name>。

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

注意

按消息属性筛选

通过在筛选器中使用 property-name 或 访问 user.property-name 中的属性。

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

按带有特殊字符的消息属性筛选

在包含空格或标点的属性名称周围使用方括号([])表示。 括号表示属性名称;单引号表示字符串值。 如果属性名称包含闭括号(]),则将该字符表示为两个闭括号(]])。

以下示例使用字符串值的应用属性。 匹配值和非匹配值指的是第一列中指定的属性。 表格中的单引号分隔字符串;它们不属于消息属性值的一部分。

属性名称 SQL 过滤器 匹配值 不匹配的值
Order Type [Order Type] = 'priority' 'priority' 'standard'
HR-EmployeeID user.[HR-EmployeeID] = 'E123' 'E123' 'E124'
http://schemas.microsoft.com/xrm/2011/Claims/EntityLogicalName [http://schemas.microsoft.com/xrm/2011/Claims/EntityLogicalName] = 'account' 'account' 'contact'
Order]Type [Order]]Type] = 'priority' 'priority' 'standard'

双引号也用于界定属性名称。 例如,以下表达式等价于括号分隔的 URI 属性示例:

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

关于标识符语法,请参见 SQL 筛选语法:属性名称。

将字符串与万用符匹配

使用 LIKE 将字符串值属性与某个模式匹配。 % 匹配零个或多个字符,并且 _ 匹配恰好一个字符。 用于 NOT LIKE 排除与模式相符的数值。

在以下示例中,Code 是类型为字符串的应用程序属性。 单引号用于分隔字符串;它们不属于消息属性值的一部分。 '' 表示空字符串。

SQL 过滤器 匹配的值 不匹配的数值
user.Code LIKE 'order-%' 'order-'、'order-123' 'preorder-123'
user.Code LIKE '%-complete' '-complete'、'order-complete' 'order-complete-extra'
user.Code LIKE '%order%' 'order'、'preorder-123' 'invoice-123'
user.Code LIKE 'item-_' 'item-A'、'item-7' 'item-'、'item-AB'
user.Code LIKE '%' ''、'order-123' 一条没有 Code 属性的消息
user.Code NOT LIKE 'test-%' 'order-123' 'test-'、'test-123'

缺失的应用属性被评估为未知,因此它不满足 LIKE 或 NOT LIKE 中的任意一个。 关于模式语法,请参见SQL 筛选器语法:模式。

匹配字面上的通配符和转义字符

使用 = 进行精确的字符串比较。 在等式表达式中, % 和 _ 是普通字符。 要在 LIKE 模式内按字面匹配它们,可以使用 ESCAPE 选择一个单字符转义字符串,并将其放在每个字面通配符前面。

以下示例使用 ! 作为转义字符,以及一个字符串值的 Code 应用属性:

SQL 过滤器 匹配的值 不匹配的数值
user.Code = 'discount%_code' 'discount%_code' 'discount10_code'
user.Code LIKE '%!%%' ESCAPE '!' 'discount%code'、'%' 'discount10code'
user.Code LIKE 'order!_%' ESCAPE '!' 'order_'、'order_123' 'orderX123'
user.Code LIKE 'folder!!%' ESCAPE '!' 'folder!'、'folder!archive' 'folderarchive'

在 '%!%%' 中,第一个和最后一个 % 是万能符,!% 表示字面的百分号。 在 'order!_%'中, !_ 表示字面上的下划线,结尾 % 仍然是万用符。 在 'folder!!%'中, !! 表示转义字符本身。

这些是SQL过滤表达式。 如果你将它们嵌入在编程语言字符串、JSON 文档或 shell 命令中,分别应用该格式的字符串转义规则。 关于SQL转义语法,请参见 SQL筛选器语法:转义字符。

按包含特殊字符的字符串值进行筛选

用单引号包住字符串值。 用两个单引号表示嵌入的单引号。 标点符号如空格、连字符、斜杠和&符号可以直接出现在字符串中。

以下示例使用 CustomerName 了类型为字符串的应用属性:

SQL 过滤器 匹配值 不匹配的值
user.CustomerName = 'O''Brien' 'O''Brien' 'OBrien'
user.CustomerName = 'North & South - Retail/Online' 'North & South - Retail/Online' 'North & South - Retail'

在第一行中,消息的属性值为 O'Brien,带有一个单引号。 字符串值转义与用于 属性名称 的括号或双引号是分开的。 关于字符串文法,请参见 SQL 筛选语法:字符串常量。

结合字符串和数值条件

当你将 OR 和 AND 合并时,请用括号分组相关条件。 例如,当其数量至少为10时,该过滤器会选择以order-或return-开头的代码:

(user.Code LIKE 'order-%' OR user.Code LIKE 'return-%') AND user.Quantity >= 10

在这些示例中,Code 是类型为字符串的应用程序属性,Quantity 是类型为整数的应用程序属性。

代码值 数量值 匹配
'order-123' 10 Yes
'return-123' 15 Yes
'order-123' 9 No
'return-123' 9 No
'invoice-123' 15 No

按带有数字值的消息属性筛选

下面的示例演示如何在筛选器中使用带有数字值的属性。

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

基于参数的筛选器

下面是使用基于参数的筛选器的几个示例。 在这些示例中,DataTimeMp 是 DateTime 类型的消息属性,@dtParam 是作为 DateTime 对象传递给筛选器的参数。

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 CorrelationRuleFilter("Contoso");

它筛选设置为 CorrelationID 的 Contoso 消息。

注意

.NET 中的 CorrelationRuleFilter 类位于 Azure.Messaging.ServiceBus.Administration 命名空间中。 有关展示如何使用 .NET 创建筛选器的示例代码,请参阅 GitHub 上的此代码。

使用系统属性和用户属性的关联筛选器

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

它等效于 sys.ReplyTo = 'johndoe@contoso.com' AND sys.Label = 'Important' AND color = 'Red'

用于创建订阅筛选器的 .NET 示例

下面是用于创建以下服务总线实体的 .NET C# 示例:

  • 名为 topicfiltersampletopic 的服务总线主题
  • 使用 True Rule 筛选器订阅名为 AllOrders 的主题,此筛选器等效于带表达式 1=1 的 SQL 规则筛选器。
  • 名为 ColorBlueSize10Orders 的订阅,带 SQL 筛选器表达式 color='blue' AND quantity=10
  • 名为 ColorRed 的订阅,带 SQL 筛选器表达式 color='red' 和操作
  • 名为 HighPriorityRedOrders 的订阅,带关联筛选器表达式 Subject = "red", CorrelationId = "high"

有关详细信息,请参阅内联代码注释。

namespace CreateTopicsAndSubscriptionsWithFilters
{
    using Azure.Identity;
    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;

        // fully qualified namespace for the Service Bus
        static readonly string fullyQualifiedNamespace = "<YOUR SERVICE BUS NAMESPACE>.servicebus.chinacloudapi.cn";

        // 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(fullyQualifiedNamespace, new DefaultAzureCredential());

                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.Identity;
    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";

        // fully qualified namespace for the Service Bus
        static string fullyQualifiedNamespace = "<YOUR SERVICE BUS NAMESPACE>.servicebus.chinacloudapi.cn";

        // 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 fullyQualifiedNamespace)
        {
            // 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(fullyQualifiedNamespace);

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

        async Task SendMessagesToTopicAsync(string fullyQualifiedNamespace)
        {
            // Create the clients that we'll use for sending and processing messages.
            client = new ServiceBusClient(fullyQualifiedNamespace, new DefaultAzureCredential());
            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 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(fullyQualifiedNamespace);
            }
            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 服务总线功能,请尝试使用所选语言的示例。