【问题标题】:why is my first query slow but then it is fast?为什么我的第一个查询很慢但是很快?
【发布时间】:2021-08-24 03:33:09
【问题描述】:

如果我访问我的站点,我会从数据库中获取数据。第一次加载很慢,需要 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}`)
});

【问题讨论】:

  • 我猜你最初看到的是启动时间,然后是缓存的行为?

标签: node.js cassandra


【解决方案1】:

您的代码正在第一次连接(创建 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}`)
  });
});

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 但我认为 cassandra 的读写速度很快。 1 Row 如何花费 1 秒?在 postgresql 中,您可以在 1 秒内获得 1-200 万行
    • 如果您使用分区键进行查询,那么它会很快。但是您在没有分区键的情况下进行查询,因此速度很慢。如果您有数百万条数据并发出此查询,则可能会出现超时异常。 Cassandra 需要知道数据在哪里,如果给出了分区键,那么 Cassandra 很容易查询正确的节点并获得结果。如果没有分区键数据,则需要在每个节点中检查。我没有使用 postgresql 的经验,因此无法对此发表评论。
    • 感谢您的回答,如何查询分区键?
    • SELECT * FROMemploy_by_id where key='ABC';这里的键是你在表模式中定义的分区键。
    • 感谢它的工作和速度,但请告诉我一件事。我怎样才能得到这个值? [ 行 { car​​_make: '宝马' } ]
    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2018-12-30
    • 2022-12-13
    • 2019-09-07
    相关资源
    最近更新 更多