Redis implements the synchronization lock mechanism requested in a distributed system

The project uses the dubbo architecture as distributed service implementation. Because the business operation process is long and the request is divided into multiple parts, it is necessary to ensure the uniqueness of the client's request. At present, the system uses the database lock mechanism to ensure the uniqueness of the request. However, if the amount of concurrency increases, it will cause greater pressure on the database.

I have studied the registration center using zookeeper before to synchronize distributed requests, but it does not conform to the business scenario, so I can use redis's setnx to achieve the uniqueness of concurrent data.

 

the code is simple

 

 

public class RedisSyc {
  
  public static void main(String[] args) {
    Jedis jedisClient = new Jedis("127.0.0.1", 6379);
    //When grabbing the lock, you can set the value to the information of the relevant request thread, and other threads will return the business exception.
    if(jedisClient.setnx("ISLOCK", Thread.currentThread().getName()) == 1){
      //business。。。
    }else {
      throw new RuntimeException("Resource competition exception");
    }
  }
}
 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327043802&siteId=291194637