简体   繁体   English

为什么要在 Next.js 中缓存 MongoDB 连接? 它有效吗?

[英]Why cache MongoDB connection in Next.js? And does it work?

I'm creating a Next.js application and I noticed that many developers cache the MongoDB connection.我正在创建一个 Next.js 应用程序,我注意到许多开发人员缓存了 MongoDB 连接。 For example例如

let cachedClient = null;
let cachedDb = null;

export async function connectToDatabase() {
    if (cachedClient && cachedDb) {
        return {
            client: cachedClient,
            db: cachedDb,
        };
    }

    const opts = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    };

    let client = new MongoClient(MONGODB_URI, opts);
    await client.connect();
    let db = client.db(MONGODB_DB);

    cachedClient = client;
    cachedDb = db;

    return {
        client: cachedClient,
        db: cachedDb,
    };
}

or或者

let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect () {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferCommands: false,
      bufferMaxEntries: 0,
      useFindAndModify: true,
      useCreateIndex: true
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

I've never seen that in Express apllications so I have 2 questions:我从未在 Express 应用程序中看到过这种情况,所以我有两个问题:

  1. Why is caching database connection such a common thing in Next.js while I've never seen that in Express.js.为什么在 Next.js 中缓存数据库连接如此普遍,而我在 Express.js 中从未见过。 What's he reason for that?他这样做的原因是什么? How does it work?它是如何工作的? And is it worth it?这值得吗?
  2. As you can see in the examples above some developer use useual let-variables while some other developer use global variables.正如您在上面的示例中看到的那样,一些开发人员使用有用的 let 变量,而其他一些开发人员使用全局变量。 What's the difference and which is the better solution?有什么区别,哪个是更好的解决方案?

In Next.Js you can cache some variables and mongo connection is one of them.在 Next.Js 中,您可以缓存一些变量,mongo 连接就是其中之一。 It will significantly improve the response time of your application because the first call to your page will make all calls to mongo to estabilish a connection and it can take more than 2 seconds just to do this, after you have this connection stabilished you can reuse in future calls to that same page (in cases of local cache) and it'll dispense those 2 seconds spent on creating connection (resulting in a WAY faster response to your user).它将显着提高应用程序的响应时间,因为对页面的第一次调用将使所有调用 mongo 以建立连接,并且这样做可能需要超过 2 秒,在您稳定此连接后,您可以重用未来对同一页面的调用(在本地缓存的情况下),它将分配花费在创建连接上的那 2 秒(从而更快地响应您的用户)。

eg:例如:

1° Request to your page:
2300ms spent to get a response //Had to establish a new connection with mongo

2° Request to your page:
230ms spent to get a response //Used cached connection

3° Request to your page:
180ms spent to get a response //Used cached connection

4° Request to your page:
210ms spent to get a response //Used cached connection
...

The difference between the global cache and "let" cache is which functions will use the same connection.全局缓存和“让”缓存之间的区别在于哪些函数将使用相同的连接。 Depending in what your application does you can use global cache and it will prevent from every function in your app create your own connection with mongo and spent that 2 seconds I've mentioned.根据您的应用程序的用途,您可以使用全局缓存,它将防止您的应用程序中的每个 function 创建您自己的与 mongo 的连接,并花费我提到的 2 秒。

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

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