Java Distributed: Distributed lock the database implementation
Distributed Lock tutorial focuses on realization of the principle of sharing the lock
The principle lock
Creating a database table called methodLock, and add a unique constraint for the method name field (method_name).
CREATE TABLE `methodLock` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', `Method_name` varchar (64) NOT NULL DEFAULT '' COMMENT 'locking method name", `Desc` varchar (1024) NOT NULL DEFAULT 'remark information', `Update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'save time data, generated automatically', PRIMARY KEY (`id`), UNIQUE KEY `uidx_method_name` (`method_name `) USING BTREE ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'locking method';
Before each access method, perform an insert operation:
insert into methodLock(method_name,desc) values (‘method_name’,‘desc’)
Once inserted successfully, that think this thread is locked successfully, if the insert fails, while the executable statements within the maximum waiting time for trying to insert.
When the method after executing business operations, a DELETE statement that is deemed to have waived the lock, so that other thread lock contention resources.
delete from methodLock where method_name ='method_name'
Diagram
Reference material
- https://www.hollischuang.com/archives/1716
- https://blog.csdn.net/u013256816/article/details/92854794