如果群集中的第一个节点已关闭,Redis客户端(Redission)将停止工作

时间:2016-04-20 14:50:50

标签: java caching redis distributed-caching redisson

我有一个3的Master Master redis集群(node1,node2,node3)。我正在使用Redission客户端跨JVM进行分布式锁定。现在根据Redission实现的RedLock算法,它尝试在大多数节点中获取锁(在我的情况下,2是大多数),并且它使用循环算法进行负载平衡。现在,如果我们阻塞node2或node3的网络,这个锁定机制可以正常工作。但是如果我们阻塞node1的网络,那么它会因以下错误而失败

Exception in thread "main" org.redisson.client.RedisNodeNotFoundException: No node for slot: 15087 and command (EVAL)
at org.redisson.connection.MasterSlaveConnectionManager.getEntry(MasterSlaveConnectionManager.java:578)
at org.redisson.connection.MasterSlaveConnectionManager.connectionWriteOp(MasterSlaveConnectionManager.java:563)
at org.redisson.command.CommandAsyncService.async(CommandAsyncService.java:368)
at org.redisson.command.CommandAsyncService.evalAsync(CommandAsyncService.java:334)
at org.redisson.command.CommandAsyncService.evalWriteAsync(CommandAsyncService.java:282)
at org.redisson.RedissonLock.tryLockInnerAsync(RedissonLock.java:207)
at org.redisson.RedissonLock.tryAcquire(RedissonLock.java:139)
at org.redisson.RedissonLock.tryLock(RedissonLock.java:225)
at com.seamless.common.cache.distributed.LockManager.getLock(LockManager.java:37)
at com.testlock.app.App.main(App.java:34)

以下是我创建Redission客户端的方法

    import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.redisson.ClusterServersConfig;
import org.redisson.Config;
import org.redisson.ReadMode;
import org.redisson.Redisson;
import org.redisson.RedissonClient;
import org.redisson.core.RLock;

public class LockManager {


private static final Logger LOG = Logger.getLogger(LockManager.class);


private RedissonClient redissonClient;

LockManager(List<String> nodes){
    Config config = new Config();
    ClusterServersConfig serverConfig=config.useClusterServers();
    serverConfig.setReadMode(ReadMode.MASTER);
    for(String node :nodes){
        serverConfig.addNodeAddress(node);
    }
    redissonClient = Redisson.create(config);

}

public boolean getLock(final String lockKey,int timeout){
    RLock lock=redissonClient.getLock(lockKey);
    try {
        return lock.tryLock(0, timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        LOG.error("Error getting lock "+e.getMessage());
    }
    return false;
}   

public void releaseLock(final String lockKey){
    RLock lock=redissonClient.getLock(lockKey);
    if(lock.isHeldByCurrentThread())
        lock.unlock();
}
}

1 个答案:

答案 0 :(得分:0)

您必须为RedLock算法使用RedissonRedLock和3个锁:

RLock lock1 = redisson.getLock("lock1");
RLock lock2 = redisson.getLock("lock2");
RLock lock3 = redisson.getLock("lock3");

RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();

//...

lock.unlock();