无法将redis导出到express中的不同文件
Fail to export redis to different files in express
当我 npm 启动 express 服务器并转到 localhost:3000/
会有错误信息:(node:6984) UnhandledPromiseRejectionWarning: Error: The client is closed
当我将 createClient() 放入 App.js 时,redisClient 将工作,但是,我想连接到 redis 一次,并且所有文件都能够建立相同的连接
"redis": "^4.0.4"
“快递”:“^4.17.3”
App.js
const express = require('express');
const port = 3000;
const { getData} = require('./utils/data');
const app = express();
app.get('/', (req, res) => {
getData()
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
./utils/data.js
const axios = require('axios');
const redisClient = require('../controllers/redis');
const getData= async() => {
redisClient.get("getData", async(error, data) => {
if (error) console.log(error);
if (data != null) {
return res.json(JSON.parse(data));
} else {
axios.get(`http://api.com`)
.then((res) => {
redisClient.set("getLeague", JSON.stringify(res.data));
res.json(res.data);
});
}
});
};
exports.getData= getData;
./controllers/redis.js
const redis = require('redis')
const redisClient = redis.createClient()
redisClient.on('connect', function () {
console.log('redis client connected');
});
module.exports = redisClient;
这将解决并能够将客户端导入不同的模块
App.js
(async () => {
const app = express();
...
})();
redis.js
const { createClient } = require('redis');
const client= createClient();
client.connect();
module.exports = {
client
};
当我 npm 启动 express 服务器并转到 localhost:3000/
会有错误信息:(node:6984) UnhandledPromiseRejectionWarning: Error: The client is closed
当我将 createClient() 放入 App.js 时,redisClient 将工作,但是,我想连接到 redis 一次,并且所有文件都能够建立相同的连接
"redis": "^4.0.4"
“快递”:“^4.17.3”
App.js
const express = require('express');
const port = 3000;
const { getData} = require('./utils/data');
const app = express();
app.get('/', (req, res) => {
getData()
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
./utils/data.js
const axios = require('axios');
const redisClient = require('../controllers/redis');
const getData= async() => {
redisClient.get("getData", async(error, data) => {
if (error) console.log(error);
if (data != null) {
return res.json(JSON.parse(data));
} else {
axios.get(`http://api.com`)
.then((res) => {
redisClient.set("getLeague", JSON.stringify(res.data));
res.json(res.data);
});
}
});
};
exports.getData= getData;
./controllers/redis.js
const redis = require('redis')
const redisClient = redis.createClient()
redisClient.on('connect', function () {
console.log('redis client connected');
});
module.exports = redisClient;
这将解决并能够将客户端导入不同的模块
App.js
(async () => {
const app = express();
...
})();
redis.js
const { createClient } = require('redis');
const client= createClient();
client.connect();
module.exports = {
client
};