設定訂閱篩選 (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-%'
注意
- 如需系統屬性的清單,請參閱訊息、承載和序列化。
- 在篩選條件中使用來自 Azure.Messaging.ServiceBus.ServiceBusMessage 的系統屬性名稱。
- 來自 Azure.Messaging.ServiceBus.ServiceBusMessage 的
Subject
會對應至已取代 Microsoft.Azure.ServiceBus.Message 中的Label
。
篩選訊息屬性
以下是在篩選中使用應用程式或使用者屬性的範例。 您可以使用 Azure.Messaging.ServiceBus.ServiceBusMessage.ApplicationProperties) (最新) 存取應用程式屬性集,或使用語法:user.property-name
或僅 property-name
,透過 Microsoft.Azure.ServiceBus.ServiceBusMessage (已淘汰) 存取使用者屬性集。
MessageProperty = 'A'
user.SuperHero like 'SuperMan%'
在 2026 年 9 月 30 日,我們將淘汰不符合 Azure SDK 準則的 Azure 服務匯流排 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
參數型篩選
以下是使用參數型篩選的一些範例。 在這些範例中,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 CorrelationFilter("Contoso");
這會透過將 CorrelationID
設定為 Contoso
來篩選訊息。
注意
.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 範例
以下是建立下列服務匯流排實體的 .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.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 服務匯流排的功能,請以您所選擇的語言嘗試各式範例。