无法从 Azure Function 连接到 Azure Cosmos DB。获取“Microsoft.Azure.Cosmos.Direct:未将对象引用设置为对象的实例

问题描述 投票:0回答:1

从 Udemy 课程获得 .Net 代码并在我的本地运行。编写了一个连接到 Azure Cosmos DB 并创建项目的 Azure 函数。但无法连接到 Azure Cosmos DB。请参阅下面的代码和错误。在调试中,我发现线路有一些问题

_container.CreateItemAsync(_blobdetails, newPartitionKey(_message.VideoName)).GetAwaiter().GetResult();

代码:

    using System;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;
    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    using Microsoft.Azure.Cosmos;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Host;
    using Microsoft.Extensions.Logging;
    
    namespace ReceiveMessages
    {
        public static class Process
        {
            private static string blob_connection_string = "<blob connection string>";
            private static string source_container_name = "unprocessed";
            private static string destination_container_name = "processed";
    
            private static readonly string _connection_string = "<cosmos connection string>";
            private static readonly string _database_name = "appdb";
            private static readonly string _container_name = "video";
    
            [FunctionName("ProcessVideos")]
            public static async Task Run([ServiceBusTrigger("videoqueue", Connection = "connection")]ServiceBusReceivedMessage myQueueItem, ILogger log)
            {
                try
                {
                    ReceivedMessage _message = JsonSerializer.Deserialize<ReceivedMessage>(Encoding.UTF8.GetString(myQueueItem.Body));
    
                    BlobServiceClient _client = new BlobServiceClient(blob_connection_string);
                    BlobContainerClient _source_container_client = _client.GetBlobContainerClient(source_container_name);
                    BlobClient _source_blob_client = _source_container_client.GetBlobClient(_message.VideoName);
    
                    BlobContainerClient _destination_container_client = _client.GetBlobContainerClient(destination_container_name);
                    BlobClient _destination_blob_client = _destination_container_client.GetBlobClient(_message.VideoName);
    
                    CosmosClient _cosmosclient = new CosmosClient(_connection_string, new CosmosClientOptions());
                    Container _container = _cosmosclient.GetContainer(_database_name, _container_name);
    
                    BlobDownloadInfo _info = _source_blob_client.Download();
                    // Copy the blob to the destination container
                    await _destination_blob_client.StartCopyFromUriAsync(_source_blob_client.Uri);
    
                    log.LogInformation(_info.Details.LastModified.ToString());
                    log.LogInformation(_info.ContentLength.ToString());
    
                    BlobDetails _blobdetails = new BlobDetails();
                    _blobdetails.BlobName = _message.VideoName;
                    _blobdetails.BlobLocation = "https://videostorage100.blob.core.windows.net/processed/" + _message.VideoName;
                    _blobdetails.ContentLength = _info.ContentLength.ToString();
                    _blobdetails.LastModified = _info.Details.LastModified.ToString();
                    _blobdetails.id = Guid.NewGuid().ToString();
    
                    _container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName)).GetAwaiter().GetResult();
                    Console.WriteLine("Item created");
    
                    // Delete the blob from the unprocessed container
                    _source_blob_client.Delete();
                    // Add the details of the blob to an Azure Cosmos DB account
    
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                }
    
    
    
            }
        }
    }       

日志:

* Executed 'ProcessVideos' (Failed, Id=53b3d0b2-d46a-4ba9-bf26-d8de76af0bce, Duration=41001ms)
[2022-03-19T23:07:25.845Z] Executed 'ProcessVideos' (Failed, Id=48b50a3d-f69f-436f-accf-5140c3d7f8a0, Duration=41001ms)
[2022-03-19T23:07:25.854Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object.{"name":"CreateItemAsync","id":"c16e23cd-badc-4f0b-a940-3fac7f52c4f7","caller info":{"member":"OperationHelperWithRootTraceAsync","file":"ClientContextCore.cs","line":219},"start time":"11:06:46:894","duration in milliseconds":36808.7271,"data":{"Client Configuration":{"Client Created Time Utc":"2022-03-19T23:06:45.5706176Z","NumberOfClientsCreated":3,"User Agent":"cosmos-netstandard-sdk/3.19.0|3.19.1|08|X64|Microsoft Windows 10.0.19043|.NET Core 3.1.20|N|","ConnectionConfig":{"gw":"(cps:50, urto:10, p:False, httpf: False)","rntbd":"(cto: 5, icto: -1, mrpc: 30, mcpe: 65535, erd: False, pr: ReuseUnicastPort)","other":"(ed:False, be:False)"},"ConsistencyConfig":"(consistency: NotSet, prgns:[])"}},"children":[{"name":"ItemSerialize","id":"647e3fbb-bd9f-4b12-9367-3ed1f6c4d436","caller info":{"member":"ExtractPartitionKeyAndProcessItemStreamAsync","file":"ContainerCore.Items.cs","line":931},"start time":"11:06:46:921","duration in milliseconds":20.2124},{"name":"Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler","id":"23650859-deb4-44e1-a696-daeeab7564c8","start time":"11:06:47:893","duration in milliseconds":35799.6699,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.DiagnosticsHandler","id":"f18265a9-2a93-46c8-aa05-78b69ed30086","start time":"11:06:47:927","duration in milliseconds":35763.5861,"data":{"CPU Load History":{"CPU History":"(2022-03-19T23:06:47.9376170Z 38.049)"}},"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.RetryHandler","id":"876ad64c-0dc3-42a2-9a47-4054ec301b57","start time":"11:06:47:945","duration in milliseconds":35744.6099,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.RouterHandler","id":"01ca2b19-39c0-477d-ad85-f930397e682a","start time":"11:06:47:954","duration in milliseconds":35729.8987,"children":[{"name":"Microsoft.Azure.Cosmos.Handlers.TransportHandler","id":"e372af16-b68c-438d-9ae1-2fdaad2d5f23","start time":"11:06:47:955","duration in milliseconds":35720.3525,"children":[{"name":"Microsoft.Azure.Documents.ServerStoreModel Transport Request","id":"9995478e-5933-4b21-8c08-cf03501ebe03","caller info":{"member":"ProcessMessageAsync","file":"TransportHandler.cs","line":109},"start time":"11:06:47:963","duration in milliseconds":35704.0196,"data":{"Client Side Request Stats":{"Id":"AggregatedClientSideRequestStatistics","ContactedReplicas":[{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14059/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901445077053s/"},{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14352/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901532421814s/"},{"Count":1,"Uri":"rntbd://cdb-ms-prod-westus1-fd76.documents.azure.com:14095/apps/0152c08e-edca-4977-bca0-40bb4325ee70/services/117845df-eb50-4f9a-8f97-0a5981cfeaae/partitions/1e48d158-7844-4a7c-89a0-aa99c17adcb8/replicas/132920901532421816s/"}],"RegionsContacted":["https://videodbupdate-westus.documents.azure.com/"],"FailedReplicas":[],"AddressResolutionStatistics":[{"StartTimeUTC":"2022-03-19T23:06:48.3431877Z","EndTimeUTC":"2022-03-19T23:06:48.4598190Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:06:54.7678280Z","EndTimeUTC":"2022-03-19T23:06:54.8820135Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:01.6288211Z","EndTimeUTC":"2022-03-19T23:07:01.7399788Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:09.6372169Z","EndTimeUTC":"2022-03-19T23:07:09.7484346Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"},{"StartTimeUTC":"2022-03-19T23:07:17.9939496Z","EndTimeUTC":"2022-03-19T23:07:18.1025134Z","TargetEndpoint":"https://videodbupdate-westus.documents.azure.com//addresses/?$resolveFor=dbs%2fHdYjAA%3d%3d%2fcolls%2fHdYjAIRIK9s%3d%2fdocs&$filter=protocol eq rntbd&$partitionKeyRangeIds=0"}],"*

*[2022-03-19T23:07:25.848Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: ServiceUnavailable (503); Substatus: 0; ActivityId: 349d6ef1-4696-4ec8-88c9-5913129164ec; Reason: (Service is currently unavailable. More info: https://aka.ms/cosmosdb-tsg-service-unavailable
[2022-03-19T23:07:26.012Z] System.Private.CoreLib: Exception while executing function: ProcessVideos. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: ServiceUnavailable (503); Substatus: 0; ActivityId: 40f51724-2bf3-46b2-ac99-c9030aed41c6; Reason: (Service is currently unavailable. More info: https://aka.ms/cosmosdb-tsg-service-unavailable
[2022-03-19T23:07:26.040Z] ActivityId: 349d6ef1-4696-4ec8-88c9-5913129164ec, Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, Windows/10.0.19043 cosmos-netstandard-sdk/3.19.1);. Microsoft.Azure.Cosmos.Direct: Message: The requested resource is no longer available at the server.*
azure azure-functions azure-cosmosdb
1个回答
1
投票

此问题已在 SDK 3.20 中修复:https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/changelog.md#-3200---2021-06-21

请升级到推荐版本以获取此修复和其他修复。

更多修复

您正在为每个函数执行创建一个客户端(Blob 和 Cosmos),这违背了建议,并且随着队列消息数量的增加会带来问题,请遵循 https://learn.microsoft.com/azure/azure- function/manage-connections?tabs=csharp#static-clients 并使用 Singleton/static 实例。我们有一个关于如何将 DI 和函数与 CosmosClient 结合使用的完整示例,网址为 https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/AzureFunctions .

另外,不要阻塞线程,因为您的函数已经是异步的,所以请改为执行

await _container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName))

这 2 点是大多数情况下会生成这些服务不可用错误的原因。

也非常重要,您的帖子包含服务密钥和连接字符串(我编辑将其删除,但它们已经暴露),请立即轮换它们

© www.soinside.com 2019 - 2024. All rights reserved.