簡體   English   中英

MongoDB C# 驅動程序在第一次連接初始化時很慢

[英]MongoDB C# Driver Is Slow On First Connection Initialize

我們有一個運行在 IIS 上的應用程序,使用 mongodb c# 驅動程序,(2.11.5.0 版本),當它打開與數據庫列表的新連接時,大約需要大約550 毫秒(包括)

在相同的環境和相同的機器上,我用 NodeJS 應用程序嘗試了相同的情況,它建立了連接並在62 毫秒內列出了數據庫。 我還嘗試了 python 代碼,它需要12 毫秒,包括從集合中獲取記錄。 (每次我控制這些持續時間時,我都會關閉與 mongodb 的所有連接並首先停止這些應用程序)

在我們的環境中,第一個連接初始化緩慢是問題,因為負載均衡器后面有服務器,如果沒有足夠的請求到達所有服務器並保持連接打開,即使我將空閑超時設置為更長的時間(如 20 分鍾),請求可以轉發到空閑服務器,並且 500 毫秒的額外持續時間是事務的成本。 在我們的例子中,事務響應時間應該小於 250 毫秒。

NodeJS 代碼:

const {MongoClient} = require('mongodb');
async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();
};
async function main(){
 
    const uri = "mongodb://dbUserName:dbPassword@SERVER/DBName?retryWrites=true&w=majority&ssl=false&replicaSet=replicaName&authSource=admin";
    
    console.time("listDatabaseNamesDuration");

    const client = new MongoClient(uri,{ useNewUrlParser: true, useUnifiedTopology: true});
 
    try {
    
        await client.connect();
 
        await  listDatabases(client);

        console.timeEnd("listDatabaseNamesDuration");

    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}
main();

C# 代碼:

       var credential = MongoCredential.CreateCredential(databaseName: "admin",
       username: "dbUserName",
       password: "dbPassword");
            IList<MongoServerAddress> serverList = new List<MongoServerAddress>();
            serverList.Add(new MongoServerAddress("serverName", portNumber));
            MongoClientSettings settings = new MongoClientSettings
            {
                Servers = serverList,
                ConnectionMode = ConnectionMode.ReplicaSet,
                ReplicaSetName = "replicasetName",
                Credential = credential,
                UseTls = false,
            };

            Stopwatch sw = Stopwatch.StartNew();
            MongoClient _client = new MongoClient(settings);
            _client.ListDatabaseNames();
            sw.Stop();
            output.ListDatabaseNamesDuration = sw.ElapsedMilliseconds;

首先嘗試緩存或使MongoClient成為 singleton。 如果這沒有幫助,請嘗試將 tcp 連接配置到KeepAlive ,如下所示:

var settings = new MongoClientSettings
{
    Servers = serverList,
    ReplicaSetName = "replicasetName",
    Credential = credential,
    UseTls = false,
};

settings.ClusterConfigurator =
    b => b.ConfigureTcp(
        tcp => tcp.With(
            socketConfigurator:
                (Action<Socket>)(
                    s => s.SetSocketOption(
                        SocketOptionLevel.Socket,
                        SocketOptionName.KeepAlive,
                        true))));

var client = new MongoClient(settings);

最好將MongoClient設為 singleton,因為這是 mongo 文檔中推薦的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM