1

我希望你能帮助我。

我是 Azure 的新手,在理解它时遇到了很多麻烦。我正在尝试编写一个 azure 函数,该函数由 EventHubTrigger 触发(当新事件发送到 eventHub 时),并将该事件存储在我的 cosmos db 表中。(cosmos db 作为输出)。

我正在用 C# 编写,因此 function.json 是自动创建的,我无法编辑它。我似乎无法使其正常工作,正确设置触发器和输出绑定。

这是我的功能代码:

[FunctionName("InsertEvent")]
public static void Run(
    [EventHubTrigger("WaterlyNamespace", 
    Connection = "connectionStr")] string eventHubString,
    [CosmosDB(
    databaseName: "waterly_db",
    collectionName: "water_table", 
    Id = "device_id",
    ConnectionStringSetting = "conStr" )] out dynamic dbItem,
    ILogger log)

{
    log.LogInformation("C# trigger function processed an event from eventhub");

    EventItem dataJson = JsonConvert.DeserializeObject<EventItem>(eventHubString);

    //adding timestamp to event json
    dataJson.timestamp = DateTime.Now;

    dbItem = dataJson;
}

这是生成的function.json:

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-3.0.3",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "connection": "ConnectionStr",
      "eventHubName": "WaterlyNamespace",
      "name": "eventHubString"
    }
  ],
  "disabled": false,
  "scriptFile": "../bin/Waterly-iot-functions.dll",
  "entryPoint": "Waterly_iot_functions.InsertEvent.Run"
}

这是host.json:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    }
  },
  "extensions": {
    "cosmosDB": {
      "connectionMode": "Gateway",
      "protocol": "Https",
      "leaseOptions": {
        "leasePrefix": "prefix1"
      }
    }
  }
}

这就是我在发布此代码后在 Azure 门户中看到的内容: 参见图片

任何想法为什么触发器位于 Azure 门户的输出区域中,我错过了什么?

任何帮助将不胜感激。谢谢,

4

1 回答 1

4

我认为您在属性中使用连接字符串有问题。

按照我的步骤,它可以正常工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace FunctionApp54
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([EventHubTrigger("test", Connection = "str")] EventData[] events,
            [CosmosDB(
                databaseName: "testbowman",
                collectionName: "testbowman",
                ConnectionStringSetting = "CosmosDBConnection",
                PartitionKey = "111")]out dynamic item, 
            ILogger log)
        {
            item = new { id = Guid.NewGuid() , custom = "11111111111111111111"};
        }
    }
}

这是我的 local.settings.json:(在本地,环境变量设置在 local.settings.json 中)

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "str": "Endpoint=sb://testbowman.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxx",
    "CosmosDBConnection": "AccountEndpoint=https://testbowman.documents.azure.com:443/;AccountKey=xxxxxx;"
  }
}

您应该从以下位置获取连接字符串:

在此处输入图像描述

在此处输入图像描述

然后我创建了一个控制台应用程序来将事件发送到事件中心。

using System;
using System.Text;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;

namespace SendEventToEventHub
{
    class Program
    {
        private const string connectionString = "Endpoint=sb://testbowman.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=pftXmTesAa894OWYGZyD5s8GynR9hXVJl7CdbMy45Nc=";
        private const string eventHubName = "test";
        static async Task Main(string[] args)
        {
            // Create a producer client that you can use to send events to an event hub
            await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
            {
                // Create a batch of events 
                using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

                // Add events to the batch. An event is a represented by a collection of bytes and metadata. 
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("First event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Second event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Third event")));

                // Use the producer client to send the batch of events to the event hub
                await producerClient.SendAsync(eventBatch);
                Console.WriteLine("A batch of 3 events has been published.");
            }
        }
    }
}

之后,我启动我的函数,我可以在 cosmosdb 中看到输出:

在此处输入图像描述

顺便说一句,如果您部署到 azure,则应在下面设置设置,而不是 local.settings.json:

在此处输入图像描述

请让我知道您是否可以按照上述尝试成功。祝你好运。:)

于 2020-05-26T06:47:19.260 回答