为什么我的第一个查询很慢但后来很快?

why is my first query slow but then it is fast?

如果我访问我的网站,我会从数据库中获取数据。第一次加载很慢,需要 1-2 秒。但它很快就像 10 毫秒。为什么第一次连接很慢?仅当我使用cassandra驱动程序时。

const http = require('http');

require('dotenv').config();

const { Client } = require('cassandra-driver');

const express = require('express');

const app = express();

const PORT = process.env.PORT;

const routes = require('./src/routes/index');

const client = new Client({
  cloud: {
    secureConnectBundle: "secure-connect-weinf.zip",
  },
  keyspace: 'wf_db',
  credentials: {
    username: "username",
    password: "password",
  },
});

const cors = require('cors');

app.use(cors());

app.use(express.json());

app.get('/', async (req, res) => {
  await client.connect();
  const rs = await client.execute("SELECT * FROM employ_by_id;");
  console.log(rs);
  return res.json({
    message: 'Hello'
  })
});

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`Server listen on port ${PORT}`)
});

从磁盘读取总是比从内存读取慢。当您第一次查询时,Cassandra 数据库从磁盘读取,这让您的结果很慢。如果启用缓存,Cassandra 第二次从缓存的行回复,因此您可以更快地获得结果。 PS :请​​不要执行“select * from table”查询,它们是 Cassandra 中的一种反模式。

您的代码是第一次连接(创建 TCP 连接):

app.get('/', async (req, res) => {
  await client.connect(); // <- this should be avoiding in the serve path
  const rs = await client.execute("SELECT * FROM employ_by_id;");
  console.log(rs);
  return res.json({
    message: 'Hello'
  })
});

为了缓解这种情况,您可以预先创建连接:

app.get('/', async (req, res) => {
  const rs = await client.execute("SELECT * FROM employ_by_id;");
  console.log(rs);
  return res.json({
    message: 'Hello'
  })
});

const server = http.createServer(app);
client.connect(err => {
  //TODO: Handle err
  // ...
  // Now that I'm connected to my DB, I can start serving requests
  server.listen(PORT, () => {
    console.log(`Server listen on port ${PORT}`)
  });
});