我有一个主redis集群3(node1,node2,node3)。我使用Redission客户机在jvm上进行分布式锁定。现在,根据通过重新发布实现的RedLock算法,它尝试在大多数节点(在我的情况下,2是大多数)中获取锁,并使用循环算法进行负载平衡。现在,如果我们为node2或node 3阻塞网络,这种锁定机制就可以正常工作了。但是如果我们阻塞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)
下面是我如何创建重新发布客户端
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();
}
}
最佳答案
对于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();