MySQL database study (b) ------ MySQL in the transaction log + + lock mechanism

MySQL database locks

Database lock Classification

  • Divided by the lock granularity may be divided into a table level lock, row-level locks, page-level locking
  • Click the lock level can be divided into shared locks, exclusive lock
  • By locking manner can be divided into automatic lock, lock the display
  • Press the operation mode can be divided into DML locks, DDL locks (this type of investigation where the additions of DML statement corresponding to the lock, and the changes in the operation of this type of structure DDL lock)
  • By use can be divided into optimistic locking, pessimistic locking

Optimistic locking : always assume the best case, every time the data are to pick up other people think is not modified, it will not be locked, but when the update will determine what others during this time did not go to update the data, You can use the version number CAS mechanisms and algorithms. For multi-reading scene.
Pessimistic locks : always assume the worst case, get a time when data modification think others will, so every time she took the data will be locked, so people want to take this data will be blocked until the lock to get it (shared resources using a time to a thread, other thread is blocked, and then run out the transfer of resources to other threads). Traditional relational database inside to use a lot of this locking mechanism, such as row locks, table locks, etc., read lock, write lock, are locked before doing the first operation. Implementation of the Java synchronized and in ReentrantLock and other exclusive lock is pessimistic locking thought. Apply to write the scene.

MyISAM and InnoDB differences on aspects of the lock

The default MyISAM table-level locking is used, it does not support row-level locking
InnoDB default is to use row-level locking, and also supports table-level locking

MyISAM中

  1. When SELECT, will generate a table-level read lock, at this time if UPDATE, INSERT, DELETE will be BLOCK, into a block until the read lock is released.
  2. Similarly, when the UPDATE, INSERT, DELETE, will generate a table-level write locks, SELECT is BLOCK, into a blocked until the write lock is released.

Table manually increase the read / write lock:

LOCK TABLES table_name read|write;

Read locks: the shared locks , because when there is a SELECT operation already in progress, then a SELECT operation at this time to the same table, and the second SELECT operation is not blocked, but performs normal, this lock can be SELECT is shared by two operations, also called shared lock. However, when in the back of the first SELECT statement plus FOR UPDATE, about to turn it into a exclusive lock , so at this time if there is a SELECT operation, the operation will fall into the blocking
write lock: When there is already a write lock, At this point if more set a write lock or read, it will fall into the blocked state.

InnoDB

InnoDB uses a two-stage lock, that lock and unlock is divided into two steps: the first to be locked inside a transaction batch operation, and then when the commit, and then to add a lock to unlock unified

Since the default is automatically submitted in MySQL's InnoDB, a transaction, the transaction closed automatically submitted, you can use

SET autocommit = 0;

In InooDB in the SELECT is optimized explicitly have to add a read lock should be added to lock in share mode after the SELECT statement; InnoDB locks are supported by default row-level

In InnoDB, sql when not used in the index using a table-level locking, when used in the index using a row-level locking

Here Insert Picture Description

MySQL database deadlock

MyISAM does not support row-level locking, so MySQL in deadlock mainly talking about the InnoDB storage engine deadlock.


MySQL resolve the deadlock in two ways: by business and by setting the database

To resolve the deadlock by business logic

  • The specified lock acquisition order
  • Break large transaction into individual small transactions
  • In the same transaction, a lock as many resources and reduce the probability of deadlock
  • Establish appropriate index to the table and reduce transaction isolation level, etc.

To resolve the deadlock by setting the database

  • Timeout parameter is set based on actual business scenario innodb_lock_wait_timeout, InnoDB engine Default is 50s.
  • After initiating deadlock detection, we found a deadlock, the deadlock in the chain initiative to roll back a transaction, so that other transactions to proceed. Innodb_deadlock_detect parameter set to on, will indicate on this logic (default ON state).

"Row-level locking when it will lock the entire table?"
InnoDB row-level locking is achieved by locking the index record, if the updated column is not indexed it will lock the entire table.
Here to thank the cattle off the net, a great harvest .

MyISAM and InnoDB respective application scenarios

  1. MyISAM:
  • Frequently perform a full table count statement, MyISAM, there is a variable to hold the number of rows in the table, so soon
  • Additions and deletions to check the efficiency of the data is not high, very frequent queries
  • No transaction
  1. InnoDB:
  • Deletions change search data are quite frequent (row-level locks can be appreciated by the table level lock)
  • High reliability requirements, requiring support services

MySQL database transactions

Four characteristics of database transactions

ACID

  • Atomicity (Automic): all the operations included in the transaction either all executed or all fail rollback
  • Consistency (Consistency): Services should ensure that the state of the database from one consistent state to transition to another consistent state.
  • Isolation (Isolation): when multiple transactions concurrently executing a transaction should not affect the execution of other transactions
  • Persistent (Durability): Once a transaction is committed, he submitted to the database should be permanently stored in the database.

Affairs issues, and transaction isolation mechanism concurrent access

Transaction isolation level

  • Uncommitted Read (Read Uncommitted):

Allow dirty reads . If a transaction has been started writing data, the additional data is not allowed to simultaneously write, but allows other transactions to read the trip data.

  • Read Committed (Read Committed):

Allows unrepeatable reads , but not dirty reads. Read data transaction allows other transactions continue to access the rows of data, but write uncommitted transactions will prevent other transactions from accessing the row.

  • Repeatable Read (Repeatable Read):

Prohibited non-repeatable reads and dirty reads , but sometimes may appear phantom reads. Read data transaction would be prohibited by a write transaction (but allowing the read transaction), the write transaction to prohibit any other transactions.

  • Serialization (Serializable):

Provide strict transaction isolation . It requires serialization of the transaction, a transaction can be performed by one, rather than concurrently.

The higher the transaction isolation level, the better to ensure the integrity and consistency of the data, but the impact of concurrent operations is greater. MySQL default transaction isolation level is repeatable read.

Concurrent access problems caused by the transaction and how to avoid

  1. Update loss: two different transactions while the same data, and then in their affairs simultaneously modify the data, then the transaction will be submitted updated to submit updates to the transaction after being overwritten, the firm submitted this case to do update is overwritten, resulting in data lost updates. (MySQL all transaction isolation level on the database level can be avoided)
  2. Dirty read: A transaction reads uncommitted data transaction B, because the B roll back the transaction, resulting in inconsistent data transaction A, the results appeared Transaction A dirty read (READ-COMMITED above transaction isolation level to avoid, MySQL's InnoBD the default isolation level is REPEATABLE_READ )

Setting the isolation level:

SET SESSION TRANSACTION ISOLATION LEVEL read uncommited; 
  1. Non-repeatable read: A transaction in case he did not update the database data, query or with a different numerical results on several occasions by the operation is performed twice, because the other transaction updates the data and submit the transaction (REPEATABLE_READ transaction isolation level above avoided)
  2. Magic Reading: A transaction is read out when reading N records, transaction B increased in the course of a transaction performed in A, A read transaction time becomes N + 1 item, this situation is called magic read. (Set to SERIALIZABLE isolation level can be avoided, resulting in transaction A looks like hallucinations, like, this is the highest level of isolation)

Non-repeatable read and phantom read distinction: Magic Reading means of a structural change, for example, the Number changed; means a non-repeatable read value read is changed.


Specific summary database level to circumvent the above problems as follows:

Transaction isolation level Lost update Dirty read Non-repeatable read Magic Reading
Uncommitted Read avoid occur occur occur
Read Committed avoid avoid occur occur
Repeatable read avoid avoid avoid occur
Serialization avoid avoid avoid avoid

For performance reasons, the higher the transaction isolation level, the higher the security, the more serious the serialized execution, this will reduce the degree of concurrency of the database, it is necessary to set the transaction isolation level based on business

MySQL database in two important log module

MySQL in use, the update operation is very frequent, if every update operations are recorded according to the corresponding condition is found, then the record is updated, and then write back to the disk, then the IO costs and find a record of the cost will be very high. So, there have been logging module, that is to say, our update update operation is to write the log, at the right time will be to write disk, the log will be updated implementation of the results back to the client.

binlog (archive log)

  • bin log is a log Server layer, all engines can be used
  • binlog is logical logs recorded original logical statement assigns a new value to the data such as the uid = 1 this line "Bob", where the statement form, which is essentially that white sql statement
  • binlog is an additional write, a log file is written to a certain size will switch to the next and does not overwrite the previous log.

Binlog log file format (statement, row, mixed)

  1. binlog recorded statement format is complete SQL statement, the advantage is small log files, better performance, disadvantages are also obvious, that is, poor accuracy, encounters a SQL statement has now () function, etc. can lead to inaccurate
  2. binlog row format records the actual data of the data line changes, the advantage is that the data records are accurate, the disadvantage is that the larger the log file.
  3. mixed format binlog mixed mode of both the front

Most use a row model, because the requirements of accuracy in many cases is ranked first.

redo log (redo log)

  • redo log InnoDB engine is unique log module, physical log is recorded on a data page What changes
  • InnoDB redo log of fixed size, such as can be configured as a set of four files, each file is 1GB, then redo log can record a total of 4GB operation. Written from scratch, it is written to the end back to the beginning of the write cycle.
  • The InnoDB redo log to ensure that the database exception occurs after the restart, before submitting the records will not be lost, this ability is called crash-safe.

In the next MySQL summary will summarize some of the techniques in SQL statements, there is a high frequency point of the interview: sql query slow tuning and some other trivial knowledge

Published 10 original articles · won praise 22 · views 4895

Guess you like

Origin blog.csdn.net/bob_man/article/details/104382299