Azure Functions 和 DocumentDB 触发器

2024-02-13

是否可以指定 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;
}

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

执行函数时出现异常: Functions.ServiceBusQueueTriggerCSharp1。 Microsoft.Azure.WebJobs.Host: 函数返回后处理参数 _return 时出错:。 Newtonsoft.Json:解析值时遇到意外字符: X。路径 '',第 0 行,位置 0。

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


您可以参考以下代码示例来创建在 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; }
}

Note:要在 C# 函数中使用 Microsoft.Azure.DocumentDB NuGet 包,请将 project.json 文件上传到函数的文件夹 https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#package-management在函数应用程序的文件系统中。

项目.json

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

另外,请确保您已经在DocumentDB中创建了触发器,创建触发器的详细信息请参考本文 https://learn.microsoft.com/en-us/azure/documentdb/documentdb-programming#client-sdk-support.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Azure Functions 和 DocumentDB 触发器 的相关文章

随机推荐