通過Redisson實現基於redis的分散式鎖
阿新 • • 發佈:2019-01-02
除了上一篇寫的基於Jedis利用redis的setnx函式實現分散式鎖之外。redis官方推薦使用Redisson作為分散式鎖的首選。使用Redisson,不需要自己去封裝lock和unlock方法。只需引入pom檔案,加入相關呼叫方法即可。
1.pom檔案
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.3.2</version>
</dependency >
2.java程式碼呼叫
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class RedissonTest {
public static void main(String[] args) {
//Redisson連線配置檔案
Config config = new Config();
config. useSingleServer().setAddress("127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RLock yuxinLock = redisson.getLock("yuxinLock" ); // 1.獲得鎖物件例項
new RedissonTest().testM(yuxinLock);
}
public void testM(RLock yuxinLock){
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
for(int i = 0; i < 5; i++){
fixedThreadPool.execute(new Task("woker_" + i,yuxinLock));
}
}
class Task implements Runnable{
private String name;
private RLock yuxinLock;
public Task(String name,RLock yuxinLock){
this.name = name;
this.yuxinLock=yuxinLock;
System.out.println(name);
}
public void run() {
boolean res=false;
try{
System.out.println(name+"開始奪鎖大戰");
//1.不支援過期自動解鎖,不會超時
//yuxinLock.lock();
// 2. 支援過期解鎖功能,10秒鐘以後自動解鎖, 無需呼叫unlock方法手動解鎖
//lock.lock(10, TimeUnit.SECONDS);
// 3. 嘗試加鎖,最多等待20秒,上鎖以後10秒自動解鎖(實際專案中推薦這種,以防出現死鎖)
res = yuxinLock.tryLock(20, 10, TimeUnit.SECONDS);
if(res){
System.out.println(this.name + "開始工作了"+new Date());
int time = 5000;
if(time > 0){
Thread.sleep(time);
}
System.out.println(this.name + "結束工作了;" + new Date());
}else{
System.out.println(name+"等待超時");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
if(res){
yuxinLock.unlock();
}
}
}
}
}