7

要访问 DocumentDB/CosmosDB,我使用的是包Microsoft.Azure.DocumentDB.Core(v1.3.2)。我在创建和初始化DocumentClient类时注意到:

var documentClient = new DocumentClient(new Uri(endpointUrl), primaryKey);
await documentClient.OpenAsync();

向端点发出了许多请求以获取有关索引和其他信息的信息。确切地说,有 9 个 HTTP 请求发出.OpenAsync()。这使得客户端的创建和激活在性能方面成为一项非常昂贵的操作 - 最多需要一秒钟才能将所有请求带回家。

因此,为了减轻这种代价高昂的操作,我DocumentClient要做一个单例,并在应用程序的整个生命周期内保持引用。

应用程序是 Asp.Net Core MVC,这可能会将此对象的引用保留在内存中数天。

问题:可以将这个对象作为单例保持那么长时间吗?如果不是,应该采取什么策略来处理它?或者有没有办法使初始化更便宜(即不发出这些初始请求?)。

4

1 回答 1

15

We've wondered that for ourselves as well and found this:

From the docs

SDK Usage Tip #1: Use a singleton DocumentDB client for the lifetime of your application Note that each DocumentClient instance is thread-safe and performs efficient connection management and address caching when operating in Direct Mode. To allow efficient connection management and better performance by DocumentClient, it is recommended to use a single instance of DocumentClient per AppDomain for the lifetime of the application.

I suppose this is still valid now you can address CosmosDB with it as well.

于 2017-06-22T06:41:20.387 回答