首先在pom.xml文件中添加如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.8.2</version>
<optional>true</optional>
</dependency>
然後就是Redission的配置,沒有什麼特別的地方:
@Configuration
public class RedisConfig {
@Bean(destroyMethod = "shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}
}
Redission的配置比較簡單,配置一個RedissonClient就可以了,默認的配置支持redis的所有實現方式,集羣,單節點,哨兵,副本等都可以進行配置,這裏需要注意的是配置的線程模型,默認配置的線程是64個。
Redission實現分佈式鎖示例代碼如下所示:支持常用的讀寫鎖,信號量,紅鎖,閉鎖
@Repository
public class RedisDaoImpl {
@Autowired
private RedissonClient redissonClient;
public String getString(String key) {
RBucket<Object> result = this.redissonClient.getBucket(key);
return result.get().toString();
}
public void setString(String key, Object value) {
RBucket<Object> result = this.redissonClient.getBucket(key);
if (!result.isExists()) {
result.set(value, 5, TimeUnit.MINUTES);
}
}
public boolean hasString(String key) {
RBucket<Object> result = this.redissonClient.getBucket(key);
if (result.isExists()) {
return true;
} else {
return false;
}
}
public long incr(String key, long delta) {
return this.redissonClient.getAtomicLong(key).addAndGet(delta);
}
public void lock() {
RCountDownLatch countDown = redissonClient.getCountDownLatch("test");
countDown.trySetCount(1);
try {
countDown.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
RCountDownLatch latch = redissonClient.getCountDownLatch("testCountDownLatchName");
latch.countDown();
RReadWriteLock rwlock = redissonClient.getReadWriteLock("ReadWriteLockName");
// 加讀鎖需要手動解鎖
rwlock.readLock().lock();
rwlock.readLock().unlock();
// 加寫鎖需要手動解鎖
rwlock.writeLock().lock();
rwlock.writeLock().unlock();
// 加讀鎖,上鎖後1秒自動解鎖
rwlock.readLock().lock(1, TimeUnit.SECONDS);
// 加寫鎖,上鎖後1秒自動解鎖
rwlock.writeLock().lock(1, TimeUnit.SECONDS);
try {
// 嘗試加鎖,最多等待100秒,上鎖以後5秒自動解鎖
boolean resRead = rwlock.readLock().tryLock(100, 5, TimeUnit.SECONDS);
boolean resWrite = rwlock.writeLock().tryLock(100, 5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 紅鎖
RLock redlock1 = redissonInstance1.getLock("redlock1");
RLock redlock2 = redissonInstance2.getLock("redlock2");
RLock redlock3 = redissonInstance3.getLock("redlock3");
RedissonRedLock redissionRedlock = new RedissonRedLock(redlock1, redlock2, redlock3);
// 同時加鎖:redlock1 redlock2 redlock3
// 注意:紅鎖在大部分節點上加鎖成功就算成功。
redissionRedlock.lock();
redissionRedlock.unlock();
}
}