gpt4 book ai didi

node.js - 为什么我的第一个查询很慢但很快?

转载 作者:行者123 更新时间:2023-12-04 01:02:23 24 4
gpt4 key购买 nike

如果我去我的网站,我会从数据库中获取数据。第一次加载很慢,需要 1-2 秒。但是它很快就像10ms。为什么第一次连接很慢?只有当我使用 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}`)
});

最佳答案

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

关于node.js - 为什么我的第一个查询很慢但很快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67865016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com