使用nodejs

时间:2017-11-21 13:40:54

标签: node.js locking hazelcast distributed-system distributed-cache

我在172.30.56.60,61,62

中运行Hazelcast集群服务器

(的

 [ Member {
    address: Address { host: '172.30.56.60', port: 5701, type: 4 },
    uuid: 'bd6428f0-e888-453f-872f-6fe8296d751d',
    isLiteMember: false,
    attributes: {} },
  Member {
    address: Address { host: '172.30.56.61', port: 5701, type: 4 },
    uuid: 'e0cd795a-0ca5-41ab-907a-492b61690a18',
    isLiteMember: false,
    attributes: {} },
  Member {
    address: Address { host: '172.30.56.62', port: 5701, type: 4 },
    uuid: '0a834ae8-e707-4b5b-945b-362bfea08cf5',
    isLiteMember: false,
    attributes: {} } ]

我尝试使用 nodejs 使用以下代码实现Hazelcast分布式锁定,

    // Initialize the hazelcast client instance.
var HazelcastClient = require('hazelcast-client').Client;
var Config = require('hazelcast-client').Config; 
var config = new Config.ClientConfig();
config.networkConfig.addresses = [{host: '172.30.56.60', port: '5701'},{host: '172.30.56.61', port: '5701'}, {host: '172.30.56.62', port: '5701'}]; 
var lock = {};
var sleep = require('sleep');
HazelcastClient
    .newHazelcastClient(config)       
    .then(function (hazelcastClient) {  
        lock = hazelcastClient.getLock("lock1");
         // do stuff with lock
    lock.lock();
    console.log('Am locked in node with lock1...will be locked for 20 seconds');
    sleep.sleep(20);
    console.log('Unlocked now...');
    lock.unlock();
    process.exit();
    });

我逐节点地启动了脚本,我希望按节点建立锁定节点,但是它会同时锁定所有节点。因此它不能作为分布式锁,所以所有脚本都在同一时间开始和结束(注意:对于测试我提供了20秒的睡眠时间)

请告诉我,如何在Hazelcast中使用节点js建立分布式锁。

1 个答案:

答案 0 :(得分:0)

我自己找到了答案,我没有意识到承诺的回归,我的不好(对nodejs来说是新的)

  // Initialize the hazelcast client instance.
var HazelcastClient = require('hazelcast-client').Client;
var Config = require('hazelcast-client').Config; 
var config = new Config.ClientConfig();
config.networkConfig.addresses = [{host: '172.30.56.60', port: '5701'},{host: '172.30.56.61', port: '5701'}, {host: '172.30.56.62', port: '5701'}]; 



var sleep = require('sleep');
// Test process
HazelcastClient
    .newHazelcastClient(config)       
    .then(function (hazelcastClient) {  
        var lock = hazelcastClient.getLock('rowId_tablename');
         // lock the code here
    lock.lock().then(function() { 
        console.log('Am locked in node with lock3...will be locked for 20 seconds');
        sleep.sleep(20);
        // unlock after process
        return lock.unlock();
    }).then(function() { 
        console.log('unlocked now');
    });
});