redis的全新功能,我找不到我做错事情的答案。
我正在使用redis将一些基本分析信息存储为中间件:
module.exports = function (req, res, next) {
if (req.path !== '/login') {
const route = req.path
const ip = req.ip
const userId = req.userId
const timestamp = new Date()
client.hmset('HashKey', {
'route': route,
'ipAddress': ip,
'userId': userId,
'timestamp': timestamp
})
}
console.log(client.hgetall('Hashkey') + ' || Hashkey')
client.hgetall('Hashkey', function (err, results) {
if (err) {
return err
} else {
console.log(results + ' || Parsed Hashkey')
}
})
next()
}
console.log(client.hgetall('Hashkey') + ' || Hashkey')
返回true,这应表明数据库中存在一个对象。但是console.log(results + ' || Parsed Hashkey')
返回null。
我在这里想念东西吗?
编辑: 这是初始化代码:
const redis = require('redis')
const client = redis.createClient({
port: 6379
})
答案 0 :(得分:1)
redis库异步调用数据库。因此,该命令console.log(client.hgetall('Hashkey') + ' || Hashkey')
不可能知道数据库中存在的对象,因为console.log语句是在返回数据之前执行的。
因此很可能您的results
为null,因为您的数据库中还没有'HashKey'对象。
答案 1 :(得分:0)
hmset
通常采用数组的参数,例如
client.hmset(["key", "test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
或
client.hmset("key", ["test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
或
client.hmset("key", "test keys 1", "test val 1", "test keys 2", "test val 2", function (err, res) {});
针对您的具体情况,使用此
const redis = require('redis')
const client = redis.createClient({
port:6379,
host:'localhost',
db:1
});
const payload = {
'route': 'my rrroute',
'ipAddress': '127.0.0.1',
'userId': 'asnim',
'timestamp': new Date()
};
const redisValues = Object.keys(payload).reduce((accumulator, key) => {
accumulator.push(key);
accumulator.push(payload[key]);
return accumulator;
}, []);
client.hmset("Hashkey",redisValues, function (err, res) {});
client.hgetall('Hashkey', function (err, results) {
if (err) {
return err
} else {
console.dir(results)
}
})
client.quit()
输出
{ route: 'my rrroute',
ipAddress: '127.0.0.1',
userId: 'asnim',
timestamp: 'Wed Aug 21 2019 02:22:21 GMT+0530 (India Standard Time)' }