ignite系列之18-Ignite 分布式锁

Ignite 事务会隐式获得分布式锁,但是有的场景可能需要显式获得锁。IgniteCacheAPI 的
lock()方法会返回 java.util.concurrent.locks.Lock 的实例,其可以获得指定键的显式分布式锁,
通过 IgniteCache.lockAll()方法,也可以在一个集合对象上获得锁。
使用代码示例:
IgniteCache<Object, Object> personCache = ignite.getOrCreateCache(cacheName);
Lock lock = personCache.lock(keyValue);
boolean acquiredLock = false;
try {
long timeout = 60;
acquiredLock = lock.tryLock(timeout, TimeUnit.SECONDS);
if(acquiredLock) {
transactionMethod(keyValue);
}else{
//重试获取锁,或者抛出异常
throw new RuntimeException("Failed to acquired lock for key=" + keyValue
+ " in " + timeout + " " + TimeUnit.SECONDS.name());
}
} catch (InterruptedException e) {
LOG.warn("Failed to acquired lock for key=" + keyValue + ",errorMsg:" + e.getMessage());
throw new RuntimeException(e);
} finally {
if(acquiredLock) {
lock.unlock();
}
}
posted @ 2024-08-08 13:19  life_start  阅读(18)  评论(0编辑  收藏  举报