在 Azure 函数中处理多个返回值

问题描述 投票:0回答:1

我有一个 Azure 函数,当前使用来自 Azure 服务总线的消息,进行一些转换并将消息发布到 Azure 事件中心。但是,我还想向 Azure 服务总线发布一条消息,该消息与我正在使用的消息不同。可以通过使用多个返回值来实现吗?

[FunctionName("IntegrationFunction")]
[return: EventHub("%Transactions:EVH:Transactions:Hub%", Connection = "Transactions:EVH:Transactions")]
public Transaction Run(
    [ServiceBusTrigger(
        "%Transactions:SB:Transactions:ReceiveTopic%",
        "%Transactions:SB:Transactions:AnalyticsTopicSubscription%",
        Connection = "Transactions:SB:Transactions")]
    string mySbMsg,
    ILogger log)
{
    if (string.IsNullOrWhiteSpace(mySbMsg))
    {
        throw new ArgumentNullException(nameof(mySbMsg));
    }

    log.LogInformation($"Service bus topic trigger function processing message: {mySbMsg}");
    
    var retailTransaction = JsonConvert.DeserializeObject<RetailTransaction>(
        mySbMsg,
        JsonSerialisationUtils.SerialiserSettings);
    
    if (retailTransaction == null)
    {
        throw new JsonException("Deserialized transaction was null");
    }

    try
    {
        var transaction = retailTransaction.ToDto();
        log.LogInformation($"Transaction {transaction.TransactionNumber} processed.");
        return transaction;
    }
    catch (Exception e)
    {
        log.LogError(e, "Error mapping transaction.");
    }

    return null;
}
azure azure-functions azureservicebus azure-eventhub
1个回答
0
投票

如本github问题中所述,在azure函数中使用多个返回是不可行的,您可以使用

CloudQueue
IAsyncCollector<T>
对象。

  • 我使用以下代码将服务总线消息发送到事件中心以及另一个服务总线队列。
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace _78237298
{
    public class IntegrationFunction
    {
        [FunctionName("IntegrationFunction")]
        public async Task Run(
            [ServiceBusTrigger(
            "%Transactions:SB:Transactions:ReceiveTopic%", 
            "%Transactions:SB:Transactions:AnalyticsTopicSubscription%", 
            Connection = "Transactions:SB:Transactions")]
            string mySbMsg,
            [EventHub("%Transactions:EVH:Transactions:Hub%", Connection = "Transactions:EVH:Transactions")] IAsyncCollector<Transaction> outputEventHubMessages,
            [ServiceBus("%OtherServiceBus:QueueName%", Connection = "OtherServiceBus:ConnectionString")] IAsyncCollector<string> outputQueueMessages,
            ILogger log)
        {
            if (string.IsNullOrWhiteSpace(mySbMsg))
            {
                throw new ArgumentNullException(nameof(mySbMsg));
            }

            log.LogInformation($"Service bus topic trigger function processing message: {mySbMsg}");

            var retailTransaction = JsonConvert.DeserializeObject<RetailTransaction>(
                mySbMsg);

            if (retailTransaction == null)
            {
                throw new JsonException("Deserialized transaction was null");
            }

            try
            {
                var transaction = retailTransaction.ToDto();
                log.LogInformation($"Transaction {transaction.TransactionNumber} processed.");
                
                // Send to Event Hub
                await outputEventHubMessages.AddAsync(transaction);

                // Send to another Service Bus queue
                var anotherSbMsg = JsonConvert.SerializeObject(transaction);
                await outputQueueMessages.AddAsync(anotherSbMsg);
            }
            catch (Exception e)
            {
                log.LogError(e, "Error mapping transaction.");
            }

        }
    }

    public class RetailTransaction
    {
        public string TransactionNumber { get; set; }
        public decimal Amount { get; set; }

        public Transaction ToDto()
        {
            return new Transaction
            {
                TransactionNumber = this.TransactionNumber,
                Amount = this.Amount
            };
        }
    }

    public class Transaction
    {
        public string TransactionNumber { get; set; }
        public decimal Amount { get; set; }
    }
}

.csproj-

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <RootNamespace>_78237298</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Messaging.EventHubs" Version="5.11.1" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.EventHubs" Version="6.2.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="5.14.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.3.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

输出-

第一个服务巴士主题-

我正在从此服务总线发送消息。

enter image description here

enter image description here

活动中心-

enter image description here

第二个服务总线队列-

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.