springboot整合redisson分散式鎖(redis叢集模式)
版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/qsssyyw/article/details/81562868
1.maven引入redisson
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.5.0</version>
</dependency>
2.redisson配置類,得到redisson物件,之後的分散式鎖由redisson物件操作
2.1 在springboot的配置檔案application.yml中新增redis叢集的ip和埠還有密碼
spring:
redis:
password: 123456
clusters: 10.10.1.1:7000,10.10.1.1:7001,10.10.1.1:7002,10.10.1.1:7003,10.10.1.1:7004,10.10.1.1:7005
2.2 建立 redisson配置類RedissonManager
import java.io.IOException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* redisson配置
*/
@Configuration
public class RedissonManager {
@Value("${spring.redis.clusters}")
private String cluster;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient getRedisson(){
String[] nodes = cluster.split(",");
//redisson版本是3.5,叢集的ip前面要加上“redis://”,不然會報錯,3.2版本可不加
for(int i=0;i<nodes.length;i++){
nodes[i] = "redis://"+nodes[i];
}
RedissonClient redisson = null;
Config config = new Config();
config.useClusterServers() //這是用的叢集server
.setScanInterval(2000) //設定叢集狀態掃描時間
.addNodeAddress(nodes)
.setPassword(password);
redisson = Redisson.create(config);
//可通過列印redisson.getConfig().toJSON().toString()來檢測是否配置成功
return redisson;
}
}
3.建立分散式鎖的介面DistributedLocker
import java.util.concurrent.TimeUnit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
public interface DistributedLocker {
RLock lock(String lockKey);
RLock lock(String lockKey, long timeout);
RLock lock(String lockKey, TimeUnit unit, long timeout);
boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime);
void unlock(String lockKey);
void unlock(RLock lock);
}
4.建立介面DistributedLocker的實現類
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Component
public class RedissonDistributedLocker implements DistributedLocker {
@Autowired
private RedissonClient redissonClient; //RedissonClient已經由配置類生成,這裡自動裝配即可
//lock(), 拿不到lock就不罷休,不然執行緒就一直block
@Override
public RLock lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
return lock;
}
//leaseTime為加鎖時間,單位為秒
@Override
public RLock lock(String lockKey, long leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(leaseTime, TimeUnit.SECONDS);
return lock;
}
//timeout為加鎖時間,時間單位由unit確定
@Override
public RLock lock(String lockKey, TimeUnit unit ,long timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, unit);
return lock;
}
//tryLock(),馬上返回,拿到lock就返回true,不然返回false。
//帶時間限制的tryLock(),拿不到lock,就等一段時間,超時返回false.
@Override
public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTime, leaseTime, unit);
} catch (InterruptedException e) {
return false;
}
}
@Override
public void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
}
@Override
public void unlock(RLock lock) {
lock.unlock();
}
}
5.使用分散式鎖
@RestController
@RequestMapping("/redisson")
public class AdvMaterialController {
@Autowired
private DistributedLocker distributedLocker;
@RequestMapping("/test")
public void redissonTest() {
String key = "redisson_key";
for (int i = 0; i < 100; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.err.println("=============執行緒開啟============"+Thread.currentThread().getName());
/*distributedLocker.lock(key,10L); //直接加鎖,獲取不到鎖則一直等待獲取鎖
Thread.sleep(100); //獲得鎖之後可以進行相應的處理
System.err.println("======獲得鎖後進行相應的操作======"+Thread.currentThread().getName());
distributedLocker.unlock(key); //解鎖
System.err.println("============================="+Thread.currentThread().getName());*/
boolean isGetLock = distributedLocker.tryLock(key,TimeUnit.SECONDS,5L,10L); //嘗試獲取鎖,等待5秒,自己獲得鎖後一直不解鎖則10秒後自動解鎖
if(isGetLock){
Thread.sleep(100); //獲得鎖之後可以進行相應的處理
System.err.println("======獲得鎖後進行相應的操作======"+Thread.currentThread().getName());
//distributedLocker.unlock(key);
System.err.println("============================="+Thread.currentThread().getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
}
---------------------
作者:YLZFK
來源:CSDN
原文:https://blog.csdn.net/qsssyyw/article/details/81562868
版權宣告:本文為博主原創文章,轉載請附上博文連結!