Coder
Coder

Reputation: 3272

Distributed lock of Hazelcast using nodejs

I have the Hazelcast cluster server running in the 172.30.56.60, 61, 62

(i.e)

 [ 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: {} } ]

I try to implement the Hazelcast distributed locking using nodejs using the following code,

    // 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();
    });

I started the script node by node, I expected to establish the lock node by node, but instead it locks all the nodes in the same time. So it is not working as a distributed lock, so all the script started and ending in the same time (NOTE : For testing I provided 20 seconds sleep)

Please let me know, How to establish the distributed lock using node js in Hazelcast.

Upvotes: 0

Views: 402

Answers (1)

Coder
Coder

Reputation: 3272

I found the answer myself, I didn't realize the return of promise, my bad (new to 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');
    });
});

Upvotes: 1

Related Questions