我似乎找不到任何有关如何从 Azure Function 隔离进程将多个文档输出到 Azure CosmosDB 的文档。
我理解“因为 .NET 独立项目在单独的工作进程中运行,所以绑定无法利用丰富的绑定类,例如 ICollector、IAsyncCollector 和 CloudBlockBlob。”参考号https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#bindings
但是,我假设仍然必须有一种方法可以在计时器函数的单次执行中插入多个记录。
在下面的代码中,我可以轻松插入一条记录,但是如何调整此代码以插入数组或记录列表?
我找到了这篇文章,但它似乎没有阐明如何在计时器函数的上下文中应用此代码。
[Function("MyFunction")]
public async Task<MultiResponse> Run([TimerTrigger("0 */1 * * * *")] MyInfo myTimer)
{
var result = await _dataService.GetData();
return new MultiResponse()
{
Document = new MyDocument
{
id = System.Guid.NewGuid().ToString(),
message = "hello world"
}
};
}
public class MultiResponse
{
[CosmosDBOutput("MyDatabase", "MyCollection",
ConnectionStringSetting = "CosmosDbConnectionString", CreateIfNotExists = true)]
public MyDocument Document { get; set; }
}
public class MyDocument
{
public string id { get; set; }
public string message { get; set; }
}
我没有使用孤立进程中似乎缺乏支持的输出绑定方法,而是能够成功地直接使用 SDK 插入文档!
参考。 https://github.com/Azure/azure-cosmos-dotnet-v3
NUGET 包:
Install-Package Microsoft.Azure.Cosmos
代码示例:
CosmosClient client = new CosmosClient("https://mycosmosaccount.documents.azure.com:443/", "mysupersecretkey");
Database database = await client.CreateDatabaseIfNotExistsAsync("MyDatabaseName");
Container container = await database.CreateContainerIfNotExistsAsync(
"MyContainerName",
"/partitionKeyPath",
400);
// Create an item
dynamic testItem = new { id = "MyTestItemId", partitionKeyPath = "MyTestPkValue", details = "it's working", status = "done" };
ItemResponse<dynamic> createResponse = await container.CreateItemAsync(testItem);
根据文档,要返回多个文档,请返回“T[],其中 T 是 JSON 可序列化类型”。
因此,要调整您的代码,请返回一组
MyDocument
JSON 可序列化对象,如下所示:
[Function("MyFunction")]
[CosmosDBOutput("MyDatabase", "MyCollection", ConnectionStringSetting = "CosmosDbConnectionString", CreateIfNotExists = true)]
public async Task<MyDocument[]> Run(
[TimerTrigger("0 */1 * * * *")] MyInfo myTimer)
{
// Initialize the response as a new List of MyDocuments
List<MyDocument> responseDocuments = myDocuments = new();
// Run your code to create your documents...
MyDocument doc1 = new MyDocument
{
id = System.Guid.NewGuid().ToString(),
message = "hello world from document 1"
}
responseDocuments.Add(doc1);
MyDocument doc2 = new MyDocument
{
id = System.Guid.NewGuid().ToString(),
message = "hello world from document 2"
}
responseDocuments.Add(doc2);
// Return the List of MyDocuments as an array
return responseDocuments.ToArray();
}
public class MyDocument
{
[JsonPropertyName("id")]
public string id { get; set; }
[JsonPropertyName("message")]
public string message { get; set; }
}