azure 函数 - 当 eventhub 中的新事件时触发,将其写入 cosmos db - 不起作用,为什么?

标签 azure azure-functions azure-cosmosdb azure-eventhub azure-triggers

希望你能帮助我。

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

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

这是我的函数代码:

[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"
}

这是主机.json:

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

这是我在发布此代码后在 Azure 门户中看到的内容: See Image

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

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

最佳答案

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

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

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

您应该从这些位置获取连接字符串:

enter image description here

enter image description here

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

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 中看到输出:

enter image description here

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

enter image description here

按照上述方法尝试后是否可以成功,请告诉我。祝你好运。:)

关于azure 函数 - 当 eventhub 中的新事件时触发,将其写入 cosmos db - 不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003403/

相关文章:

azure - 问 : Azure Cosmos DB Graph: How to run queries in Graph API when Indexing Policy is defined as Manual?

image - 在成功的 TeamCity 构建上创建 Docker 镜像

azure - 无法对 PR 验证进行排队

azure-cosmosdb - ReadItemAsync 与 GetItemLinqQueryable?

azure - Cosmos DB 扩展成本

angularjs - Azure AD 应用程序、cordova、adal-Angular、Windows Phone 8 重定向 url

python-3.x - 如何强制本地 Azure 函数服务器使用 HTTP 2.0 而不是 1.1?

Azure Functions 静态 SqlConnection - 正确的扩展方式?

azure - 在 Azure Functions 中使用 F#

CosmosDB 更改源上的 Azure V1 功能会在发布时触发所有更改