简体   繁体   中英

Distributed lock with Hazelcast not working

I am trying to test my distributed lock implementation but I still haven't found a way to make it work. I deployed a REST service with two simple methods, like this:

@GET
@Path("/lock")
@Produces("text/*")
public String lock() throws InterruptedException {
    Lock lock = distributedService.getDistributedLock("test");
    boolean result = lock.tryLock(5, TimeUnit.SECONDS);
    return result ? "locked" : "timeout";
}

@GET
@Path("/unlock")
@Produces("text/*")
public String unlock() {
    Lock lock = distributedService.getDistributedLock("test");
    lock.unlock();
    return "unlocked";
}

The distributedService object implements the getDistributedLock() method:

@Override
public Lock getDistributedLock(String lockName) {
    return Hazelcast.getDefaultInstance().getLock(lockName);
}

In the hazelcast.xml file, I enabled TCP-IP connection and disabled everything else:

<network>
<port auto-increment="true">5701</port>
<join>
  <multicast enabled="false" />
  <tcp-ip enabled="true">
    <interface>192.168.0.01</interface>
    <interface>192.168.0.02</interface>
  </tcp-ip>
</join>
<interfaces enabled="false" />
<symmetric-encryption enabled="false" />
<asymmetric-encryption enabled="false" />

I deployed the application in the two machines, with IP adresses corresponding to the .xml file (192.168.0.01 and 192.168.0.02) and when I call the service from the browser It works for the first time (it locks and returns "locked") and everytime I call the unlock() method it returns correctly (I get the string "unlocked") but after the first time, everytime that I call the lock() method I get a timeout. It doesn't look like the unlock() method is unlocking it.

Can someone point me the correct way to use Distributed Lock with hazelcast?

Only the thread that locked can unlock it. You are saying that you have implemented REST for lock and unlock. And I guess the thread that locks and unlocks are different. That's why it is not working. Try to print the Thread name and see yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM