Azure Functions 和 DocumentDB 触发器

Azure Functions and DocumentDB triggers

是否可以指定 DocumentDB 在写入 DocumentDB 时触发触发器?

我有一个 Azure 函数,可以从服务总线队列中提取 JSON 消息并将它们放入 DocumentDB,如下所示:

using System;
using System.Threading.Tasks;

public static string Run(string myQueueItem, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

    return myQueueItem;
}

这会将新文档插入到数据库中,因为它们被添加到服务总线队列中,但是我需要 DocumentDB 在添加它们和添加附件时处理它们。这在当前设置中无法完成,我想告诉 DocumentDB 触发触发器。

我试过这样的方法:

using System;
using System.Threading.Tasks;

public static string Run(string myQueueItem, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

    return "x-ms-documentdb-post-trigger-include: addDocument\n" + myQueueItem;
}

它不起作用,给我这样的错误:

Exception while executing function: Functions.ServiceBusQueueTriggerCSharp1. Microsoft.Azure.WebJobs.Host: Error while handling parameter _return after function returned:. Newtonsoft.Json: Unexpected character encountered while parsing value: x. Path '', line 0, position 0.

我喜欢这个设置,因为我可以用添加记录的请求使队列饱和,它们只是缓冲直到数据库可以处理它,处理需求高峰,但它允许从客户端计算机卸载数据的速度尽可能快因为网络可以承载它,然后当需求再次下降时 queue/database 组合会被赶上。

您可以参考以下代码示例来创建在 Azure Functions 中启用触发器的文档。

using System;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;

public static void Run(string myQueueItem, TraceWriter log)
{
    string EndpointUri = "https://{documentdb account name}.documents.azure.com:443/";
    string PrimaryKey = "{PrimaryKey}";

    DocumentClient client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

    client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("{databaseid}", "{collenctionid}"), new MyChunk { MyProperty = "hello" },
               new RequestOptions
               {
                   PreTriggerInclude = new List<string> { "YourTriggerName" },
               }).Wait();

    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}

public class MyChunk
{
    public string MyProperty { get; set; }
}

注意:要在C#函数中使用Microsoft.Azure.DocumentDB NuGet包,请在函数中upload a project.json file to the function's folder应用程序的文件系统。

project.json

 {
  "frameworks": {
    "net46":{
      "dependencies": {
        "Microsoft.Azure.DocumentDB": "1.13.1"
      }
    }
   }
}

此外,请确保您已经在您的DocumentDB中创建了触发器,创建触发器的详细信息请参考this article