1. 程式人生 > 資料庫 >分散式鎖之Redisson入門

分散式鎖之Redisson入門

Redisson是一個在Redis的基礎上實現的Java駐記憶體資料網格(In-Memory Data Grid)。它不僅提供了一系列的分散式的Java常用物件,還提供了許多分散式服務。其中包括(BitSet,Set,Multimap,SortedSet,Map,List,Queue,BlockingQueue,Deque,BlockingDeque,Semaphore,Lock,AtomicLong,CountDownLatch,Publish / Subscribe,Bloom filter,Remote service,Spring cache,Executor service,Live Object service,Scheduler service) Redisson提供了使用Redis的最簡單和最便捷的方法。Redisson的宗旨是促進使用者對Redis的關注分離(Separation of Concern),從而讓使用者能夠將精力更集中地放在處理業務邏輯上。

官方文件地址:https://github.com/redisson/redisson/wiki

3.3.1. 快速入門

  1. 引入依賴

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.11.2</version>
</dependency>

 

  1. 新增配置

@Configuration
public class RedissonConfig {
​
    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        // 可以用"rediss://"來啟用SSL連線
        config.useSingleServer().setAddress("redis://172.16.116.100:6379");
        return Redisson.create(config);
    }
}

 

  1. 程式碼實現

@Autowired
private RedissonClient redissonClient;
​
@Override
public void testLock() {
​
    RLock lock = this.redissonClient.getLock("lock"); // 只要鎖的名稱相同就是同一把鎖
    lock.lock(); // 加鎖
​
    // 查詢redis中的num值
    String value = this.redisTemplate.opsForValue().get("num");
    // 沒有該值return
    if (StringUtils.isBlank(value)) {
        return;
    }
    // 有值就轉成成int
    int num = Integer.parseInt(value);
    // 把redis中的num值+1
    this.redisTemplate.opsForValue().set("num",String.valueOf(++num));
​
    lock.unlock(); // 解鎖
}

 

閉鎖(CountDownLatch)演示程式碼(分散式秒殺場景使用)

public class IndexController {
	@Autowired
	private IndexService indexService;

	@GetMapping("/main")
	public String testMain() throws InterruptedException {
		return indexService.testMain();
	}

	@GetMapping("/sub")
	public String testSub() {
		return indexService.testSub();
	}

}
@Service
public class IndexService {
	@Autowired
	private RedissonClient redissonClient;

	public String testMain() throws InterruptedException {
		RCountDownLatch latch = this.redissonClient.getCountDownLatch("latch");
		latch.trySetCount(5L);

		latch.await();
		return "主業務開始執行";

	}

	public String testSub() {
		RCountDownLatch latch = this.redissonClient.getCountDownLatch("latch");
		latch.countDown();

		return "分支業務執行了一次";
	}
}