nodejs redis执行lua脚本

const Redis = require("ioredis");
const redis = new Redis({
    port: 6300, // Redis port
    host: '192.168.50.111', // Redis host
    password: '123',
    db: 0,
});

 1.第一种执行lua脚本的方式

const result3 = redis.eval(`return redis.call('MSET', KEYS[1],ARGV[1], KEYS[2],ARGV[2])`, 2, ['testKey1', 'testKey2', 'val1', 'val2'])
async function eval() {
    let str = await result3;
    console.log(str)
    // await redis.evalTest('testKey1', 'testKey2', 'val1', 'val2');
    const result = await redis.get('testKey1');
    const result2 = await redis.get('testKey2');
    console.log(result, result2); 
}
eval()
执行结果

 

 参照: https://www.runoob.com/redis/scripting-eval.html

 

 参照文档可知道: keys全部写在前面,中间2是key的数量,val值后面排着写

  


2.第二种执行Lua方式

const luaScript = `return redis.call('MSET', KEYS[1],ARGV[1], KEYS[2],ARGV[2])`;

redis.defineCommand("evalTest", {
    numberOfKeys: 2,
    lua: luaScript,
})
async function eval() {
    await redis.evalTest('testKey1', 'testKey2', 'val1', 'val2');
    const result = await redis.get('testKey1');
    const result2 = await redis.get('testKey2');
    console.log(result, result2); // val2
}
eval();
执行结果

 

 

  

posted @ 2021-01-19 11:10  江山一族  阅读(765)  评论(0编辑  收藏  举报