Azure Function CosmosDb Change feed触发器是否会处理JsonDocument类型的输入文档?

uz75evzq  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(92)

我有下面的Azure函数和CosmosDb更改提要触发器:

[Function("Example")]
        public async Task Run([CosmosDBTrigger(
                databaseName: "%DATABASE_NAME%",
                containerName: "example-container",
                Connection = "EXAMPLE_DATABASE_CONNECTION",
                LeaseContainerName = "example-container-leases",
                LeaseContainerPrefix = "Example",
                CreateLeaseContainerIfNotExists = true)]
            IReadOnlyList<JsonDocument> documents)
       {
         // do stuff with the documents
       }

字符串
文档指出JsonDocument builds an in-memory view of the data into a pooled buffer. Therefore the JsonDocument type implements IDisposable and needs to be used inside a using block. Azure Functions自己处理这个问题还是我应该手动处理它们?如果根本不释放它们,会不会导致函数出现问题?

vbopmzt1

vbopmzt11#

Azure函数是否处理dispose JsonDocument本身
我没有得到任何MS文档,其中说Azure函数处理它,但你可以使用我下面的代码来手动处理它。

一月一日

using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace FunctionApp7
{
    public class Function1
    {
        private readonly ILogger _logger;

        public Function1(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Function1>();
        }

        [Function("Function1")]
        public void Run([CosmosDBTrigger(
            databaseName: "example-database",
            collectionName: "example-container",
            ConnectionStringSetting = "EXAMPLE_DATABASE_CONNECTION",
            LeaseCollectionName = "example-container-leases",
            LeaseCollectionPrefix ="Example",
            CreateLeaseCollectionIfNotExists =true)] IReadOnlyList<JsonDocument> documents)
        {
            _logger.LogInformation("C# CosmosDB change feed trigger function processed a batch of {0} documents", documents.Count);
            foreach (var document in documents)
            {
                try
                {

                    string jsonString = document.RootElement.GetRawText();
                    MyModel model = JsonSerializer.Deserialize<MyModel>(jsonString);

                    Console.WriteLine($"Model Data: {jsonString}");

                }
                finally
                {
                    document.Dispose();

                }
            }
        }
    }

    public class MyModel
    {
        public string? Property1 { get; set; }
        public string? Property2 { get; set; }
    }
}

字符串

一米


的数据
如果根本不释放它们,是否会导致函数出现问题
由于没有特定的文档说明Azure函数处理IDisposable本身,因此它始终是垃圾收集的最佳实践。你也可以参考这个SO thread,它也说同样的话。

相关问题