在node js中使用redis的rpush()和lrange()函数的问题

koaltpgm  于 8个月前  发布在  Redis
关注(0)|答案(1)|浏览(86)

我使用rpush方法将列表存储在redis中,并使用lrange从redis中获取列表元素。在node js中,我得到了一个错误,rpush和lrange不起作用。
因此,我根据redis节点文档使用RPUSH和LRANGE函数。应用程序运行正常,但两个功能都没有出错。RPUSH functiom正在设置Redis中的列表项,因为我可以在Redis中看到它们,但是这个函数并没有给予我任何保存数据的响应,我在控制台中写“Hello from inside RPUSH”,它没有在控制台中打印它(函数没有触发器),但是数据在列表中推送。LRANGE函数不能获取列表项,但是我可以通过redio-tool查看列表项,这里是代码,当然可以!下面是你的代码,缩进4个空格,以便发布在Stack Overflow上:

const redis = require('redis');
const client = redis.createClient({
    host: '127.0.0.1',
    port: 6379
});

client.on('error', err => console.log('Redis Client Error', err));

// Pushing data into the list using rpush
client.rpush("mylist2", "Hello3", (error, reply) => {
    console.log("Hello from inside client .rpush");
    if (error) {
        console.error('Error pushing data:', error);
    } else {
        console.log('Pushed data:', reply);

        // Once data is pushed, perform lRange operation
        performLRANGE();
    }
});

performLRANGE();

function performLRANGE() {
    // Replace 'mylist' with your actual list key
    const listKey = 'mylist2';
    const startIndex = 0;
    const endIndex = -1; // -1 retrieves all elements

    console.log("Hello from inside performLrange function");
    // Using the lrange command
    client.lrange(listKey, startIndex, endIndex, (error, result) => {
        console.log("Hello from inside LRANGE");
        if (error) {
            console.error('Error:', error);
        } else {
            console.log('Elements in the list:', result);
        }

        // Close the Redis connection
        client.quit();
    });
}

任何人谁可以帮助我解决这个问题。我感谢你的帮助,以解决这个问题。谢谢你的时间

dohp0rv5

dohp0rv51#

Node-Redis 4以后使用promise而不是回调。这是Node-Redis 4版本中的一个突破性变化,但使您的代码更容易理解。
这里有一个例子,展示了你的代码被重构为使用Node-Redis/await,我也把它变成了一个模块,这样你就可以使用顶级的Node-Redis/await和导入,但是在使用Node-Redis 4时,这些都不是必需的。
package.json:

{
  "name": "solistnode",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "dependencies": {
    "redis": "^4.6.7"
  }
}

index.js:

import { createClient } from 'redis';

const client = createClient({
  host: '127.0.0.1',
  port: 6379
});

// Connect to Redis...
await client.connect();

try {
  // Pushing data into the list using rpush - use await...
  const rpushResponse = client.rPush('mylist2', 'hello3');
  console.log('Pushed data.');

  const lrangeResponse = await client.lRange('mylist2', 0, -1);
  console.log('Data from the list:');
  console.log(lrangeResponse);
} catch (e) {
  console.log('Error working with Redis list:');
  console.log(e);
}

await client.disconnect();

节点版本:

$ node --version
v18.14.2

运行代码几次:

$ node index.js
Pushed data.
Data from the list:
[ 'hello3' ]
$ node index.js
Pushed data.
Data from the list:
[ 'hello3', 'hello3' ]
$ node index.js
Pushed data.
Data from the list:
[ 'hello3', 'hello3', 'hello3' ]

如果你仍然需要从Node-Redis 4使用旧的Node-Redis 3接口,请查看迁移和遗留模式文档:https://github.com/redis/node-redis/blob/master/docs/v3-to-v4.md

相关问题