2

是否可以指定DocumentDB在写入DocumentDB时触发触发器?Azure函数和DocumentDB触发器

我有拉JSON消息掀起了服务总线队列,并将它们放入DocumentDB像这样的Azure的功能:

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

我喜欢这种设置,因为我可以请求饱和队列中添加记录,他们只是缓冲,直到该数据库可以处理它,这与在需求高峰的交易,但它允许客户机上的数据卸载速度与网络可以承载的速度一样快,然后当需求再次下降时,队列/数据库组合就会被抓住。

回答

2

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

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#的功能,请在功能应用程序的文件系统upload a project.json file to the function's folder使用Microsoft.Azure.DocumentDB NuGet包。

project.json

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

此外,请确保您已在DocumentDB创建触发器,详细了解创建触发器,请参考this article