问题描述
我为带有缓存和连接池的简单查询创建了一个插件。当我用那个插件(功能)响应时,响应比以前慢。所以我想知道我是不是把插件弄错了。这是正确的用法还是我在某处犯了错误?
db.js
const fp = require('fastify-plugin')
const oracledb = require('oracledb');
oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
oracledb.autoCommit = true;
module.exports = fp(async function (fastify,opts) {
fastify.decorate('simpleSelectWithCache',async function (key,ttl,sql) {
let cached = await fastify.cache.get(key);
if (cached) {
console.log('Cached:',cached.item);
return cached.item;
} else {
let connection;
try {
connection = await oracledb.getConnection();
const data = await connection.execute(sql);
fastify.cache.set(key,data.rows,ttl);
console.log('Real:',data.rows);
return data.rows;
// oracledb.getPool()._logStats(); // show pool statistics. _enableStats must be true
} catch (error) {
console.error(err);
} finally {
if (connection) await connection.close();
}
}
})
})
api.js
module.exports = async function (fastify,opts) {
fastify.get(
'/cached',{
schema: {
description: 'Shared Api',tags: ['Shared'],},async function (req,reply) {
const data = await fastify.simpleSelectWithCache('shared-cached',60*1000,'SELECT id FROM users WHERE id < 50')
reply.send(data);
}
);
};
解决方法
这是正确的用法还是我在某处犯了错误?
连接是一项繁重的操作,对于每个查询,都会在您的服务器和数据库之间创建一个新连接(也称为新套接字)。
要优化您的插件,您需要在开始时创建连接池:
module.exports = fp(async function (fastify,opts) {
await oracledb.createPool({
user: opts.user,password: opts.password,connectString: opts.connectString
})
fastify.decorate('simpleSelectWithCache',async function (key,ttl,sql) {
const cached = await fastify.cache.get(key)
if (cached) {
console.log('Cached:',cached.item)
return cached.item
} else {
let connection
try {
connection = await oracledb.getConnection()
const data = await connection.execute(sql)
fastify.cache.set(key,data.rows,ttl)
console.log('Real:',data.rows)
return data.rows
// oracledb.getPool()._logStats(); // show pool statistics. _enableStats must be true
} catch (error) {
console.error(error)
} finally {
if (connection) await connection.close()
}
}
})
fastify.addHook('onClose',(instance,done) => {
oracledb.getPool().close(10)
.then(done)
.catch(done)
})
})
// then register your plugin
fastify.register(myOraclePlugin,{
user: 'ora'
password: '1234',connectString: 'foo'
})