MySQL Advanced-Master-Slave Relationship of Lock+mysql (Detailed Explanation 02)

Table of contents

1. lock

1.1. Mysql lock problem

1.1.1. Lock overview

1.1.2. Lock classification

1.1.3. Mysql lock

1.2.MyISAM table lock

1.2.1. How to add table lock

1.2.2. Read lock case

1.2.3. Write lock case

1.3. InnoDB row locks support transactions

1.3.1. Introduction to row locks

1.3.2. Background knowledge

1.3.3. InnoDB's row lock mode

1.3.4. Case preparation innodb supports transactional row-level locks

1.3.5. Row Lock Basic Demonstration----Support Transaction

1.4. Pessimistic lock and optimistic lock


1. lock

1.1. Mysql lock problem

1.1.1. Lock overview

A lock is a mechanism by which a computer coordinates concurrent access to a shared resource by multiple processes or threads (to avoid contention).

In a database, data is also a resource shared by many users. How to ensure the consistency and validity of concurrent access to data is a problem that all databases must solve, and lock conflicts are also an important factor affecting the performance of concurrent access to databases. From this perspective, locks are particularly important and more complex for databases.

1.1.2. Lock classification

From the granularity of data operations:

1) Table lock: During operation, the entire table will be locked. InnoDB support after MyISAM 5.6

2) Row lock: During operation, the current operation row will be locked. InnoDB

From the type of data operation:

1) Read lock (shared lock): For the same piece of data, multiple read operations can be performed simultaneously without affecting each other.

2) Write lock (exclusive lock): Before the current operation is completed, it will block other write operations and read operations.

1.1.3. Mysql lock

Compared with other databases, the locking mechanism of MySQL is relatively simple, and its most notable feature is that different storage engines support different locking mechanisms. The following table lists the support of each storage engine for locks:

storage engine table lock row level lock
MyISAM support not support
InnoDB Support 5.6 support

The characteristics of these two MySQL locks can be roughly summarized as follows:

lock type features
table lock Prefer the MyISAM storage engine, with low overhead and fast locking; no deadlocks; large locking granularity, the highest probability of lock conflicts, and the lowest concurrency.
row level lock Prefer the InnoDB storage engine, which has high overhead and slow locking; there will be deadlocks; the locking granularity is the smallest, the probability of lock conflicts is the lowest, and the concurrency is also the highest.

It can be seen from the above characteristics that it is difficult to say which lock is better in general, but which lock is more suitable for specific application characteristics! Only from the perspective of locks: table-level locks are more suitable for query-based applications with only a small amount of data updated according to index conditions, such as Web applications; row-level locks are more suitable for a large number of concurrent updates based on index conditions and a small number of different data, and concurrent query applications, such as some online transaction processing (OLTP) systems.

1.2.MyISAM table lock

The MyISAM storage engine only supports table locks , which is the only lock type supported in the first few versions of MySQL.

1.2.1. How to add table lock

Before executing a query statement (SELECT), MyISAM will automatically add a read lock to all the tables involved , and before executing an update operation (UPDATE, DELETE, INSERT, etc.), it will automatically add a write lock to the involved tables . This process does not require User intervention, therefore, users generally do not need to explicitly lock MyISAM tables directly with the LOCK TABLE command. But we artificially lock it in order to demonstrate the effect for you.

Show table lock syntax:

加读锁 : lock table table_name read;

加写锁 : lock table table_name write;

释放锁:   unlock tables;

1.2.2. Read lock case

Prepare the environment:

create database demo_03 default charset=utf8mb4;

use demo_03;

CREATE TABLE `tb_book` (
  `id` INT(11) auto_increment,
  `name` VARCHAR(50) DEFAULT NULL,
  `publish_time` DATE DEFAULT NULL,
  `status` CHAR(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=myisam DEFAULT CHARSET=utf8 ;

INSERT INTO tb_book (id, name, publish_time, status) VALUES(NULL,'java编程思想','2088-08-01','1');
INSERT INTO tb_book (id, name, publish_time, status) VALUES(NULL,'solr编程思想','2088-08-08','0');



CREATE TABLE `tb_user` (
  `id` INT(11) auto_increment,
  `name` VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=myisam DEFAULT CHARSET=utf8 ;

INSERT INTO tb_user (id, name) VALUES(NULL,'令狐冲');
INSERT INTO tb_user (id, name) VALUES(NULL,'田伯光');

Client one:

1) Obtain the read lock of the tb_book table

lock table tb_book read;

2) Execute the query operation

select * from tb_book;

It can be executed normally and the data can be queried.  

Client two:

3) Execute the query operation

select * from tb_book;

Client one:

4) Query unlocked tables

select name from tb_user;

Because the current user has already locked other tables, only after unlocking can other tables be read.

unlock tables;
Client two: 
5) Query unlocked tables
select name from tb_user;

Unlocked tables can be queried normally;

Client one:

6) Perform the insert operation

insert into tb_book values(null,'Mysql高级','2088-01-01','1');

Execute the insert and report an error directly, because the current tb_book obtains a read lock, the update operation cannot be performed.

Client two:

7) Perform the insert operation

insert into tb_book values(null,'Mysql高级','2088-01-01','1');

 

After the lock command unlock tables is released in client 1, the inesrt statement in client 2 is executed immediately;

Read lock: It does not affect the read operations of other clients, but it will block the write operations of other clients.


1.2.3. Write lock case

Write lock (exclusive lock): Do not allow other sessions to perform arbitrary operations

Client one:

1) Obtain the write lock of the tb_book table

lock table tb_book write ;

2) Execute the query operation

select * from tb_book ;
 
  

The query operation is executed successfully;

3) Perform an update operation

update tb_book set name = 'java编程思想(第二版)' where id = 1;

The update operation is executed successfully;

Client two:

4) Execute the query operation

select * from tb_book ;

 

After the lock command unlock tables is released in client 1, the select statement in client 2 is executed immediately;

Write lock: Block any operation of other users.

Summarize

1.3. InnoDB row locks support transactions

1.3.1. Introduction to row locks

Row lock features: biased towards the InnoDB storage engine, with high overhead and slow locking; deadlocks may occur; the locking granularity is the smallest, the probability of lock conflicts is the lowest, and the degree of concurrency is also the highest.

There are two biggest differences between InnoDB and MyISAM: one is to support transactions; the other is to use row-level locks.

1.3.2. Background knowledge

What business?
       A transaction is a coherent sequence of operations in an application, all of which must complete successfully, otherwise all changes made during each operation are undone. That is, transactions are atomic, and a series of operations in a transaction either succeed or none are performed.

Transactions and their ACID properties

A transaction is a logical processing unit composed of a set of SQL statements.

Transactions have the following four characteristics, referred to as transaction ACID properties.

ACID properties meaning
Atomicity A transaction is an atomic operation unit, and its modification to data either succeeds or fails.
Consistent Data must be in a consistent state at both the start and finish of a transaction.
Isolation The database system provides a certain isolation mechanism to ensure that transactions run in an "independent" environment that is not affected by external concurrent operations.
Durable After the transaction is completed, the modification to the data is permanent.

Problems caused by concurrent transaction processing

question meaning
Lost Update When two or more transactions select the same row, the value modified by the initial transaction will be overwritten by the value modified by the subsequent transaction.
Dirty Reads When a transaction is accessing data and modifying the data, but this modification has not been submitted to the database, at this time, another transaction also accesses the data and then uses the data.
Non-repeatable reads (Non-Repeatable Reads) A transaction reads the previously read data at a certain time after reading some data, but finds that it is inconsistent with the previously read data.
Phantom Reads A transaction re-reads previously queried data according to the same query conditions, but finds that other transactions have inserted new data that meets its query conditions.

transaction isolation level

In order to solve the transaction concurrency problem mentioned above, the database provides a certain transaction isolation mechanism to solve this problem. The stricter the transaction isolation of the database, the smaller the side effects of concurrency, but the greater the price paid, because transaction isolation is essentially "serialization" of transactions to a certain extent, which is obviously contradictory to "concurrency".

There are 4 isolation levels of the database, from low to high, they are Read uncommitted, Read committed, Repeatable read, and Serializable. These four levels can solve problems such as dirty write, dirty read, non-repeatable read, and phantom read one by one.

isolation level lost update dirty read non-repeatable read Phantom reading
Read uncommitted ×
Read committed × ×
Repeatable read (default) × × ×
Serializable × × × ×

Remarks: √ means it may appear, × means it will not appear.

The default isolation level of Mysql database is Repeatable read, view method:

show variables like 'tx_isolation';

1.3.3. InnoDB's row lock mode

InnoDB implements the following two types of row locks.

  • Shared lock (S): Also known as read lock, or S lock for short, a shared lock means that multiple transactions can share a lock for the same data, and all can access the data, but they can only read and cannot be modified.

    When you execute select, innodb will add a shared lock to the database by default

  • Exclusive lock (X): Also known as write lock, X lock for short, exclusive lock cannot coexist with other locks. For example, if a transaction acquires an exclusive lock on a data row, other transactions can no longer acquire other locks on the row, including Shared locks and exclusive locks, but transactions that acquire exclusive locks can read and modify data.

    When performing a modification operation, by default InnoDB will add an exclusive lock to the corresponding row in the database table

For UPDATE, DELETE and INSERT statements, InnoDB will automatically add an exclusive lock (X) to the involved data set;

For ordinary SELECT statements, InnoDB does not add any locks;


1.3.4. Case preparation innodb supports transactional row-level locks

create table test_innodb_lock(
	id int(11),
	name varchar(16),
	sex varchar(1)
)engine = innodb default charset=utf8;

insert into test_innodb_lock values(1,'100','1');
insert into test_innodb_lock values(3,'3','1');
insert into test_innodb_lock values(4,'400','0');
insert into test_innodb_lock values(5,'500','1');
insert into test_innodb_lock values(6,'600','0');
insert into test_innodb_lock values(7,'700','0');
insert into test_innodb_lock values(8,'800','1');
insert into test_innodb_lock values(9,'900','1');
insert into test_innodb_lock values(1,'200','0');

create index idx_test_innodb_lock_id on test_innodb_lock(id);
create index idx_test_innodb_lock_name on test_innodb_lock(name);

1.3.5. Row Lock Basic Demonstration----Support Transaction

SESSION-1 SESSION-2

Turn off autocommit

Turn off autocommit

All data can be queried normally

All data can be queried normally

Query data with id 3

Get the data with id 3

Update the data with id 3, but do not submit;

Update the data with id 3, in waiting state

Submit the transaction through commit

Unblocking, the update proceeds normally  

Above, the data of the same row is operated, and then, the data of different rows is demonstrated:

Since it is not the same row as the Session-1 operation, acquire the current row lock and perform the update;
Update the data whose id is 3, obtain the row lock normally, and execute the update;

row level:

Divided into: Shared lock: This lock will be added automatically when the select is executed. Does not affect other operations.

Exclusive lock: This lock is automatically added when an update operation is performed. Update operations that affect other transactions


1.4. Pessimistic lock and optimistic lock

  • Optimistic locking: Every time you go to get the data, you think that others will not modify it, so it will not be locked, but when you submit the update, you will judge whether others have updated the data during this period.
  • Pessimistic locking: Every time you go to get the data, you think that others will modify it, so every time you get the data, you will lock it, so that others will stop if they want to get the data until the lock is released.
  • The optimistic lock of the database needs to be implemented by yourself. Add a version field in the table, and add 1 to the successful value of each modification, so that each time you modify it, first compare whether the version you own is consistent with the current version of the database. Modify, so that optimistic locking is implemented.

Guess you like

Origin blog.csdn.net/WQGuang/article/details/132219911