Contents

nodejs ioredis cluster defineCommand筆記

一開始寫法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// 一開始寫法 由ARGV帶進key name 會噴錯 ERR Script attempted to access a non local key in a cluster
const Redis = require('ioredis');
const ioredis = new Redis.Cluster([{
    port: 6379,
    host: 'localhost',
}]);

const luaScript = `
  local data = cjson.decode(ARGV[1])
  local key1 = data.key1
  local result = redis.call('SET', key1, data.value1)
  local key2 = data.key2
  local result = redis.call('SET', key2, data.value2)
`;

ioredis.defineCommand('fakeCommand', {
    numberOfKeys: 0,
    lua: luaScript,
});

const result = await ioredis.fakeCommand(JSON.strigify({key1: 'imFakeKey1', value1: 'imFakeValue1',key2: 'imFakeKey2', value2: 'imFakeValue2'}));

修正寫法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const Redis = require('ioredis');
const ioredis = new Redis.Cluster([{
    port: 6379,
    host: 'localhost',
}]);

const luaScript = `
  local data = cjson.decode(ARGV[1])
  local key1 = KEY[1]
  local result = redis.call('SET', key1, data.value1)
  local key2 = KEY[2]
  local result = redis.call('SET', key2, data.value2)
`;

ioredis.defineCommand('fakeCommand', {
    numberOfKeys: 2, // 用到多少key就要帶入多少key數量 redis cluster才能知道
    lua: luaScript,
});

const data = { key1: 'imFakeKey1', value1: 'imFakeValue1', key2: 'imFakeKey2', value2: 'imFakeValue2' };

const result = await ioredis.fakeCommand(data.key1, data.key2, JSON.stringify(data));

參考資料 https://redis.io/docs/latest/commands/eval/


Important: to ensure the correct execution of scripts, both in standalone and clustered deployments, all names of keys that a script accesses must be explicitly provided as input key arguments. The script should only access keys whose names are given as input arguments. Scripts should never access keys with programmatically-generated names or based on the contents of data structures stored in the database.

重要提示:為確保腳本在獨立部署和集群部署中正確執行,必須明確提供腳本訪問的所有鍵名稱作為輸入鍵參數。該腳本應僅訪問其名稱作為輸入參數給出的鍵。腳本絕不應訪問具有程式設計生成的名稱或基於資料庫中存儲的數據結構內容的鍵。