[Switch] MySQL optimistic lock practices in Distributed scenarios, mysql scenarios
Background
In the E-commerce shopping scenario, when we click shopping, the backend service will perform inventory reduction for the corresponding products. When a single instance is deployed, we can simply use the lock mechanism provided by JVM to lock the inventory reduction operation to prevent inventory inconsistency caused by multiple users clicking the purchase at the same time.
However, in practice, we usually deploy multiple instances to improve system availability. Different instances have their own JVMs. User requests that are evenly distributed to different instances cannot be mutually exclusive through the JVM lock mechanism.
Therefore, to ensure data consistency in Distributed scenarios, we generally have two practices: 1. Use MySQL optimistic locks; 2. Use distributed locks.
This article mainly introduces optimistic MySQL locks. I will introduce distributed locks in the next blog.
Introduction to optimistic locks
The Optimistic Locking corresponds to the pessimistic lock. When we use the Optimistic lock, we assume that the data does not conflict in most cases. Therefore, only when the data is submitted, checks whether data conflicts occur. If any data conflict occurs, the system returns an error message for corresponding processing.
So how can we implement optimistic locks? Generally, the following methods are used: version is used for implementation, which is the most common implementation method of optimistic locks.
Version Number
So what is the version number? The version number is used to add a version flag to the data. Generally, I will add an int type "version" field to the table in the database. When we read the data, we will read the version field together. When the data is updated, we will add 1 to the version value of the data. When submitting data, we will determine whether the current version number in the database is consistent with the version number when the data is retrieved for the first time. If the two versions are the same, the database is updated; otherwise, the database is deemed to have expired, returns an error message. We can illustrate the problem:
If the update operation is executed in the same order as in the first figure, the data version number increases sequentially without conflict. However, as shown in the second figure, if different user operations read the same version of the data and then update the data respectively, user A's update operation can be successful, when user B updates, the data version has changed, so the update fails.
Code practice
When we reduce the inventory of a product, we can perform the following three steps:
To use the optimistic MySQL lock, we need to add a version field version for the product table goods. The specific table structure is as follows:
CREATE TABLE `goods` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(64) NOT NULL DEFAULT '', `remaining_number` int(11) NOT NULL, `version` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Java code for Goods:
* Product name */private String name;/*** inventory quantity */private Integer remainingNumber;/*** version number */private Integer version; @ Override public String toString () {return "Goods {" + "id =" + id + ", name = '" + name +' \ ''+", remainingNumber = "+ remainingNumber + ", version = "+ version + '}';}}
GoodsMapper. java:
public interface GoodsMapper { Integer updateGoodCAS(Goods good);}
GoodsMapper. xml is as follows:
<update id="updateGoodCAS" parameterType="com.ztl.domain.Goods"> <![CDATA[ update goods set `name`=#{name}, remaining_number=#{remainingNumber}, version=version+1 where id=#{id} and version=#{version} ]]> </update>
GoodsService. java interface:
public interface GoodsService { @Transactional Boolean updateGoodCAS(Integer id, Integer decreaseNum);}
GoodsServiceImpl. java class:
@ Servicepublic class GoodsServiceImpl implements GoodsService {@ Autowired private GoodsMapper goodsMapper; @ Override public Boolean updateGoodCAS (Integer id, Integer decreaseNum) {Goods good = goodsMapper. selectGoodById (id); System. out. println (good); try {Thread. sleep (3000); // simulate concurrency. Different users read the same data version} catch (InterruptedException e) {e. printStackTrace ();} good. setRemainingNumber (good. getRemaini NgNumber ()-decreaseNum); int result = goodsMapper. updateGoodCAS (good); System. out. println (result = 1? "Success": "fail"); return result = 1 ;}}
GoodsServiceImplTest. java test class
@ RunWith (SpringRunner. class) @ SpringBootTestpublic class GoodsServiceImplTest {@ Autowired private GoodsService goodsService; @ Test public void updateGoodCASTest () {final Integer id = 1; Thread thread Thread = new Thread (new Runnable () {@ Override public void run () {goodsService. updateGoodCAS (id, 1); // user 1 request}); thread. start (); goodsService. updateGoodCAS (id, 2); // user 2 request System. out. println (goodsService. selectGoodById (id ));}}
Output result:
Goods {id = 1, name = 'mobile', remainingNumber = 10, version = 9} Goods {id = 1, name = 'mobile', remainingNumber = 10, version = 9} successfailGoods {id = 1, name = 'mobile', remainingNumber = 8, version = 10}
Code Description:
In the updateGoodCASTest () test method, user 1 and user 2 both find the same version of the product with id = 1, then, goods are reduced by 1 and 2 respectively. The output result shows that the inventory reduction operation of user 2 is successful, and the inventory of goods is successfully subtracted from 2. When user 1 submits the inventory reduction operation, the data version number has changed, so the data change fails.
In this way, we can use the Optimistic Locking Mechanism of MySQL to ensure data consistency in Distributed scenarios.
Above.
Original article link
Https://segmentfault.com/a/11...