如何仅向一个 Azure 服务总线订阅发送消息?

Ren*_*ite 2 azure azureservicebus

我有以下场景:我在 Azure 服务总线中订阅了 2 个微服务,一个微服务用于发送推送通知,另一个微服务用于发送电子邮件,这些微服务永远不会一起工作,因此消息将仅由一个微服务执行。

我正在搜索,看起来将消息发送到主题并使用过滤器来选择应该执行操作的微服务是个好主意。

所以我有两个问题:

我应该使用主题和过滤器吗?不确定是否是更好的做法。

如果是,是否有办法将消息发送到正确的订阅?例如,我向订阅 X 发布一条消息,而不是向所有订阅发布消息。

在此输入图像描述

谢谢

Sea*_*man 5

我应该使用主题和过滤器吗?不确定是否是更好的做法。

是的。这是主题和订阅的经典用例。

如果是,是否有办法将消息发送到正确的订阅?例如,我向订阅 X 发布一条消息,而不是向所有订阅发布消息。

发布的工作方式是将其发布到主题,主题获取消息并根据所有订阅的过滤器进行验证。满足过滤条件的订阅会收到消息。不满足过滤条件的订阅将被跳过。过滤器分为三种类型:布尔型、SQL 型和关联型。布尔过滤器与您不太相关。相关或 SQL 过滤器可以完成这项工作。您可以在我的帖子中找到有关过滤器的更多信息。

我在这里建议的是用通知方法“标记”每条消息。由于您将在每个方法中使用一个通知方法,因此“相关性”过滤器将是最简单且最有效的。通知方法值可以分配给Label传出消息的系统属性和两个订阅(一个用于电子邮件服务,一个用于推送通知服务)上的相关过滤器。例如(伪代码):

var message = new Message();

// custom logic to determine what notification method to use

if (notificationMethod == NotificationMethod.Email)
{
  message.Label = "email";
}
else
{
  message.Label = "push";
}

// publish the message to the topic
Run Code Online (Sandbox Code Playgroud)

两个过滤器设置为:

// email notification service subscription
var emailFilter = new CorrelationFilter();
filter.Label = "email";

// push notifications service subscription
var pushFilter = new new CorrelationFilter();
filter.Label = "push";
Run Code Online (Sandbox Code Playgroud)

使用给定的过滤器创建订阅(例如电子邮件):

var management = new ManagementClient(...);
await management.CreateSubscriptionAsync(new SubscriptionDescription("topic", "subscription"));

var client = new SubscriptionClient("topic", "subscription");
await client.AddRuleAsync(new RuleDescription(
{
  Filter = emailFilter,
  Name = "email filter"
}));
Run Code Online (Sandbox Code Playgroud)