使用.NET Core SDK创建筛选的服务总线订阅

时间:2018-08-01 11:49:27

标签: azure .net-core azureservicebus

我想从.NET Core 2.1应用程序内部使用Azure Service Bus。我熟悉Nuget软件包Microsoft.Azure.ServiceBus随附的SDK,并正在使用该SDK编写主题并从中接收消息。

我现在想要的是为每个客户端创建有关此主题的订阅。关键是我想使用SqlFilter创建过滤的订阅。这意味着,我必须通过代码创建预订。

顺便说一句:据我所知,在代码中执行此操作的另一种方法是使用ARM模板进行部署,因为门户不允许我创建过滤订阅。

我了解到Microsoft.Azure.ServiceBus无法创建资源,因此我去了Nuget软件包Microsoft.Azure.Management.ServiceBus。因此,我现在可以通过如下代码创建新的订阅:

private static async Task CreateSubscriptionAsync()
{
    var context = new AuthenticationContext($"https://login.microsoftonline.com/{Configuration["AppSettings:AzureManagement:TenantId"]}");
    var token = await context.AcquireTokenAsync(
        "https://management.core.windows.net/",
        new ClientCredential(Configuration["AppSettings:AzureManagement:ClientId"], Configuration["AppSettings:AzureManagement:ClientSecret"]));
    var creds = new TokenCredentials(token.AccessToken);
    using (var sbClient = new ServiceBusManagementClient(creds)
    {
        SubscriptionId = VariableHelper.Configuration["AppSettings:AzureManagement:AzureSubscriptionId"]
    })
    {                
        var queueParams = new SBSubscription
        {
            LockDuration = TimeSpan.FromSeconds(10)
        };          
        await sbClient.Subscriptions.CreateOrUpdateAsync(
            Configuration["AppSettings:ServiceBus:ResourceGroup"],
            Configuration["AppSettings:ServiceBus:Namespace"],
            Configuration["AppSettings:ServiceBus:TopicName"],
            "mysub",
            queueParams);                
    }
}

这有效,因此我有一个新订阅,也可以删除。但是现在在哪里可以定义过滤器? SBSubscription类型不包含定义过滤器的选项,并且sbClient.Subscriptions.CreateOrUpdateAsync中没有方法重载。

我发现在代码中执行此操作的唯一方法是基于旧的Nuget WindowsAzure.ServiceBus,它不适用于.NET Core。因此,我将使用像这样的NamespaceManager

var manager = NamespaceManager.CreateFromConnectionString("MyConnectionString");            
var rule = new RuleDescription("property > 4");
var sub = manager.CreateSubscriptionAsync(new SubscriptionDescription("mytopic", "mysub"), rule); 

没有此功能,完整的主题对我来说似乎是无用的,而且我不敢相信这意味着Azure Service Bus根本不适合.NET Core。

编辑:Arunprabhu建议的解决方案

我只是想完整地介绍解决方案。

  1. 添加对NuGet Microsoft.Azure.Management.ServiceBus的引用。
  2. 添加对NuGet Microsoft.Azure.ServiceBus的引用。
  3. 按如下方式创建子项:
private static async Task CreateSubscriptionAsync()
{
    // this is to show that it works with any subscription-name
    var subName = Guid.NewGuid().ToString("N");     
    // create the subscription using Azure Management API
    var context = new AuthenticationContext($"https://login.microsoftonline.com/{Configuration["AppSettings:AzureManagement:TenantId"]}");
    var token = await context.AcquireTokenAsync(
        "https://management.core.windows.net/",
        new ClientCredential(Configuration["AppSettings:AzureManagement:ClientId"], Configuration["AppSettings:AzureManagement:ClientSecret"]));
    var creds = new TokenCredentials(token.AccessToken);
    using (var sbClient = new ServiceBusManagementClient(creds)
    {
        SubscriptionId = VariableHelper.Configuration["AppSettings:AzureManagement:AzureSubscriptionId"]
    })
    {                
        var queueParams = new SBSubscription
        {
            LockDuration = TimeSpan.FromSeconds(10)
        };          
        await sbClient.Subscriptions.CreateOrUpdateAsync(
            Configuration["AppSettings:ServiceBus:ResourceGroup"],
            Configuration["AppSettings:ServiceBus:Namespace"],
            Configuration["AppSettings:ServiceBus:TopicName"],
            subName,
            queueParams);                
    }
    // add filter-rule using Azure ServiceBus API
    var client = new SubscriptionClient(ServiceBusConnectionString, Configuration["AppSettings:ServiceBus:TopicName"], subName);
    await client.AddRuleAsync("default", new SqlFilter("1=1"));
    // That's it        
}

4 个答案:

答案 0 :(得分:4)

  

我了解到Microsoft.Azure.ServiceBus无法创建资源

Microsoft.Azure.ServiceBus的3.1.0版开始,您可以使用ManagementClient创建实体,而无需Microsoft.Azure.Management.ServiceBus库。它具有CreateSubscriptionAsync()的重载,将RuleDescription作为默认规则创建。另外,不提供RuleDescription会自动为您设置默认规则。

答案 1 :(得分:2)

Microsoft.Azure.ServiceBus中的SubscriptionClient下有类似的方法可用于规则管理。在here中查找示例。

答案 2 :(得分:0)

解释Sean Feldman的答案,因为他的示例链接现在已断开,您可以执行以下操作:

public static async Task CreateSubscription(
    string connection,
    string topicPath,
    string subscriptionName,
    string matchExpression,
    string ruleDescription,
    bool checkForExisting = false,
    CancellationToken cancellationToken = default(CancellationToken)
)
{
    if (checkForExisting)
    {
        var exists = (await new ManagementClient(connection)
            .GetSubscriptionsAsync(topicPath, cancellationToken: cancellationToken))
            .Any(sub => sub.SubscriptionName == subscriptionName);

        if (exists) return;
    }

    var subscriptionDescription = new SubscriptionDescription(topicPath, subscriptionName);
    var rule = new RuleDescription(ruleDescription, new SqlFilter(matchExpression));
    await new ManagementClient(connection).CreateSubscriptionAsync(subscriptionDescription, rule, cancellationToken);
}

为简单起见,我已删除了强制输入验证,例如空字符串或无效字符。我还提供了一种检查订阅是否已存在的方法。理想情况下,您只执行一次检查,然后在内存中保留一个运行选项卡,这样就不必每次都执行该API调用。

对于matchExpression,您将根据发布时添加到消息中的用户属性,以SQLish语法为该订阅定义过滤器。 该实现将类似于:

await CreateSubscription(
    Configuration.GetConnectionString("MyServiceBusConnectionString"),
    "myTopicName",
    "mySubscription",
    "MyUserProperty='MyValue'",
    "MyRule",
    true
)

答案 3 :(得分:0)

可以使用Microsoft.Azure.Management.ServiceBus包创建过滤器,它们是Rules的一部分。

await client.Rules.CreateOrUpdateAsync(resourceGroupName, namespaceName, 
    topicName, subscriptionName, filterName, new Rule {
    SqlFilter = new SqlFilter(sql)
});

您可以在下面的Azure门户屏幕快照中看到过滤器名称和SQL字符串:

enter image description here