If I go to my site I get data from database. First Load is slow and takes 1-2 seconds. But then it is fast like 10ms. Why is the first connection slow? It is only when I use cassandra driver.
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}`)
});
Your code is connecting (creating the TCP connections) the first time:
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'
})
});
To mitigate this, you can create the connections beforehard:
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}`)
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With