[Springboot] use redisson distributed lock

Redisson is a highly high-performance, more convenient and comprehensive middleware component based on redis. This article records the use of redisson distributed locks. The distributed lock implemented using redis was introduced before: the distributed lock is implemented based on single node redis .

Under normal circumstances, redis is deployed in a cluster (master-slave, sentinel, cluster is not distinguished here), in the cluster through setnx, del operations need to consider more issues (such as high concurrency redis cluster data synchronization problem, cluster down Problems, etc.), the correct handling of the security and activity of the lock requires more complex operations, and redisson can easily handle all of this.
Let's use redisson to test the effect of distributed locks and introduce pom dependency:

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

This article uses springboot2 to initialize the redisson instance:

@Data
@Configuration
@ConfigurationProperties
(prefix = "spring.redisson")
public class RedissonConfig {
   
private String host;
   private
String password;
   private int
connectTimeout;
   
@Bean
   
public RedissonClient redissonClient(){
       
Config config = new Config();
       
config.setTransportMode(TransportMode.NIO);

       config.useSingleServer().setAddress(host)

        .setPassword(password).setConnectTimeout(connectTimeout);
       return

       return Redisson.create(config);
   
}
}

The relevant yml attributes are as follows (abbreviated configuration):

spring:
 
redisson:
   host:
redis://127.0.0.1:6379
   password: redis5
   connection-timeout: 5000

Finally, the test verifies the case based on the single-point redis distributed lock:

@GetMapping("hello")
public String hello() {
   
CountDownLatch latch = new CountDownLatch(1000);
   
RLock lock = redissonClient.getLock(KEY);
   for
(int i = 0; i < 1000; i++) {
       
new Thread(() -> {
           
boolean res = false;
           try
{
               
res = lock.tryLock(100, 10, TimeUnit.SECONDS);
               if
(res){
                   
amount--;
               
}
           
}finally{
               
lock.unlock();
           
}
           
latch.countDown();
       
}).start();
   
}
   
latch.await();
   
return "amount:" + amount;
}

Multiple test data is correct, and the request processing efficiency is more efficient than the previous single-point redis distributed lock, with less coding and simpler operation. The power of redisson goes far beyond distributed locks, but also includes distributed collections, distributed objects, data sharding, etc. For related documentation, please refer to:

redisson wiki

https://github.com/redisson/redisson/wiki


Guess you like

Origin blog.51cto.com/15060464/2638270