【问题标题】:Dynamic arguments for ZINTERSTORE with node_redis带有 node_redis 的 ZINTERSTORE 的动态参数
【发布时间】:2013-06-13 13:07:12
【问题描述】:

我正在尝试使用 node_redis 从 node.js 使用 redis 的 ZINTERSTORE 命令:

//node.js server code
var redis = require("redis");
var client = redis.createClient();

// ... omitted code ...

exports.searchImages = function(tags, page, callback){

  //tags = ["red", "round"]

  client.ZINTERSTORE("tmp", tags.length, tags.join(' '), function(err, replies){

    //do something

  });
}

但是调用client.ZINTERSTORE会抛出错误:[Error: ERR syntax error]。将标签作为数组传递(而不是使用 tags.join(' '))会引发相同的错误。

在哪里可以找到此命令的正确语法? node_redis 的源代码已将其隐藏在 javascript 解析器中,但如果不“单步执行”代码,则很难看到发生了什么。有没有用 node.js 进行单步调试的好方法?

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    有多种方法可以使用 node.js 调试 Redis 客户端。

    首先,您可以依靠 Redis 监控功能来记录 Redis 服务器收到的每条命令:

    > src/redis-cli monitor
    OK
    1371134499.182304 [0 172.16.222.72:51510] "info"
    1371134499.185190 [0 172.16.222.72:51510] "zinterstore" "tmp" "2" "red,round"
    

    可以看到Redis收到的zinterstore命令格式不正确。

    然后,您可以通过在脚本中添加以下行来激活 node_redis 的调试模式:

    redis.debug_mode = true;
    

    它会在运行时输出Redis协议:

    Sending offline command: zinterstore
    send ncegcolnx243:6379 id 1: *4
    $11
    zinterstore
    $3
    tmp
    $1
    2
    $9
    red,round
    
    send_command buffered_writes: 0  should_buffer: false
    net read ncegcolnx243:6379 id 1: -ERR syntax error
    

    然后,您可以使用node.js debugger。通过以下方式在代码中放置调试器断点:

    function search(tags, page, callback) {
      debugger;    // breakpoint is here
      client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
        console.log(err);
        console.log(replies);
        callback('ok')
      });
    }
    

    然后您可以在调试模式下使用节点启动脚本:

    $ node debug test.js
    < debugger listening on port 5858
    connecting... ok
    break in D:\Data\NodeTest\test.js:1
      1 var redis = require("redis");
      2 var client = redis.createClient( 6379, "ncegcolnx243" );
      3
    debug> help
    Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
    watch, unwatch, watchers, repl, restart, kill, list, scripts, breakOnException, breakpoints, version
    
    debug> cont
    break in D:\Data\NodeTest\test.js:8
      6 function search(tags, page, callback) {
      7
      8   debugger;
      9   client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
     10     console.log(err);
    
    ... use n(ext) and s(tep) commands ...
    

    通过单步执行代码,您会发现命令数组不正确,因为标签被序列化并作为唯一参数处理。

    如下修改代码即可解决问题:

    var cmd = [ "tmp", tags.length ];
    client.zinterstore( cmd.concat(tags), function(err, replies) {
        ...
    });
    

    【讨论】:

    • 最后一个代码 sn-p 是我试错的。调试的详细描述非常有价值。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2018-07-31
    • 2023-03-18
    • 2019-05-04
    • 2013-02-28
    相关资源
    最近更新 更多