Officer:

Based on Redis Redisson distributed signal (Semaphore) Java objects RSemaphore adopted with Java. Util. Concurrent. The Semaphore similar interface and usage. It also provides Async, Reactive and RxJava2 standard interfaces.

RSemaphore semaphore = redisson.getSemaphore("semaphore");
semaphore.acquire();
/ / or
semaphore.acquireAsync();
semaphore.acquire(23);
semaphore.tryAcquire();
/ / or
semaphore.tryAcquireAsync();
semaphore.tryAcquire(23, TimeUnit.SECONDS);
/ / or
semaphore.tryAcquireAsync(23, TimeUnit.SECONDS);
semaphore.release(10);
semaphore.release();
/ / or
semaphore.releaseAsync();
Copy the code

Redisson Expiration Semaphore based on Redis permitABlesemaphore is an expiration time added to each signal on the basis of RSemaphore object. Each signal can be identified by its own ID, which can only be released by submitting the ID. It provides interfaces to Async, Reactive, and RxJava2 standards.

RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("mySemaphore");
String permitId = semaphore.acquire();
// Get a signal, valid for 2 seconds.
String permitId = semaphore.acquire(2, TimeUnit.SECONDS);
// ...
semaphore.release(permitId);
Copy the code

One: Test semaphore

Write the following code

/** * Test semaphore */
@GetMapping("/acquire")
@ResponseBody
public String acquire() throws InterruptedException {
    RSemaphore semaphore = redissonClient.getSemaphore("Semaphore-test");
    semaphore.acquire();
    System.out.println("Acquire semaphore lock, start service --");
    return "ok";
}
Copy the code
@ResponseBody
@GetMapping("/release")
public String release(){
    RSemaphore semaphore = redissonClient.getSemaphore("Semaphore-test");
    semaphore.release();
    System.out.println("Begin to release --");
    return "ok";
}
Copy the code

Set key semaphore-test to 5 in Redis in advance, as shown in the picture below:

Start the project, open your browser and start testing

It is found that when semaphore-test value is 0, acquire operation will be blocked until release is called and semaphore-test value is greater than 0, acquire operation will continue

2. TryAcquire mode

/** * Test semaphore */
@GetMapping("/acquire")
@ResponseBody
public String acquire() throws InterruptedException {
    RSemaphore semaphore = redissonClient.getSemaphore("Semaphore-test");
    boolean b = semaphore.tryAcquire();
    if(b){
        System.out.println("Acquire semaphore lock, start service --");
        return "ok";
    }
    return "ok---->"+b;
}
@ResponseBody
@GetMapping("/release")
public String release(){
    RSemaphore semaphore = redissonClient.getSemaphore("Semaphore-test");
    semaphore.release();
    System.out.println("Begin to release --");
    return "ok";
}
Copy the code

The tryAcquire method returns Boolean, which can be used to determine whether the business can be executed

Semaphore usage scenarios: Used for distributed current limiting