简体   繁体   English

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

[英]Unable to Connect from Azure Function to Azure Cosmos DB. Getting "Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object

Got a.Net code from Udemy course and ran in my local.从 Udemy 课程中获得了一个 .Net 代码并在我的本地运行。 Wrote an Azure Function which connects to Azure Cosmos DB and creates an item.写了一个 Azure Function 连接到 Azure Cosmos DB 并创建一个项目。 But not getting connected to Azure Cosmos DB.但没有连接到 Azure Cosmos DB。 See below the code and error.请参阅下面的代码和错误。 Appreciate any help.感谢任何帮助。 In the debug, found out some issue with the line在调试中,发现线路有问题

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


Code :

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.*

This was fixed in SDK 3.20: https://github.com/Azure/azure-cosmos-do.net-v3/blob/master/changelog.md#-3200---2021-06-21这已在 SDK 3.20 中修复: https://github.com/Azure/azure-cosmos-do.net-v3/blob/master/changelog.md#-3200---2021-06-21

更改日志条目的屏幕截图

Please upgrade to the recommended version to get this and other fixes.请升级到推荐版本以获得此修复和其他修复。

More fixes更多修复

You are creating a client (both Blob and Cosmos) per Function execution, that goes against the recommendations and will bring problems as the number of queue messages increase, please follow https://learn.microsoft.com/azure/azure-functions/manage-connections?tabs=csharp#static-clients and use Singleton/static instances.您正在为每个 Function 执行创建一个客户端(包括 Blob 和 Cosmos),这违反了建议,并且随着队列消息数量的增加会带来问题,请遵循https://learn.microsoft.com/azure/azure-functions/ manage-connections?tabs=csharp#static-clients并使用 Singleton/static 实例。 We have a complete example on how to use DI and Functions with the CosmosClient at https://github.com/Azure/azure-cosmos-do.net-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/AzureFunctions .我们在https://github.com/Azure/azure-cosmos-do.net-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/有一个关于如何在 CosmosClient 中使用 DI 和函数的完整示例Azure 函数

Also, do not block threads, since your Function is already async, do await _container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName)) instead.另外,不要阻塞线程,因为您的 Function 已经是异步的,请await _container.CreateItemAsync(_blobdetails, new PartitionKey(_message.VideoName))

These 2 points is what will generate these Service Unavailable errors in most cases.在大多数情况下,这两点会产生这些服务不可用错误。

ALSO VERY IMPORTANT, YOUR POST CONTAINED SERVICE KEYS AND CONNECTIONSTRINGS (I EDITED TO REMOVE THEM BUT THEY WERE ALREADY EXPOSED), ROTATE THEM IMMEDIATELY同样非常重要的是,您的帖子包含服务密钥和连接字符串(我编辑删除它们但它们已经暴露),立即旋转它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM