首页 文章

Azure Functions和DocumentDB触发器

提问于
浏览
2

是否可以指定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位 .

我喜欢这种设置,因为我可以通过添加记录的请求来使队列饱和,它们只是缓冲,直到数据库可以处理它,它处理需求的峰值,但它允许从客户端机器上卸载数据,就像网络可以携带一样快然后,当需求再次下降时,队列/数据库组合会被捕获 .

1 回答

  • 2

    您可以参考以下代码示例来创建在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包,请在函数应用程序的文件系统中使用upload a project.json file to the function's folder .

    project.json

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

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

相关问题