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

时间:2020-04-23 17:54:03

标签: azure azureservicebus

我有以下情况:我有2个微服务在Azure Service Bus中订阅,一个微服务发送推送通知,另一个微服务发送电子邮件,这些微服务将永远无法协同工作,因此消息将仅由一个微服务执行。 / p>

我正在搜索,将消息发送到主题并有一个筛选器来选择应该执行什么操作的微服务似乎是个好主意。

所以我有两个问题:

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

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

enter image description here

谢谢

1 个答案:

答案 0 :(得分:1)

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

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

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

发布的工作方式是将其发布到主题,该主题接收消息并针对所有订阅上的过滤器进行验证。具有令人满意的过滤条件的订阅会收到该消息。不满足过滤条件的订阅将被跳过。过滤器分为三种类型:布尔值,SQL和关联。布尔过滤器与您无关。相关性或SQL过滤器将完成这项工作。您可以在我的post中找到有关过滤器的更多信息。

我在这里建议的是用通知方法“盖章”每条消息。由于每种方法将使用一种通知方法,因此“关联”过滤器将是最简单,最有效的。可以将通知方法值分配给传出消息的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

两个过滤器设置为:

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

// push notifications service subscription
var pushFilter = new new CorrelationFilter();
filter.Label = "push";

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

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"
}));