Spring consolidates curator for distributed locks

Source: Internet
Author: User
Why do we have distributed locks?

For example, we want to place orders, divided into two operations, the Order of Success (orders service), deduct Inventory (goods service). If there is no lock, two requests come in at the same time. First check there is no inventory, a look has, and then place orders, reduce inventory. There must be an error. The result we want is. Only one request can come in. When the operation is complete, the next request comes in again. This is not the phenomenon of inventory selling super. At this point, we need to use distributed locks to implement.

There are many ways to implement distributed locks. REDIS,ZK is all you can. But it is recommended ZK.

First, the general idea:

First, we get the lock first when we place the order. If successful, proceed with our business process below. After the process is finished. Release the lock. The other request, if requested, also acquires the lock first, and of course it is not, so it hangs, when someone else releases it, and then tries to acquire the lock again.

How do I get a lock?

The main use of ZK to create a node implementation, that is, the first node is not, that no one acquires a lock, and then you create this node, you get this lock. Remember, this node must be a temporary node.

Then, of course, acquiring the lock this operation is a dead loop. Controlled by a static variable Countdownlatch. If Countdownlatch is greater than 0, wait hangs, and when someone else releases, another loop continues, attempting to acquire the lock.

Let's release the lock. This node is deleted. Countdownlatch Reset to 1.

The code is empty!!!! First occupy the Pit

Spring consolidates curator for distributed locks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.