client.get("ping", (err, data) => 在 redis 中挂起我的节点 js 代码
client.get("ping", (err, data) => in redis hangs my node js code
这是我对路由的服务器调用
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
这是我的API路线
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
这是我的缓存路由函数
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
这是我的API呼叫代码
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
当它调用中间函数时,它在 clinet.get()
之后挂起我的代码
使用此代码连接redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});
我得到了答案,我正在回拨但忘记添加 await ,
所以这是更新的中间件代码
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};
这是我对路由的服务器调用
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
这是我的API路线
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
这是我的缓存路由函数
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
这是我的API呼叫代码
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
当它调用中间函数时,它在 clinet.get()
之后挂起我的代码使用此代码连接redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});
我得到了答案,我正在回拨但忘记添加 await , 所以这是更新的中间件代码
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};