【问题标题】:Differentiate between data coming in my Service bus Queue区分进入我的服务总线队列的数据
【发布时间】:2021-02-03 08:15:46
【问题描述】:

下面是一个 Azure 函数,它从我的 cosmos db 将数据推送到我的服务总线中。这已经是编写好的代码,在这里他们在将 Json 返回到服务总线之前检查不同的元数据。现在我必须编写另一个函数,从服务总线中提取这些数据并根据来自上述函数或其他来源的数据进一步处理它,因为需求正在发生变化,我可能会从其他来源获取服务总线中的数据。我想知道如何区分这些数据以识别哪些来自哪里。

[FunctionName( "Push Data to Service Bus" )]
        [return: ServiceBus( "topicname", Connection = "ServiceBusConnection" )]
        public static string Notify(
            [CosmosDBTrigger(
                databaseName: "test",
                collectionName: "testcontay",
                ConnectionStringSetting = "CosmosDBConnection",
                LeaseCollectionName = "leases",
                CreateLeaseCollectionIfNotExists = true)]
                IReadOnlyList<Document> documents,
            ILogger log )
        {
            if( documents == null || documents.Count == 0 )
            {
                log.LogWarning( "No documents received" );
                return null;
            }


            var triggerDocs =
                (from d in documents
                 let trigger = d.GetPropertyValue<bool?>( "Trigger" )
                 where !trigger.HasValue || trigger == true
                 select new
                 {
                     Id = d.GetPropertyValue<string>( "id" ),
                     Project = d.GetPropertyValue<string>( "Project" ),
                     ProjectId = d.GetPropertyValue<string>( "ProjectId" ),
                     Tags = d.GetPropertyValue<string[]>( "Tags" ),
                     Properties = d.GetPropertyValue<Dictionary<string, object>>( "Properties" ),
                     Categories = d.GetPropertyValue<string[]>( "Categories" ),
                     Trigger = d.GetPropertyValue<bool?>( "Trigger" ),
                     Received = DateTime.UtcNow
                 }).ToList();


            log.LogInformation( $"Documents triggered: {triggerDocs.Count}" );

            if( triggerDocs.Count() == 0 )
                return string.Empty;

            var json = JsonSerializer.Serialize( triggerDocs, triggerDocs.GetType() );
            return json;
        }


[FunctionName( "GettingDataFromServiceBus" )]
        public async void Run([ServiceBusTrigger("topicname", "subscriptionname",
            Connection = "AzureServiceBusString")] 
            string SbMsg, ExecutionContext context,
            ILogger log)
        {
           
                if (!string.IsNullOrEmpty(SbMsg))
                {
                    log.LogInformation($"C# ServiceBus topic trigger function processed message: {SbMsg}");
}
}

【问题讨论】:

  • 您已经在使用主题和订阅。因此,您已在订阅中应用过滤器并在新的 Azure 函数中使用它
  • 但这将要求创建两个订阅。在我的要求中,所有 json 数据都来自一个订阅。无论如何我对 sbMsg 进行过滤,检查 sbMsg 是否具有与从 CosmosDb 触发器推送的相同的属性
  • 检查这个 - github.com/Azure/azure-functions-host/issues/4439。这表明它目前不受支持。您可以跟进相同的 github isuse 或创建一个新的。

标签: c# azure-functions azureservicebus


【解决方案1】:

更新:

    //Such as this is your message.
    string str = "{\"projectID\":\"111\"}";
    try
    {
        JObject obj = JObject.Parse(str);
        if (obj["projectID"] != null)
        {
            //Message have projectID, so it is from xxx.
        }
        else
        {
            //Message don't have projectID, so it is from xxx.
        }
    }
    catch (Exception ex) { 
        //Message format is not json, so it is comes from xxx.
    }

原答案:

您可以使用自定义属性来满足您的要求。将 ApplicationProperties 添加到消息中,然后将其发布到 azure 服务总线队列。

看看这个(基于.Net):

https://docs.microsoft.com/en-us/dotnet/api/azure.messaging.servicebus.servicebusmessage?view=azure-dotnet#properties

C# 示例:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using Azure.Messaging.ServiceBus;

namespace ConsoleApp3
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            string connectionString = "Endpoint=sb://bowman1012.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X/NHgQ4AQxul6YlMsUofD+JNE20Tovnzx3g2gDt8qyY=";
            string queueName = "queuename";
            string source = "function";
            await SendMessageAsync(connectionString, queueName, source);
        }
        static async Task SendMessageAsync(string connectionString,string queueName,string source)
        {
            // create a Service Bus client 
            await using (ServiceBusClient client = new ServiceBusClient(connectionString))
            {
                // create a sender for the queue 
                ServiceBusSender sender = client.CreateSender(queueName);

                // create a message that we can send
                ServiceBusMessage message = new ServiceBusMessage("Hello world!");
                message.ApplicationProperties.Add("message_source",source);

                // send the message
                await sender.SendMessageAsync(message);
                Console.WriteLine($"Sent a single message to the queue: {queueName}");
            }
        }
    }
}

【讨论】:

  • 我认为它与 Service Bus 没有任何关系。我有一组数据,在进一步处理之前,我需要对这些数据进行过滤
  • @AnkitKumar 我的意思是使用消息的自定义属性来记录信息的来源(使用key-value),然后就可以根据这个进行过滤了。
  • 我不确定你的意思是什么?您是要我在数据中添加另一个属性,然后将其用于过滤吗?
  • @AnkitKumar 是的,使用自定义属性。我认为没有内置方法可以找到消息的来源。
  • 这不是我能做的......我不能改变数据
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2013-08-19
  • 2017-02-25
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多