zoukankan      html  css  js  c++  java
  • MySQL Lock--MySQL加锁规则

    =====================================================================

    淘宝林晓斌总结

    在可重复读事务隔离级别下,加锁规则如下:
    原则1、加锁的基本单位是Next-Key Lock(前开后闭区间)。
    原则2、查找数据过程中访问过得对象才会被加锁。
    优化1、对唯一索引做等值查询,对匹配的索引记录加锁时,Next-Key Lock会退化为Row Lock。 优化2、在索引上做等值查询,从第一个满足等值查询条件的索引记录开始向右遍历记录到第一个不满足等值条件记录时,将第一个不满足等值条件记录上的Next-Key Lock退化为间隙锁。
    Bug1、在对唯一索引做范围扫描时,会对满足条件的最后一条记录的下一行加Next-Key Lock。

    学习整理:

    在可重复读事务隔离级别下,整理加锁规则如下:
    A)对唯一索引做等值查询:
    1、如果找到到满足条件的记录,则对该记录加行锁。
    2、如果未找到满足条件的记录,则对该值前后两条记录之间间隙加间隙锁。
    
    B)对非唯一索引做等值查询:
    1、对满足条件的记录加Next-key锁。
    2、从左向右扫描满足条件的记录,当遇到第一条不满足条件记录时,对该记录之前间隙加间隙锁(Cap Lock)。
    
    C)做范围扫描:
    1、对满足条件的记录加Next-key锁。
    2、从左向右扫描满足条件的记录,当遇到第一条不满足条件记录时,对该记录和该记录之前的间隙加锁(Next-Key Lock)。
    
    D)只对扫描到的数据加锁:
    1、当使用覆盖索引+LOCK IN SHARE MODE时,不会对聚集索引记录加锁。
    2、当满足条件数据超过LIMIT限制时,不会对所有满足条件记录加锁。

    Insert操作加锁规则

    1、INSERT操作会对新插入的记录加行锁(ROW LOCK)+排他锁(X LOCK),不会产生任何GAP锁和Next-Key锁
    2、在插入记录前,会向插入记录所在位置申请意向插入Gap锁(Insertion Intention Gap Lock),相同区间的意向插入Gap锁不会冲突。
    3、对于唯一索引,如果插入记录时表中已存在相同键值记录(被其他事务修改且未提交),即存在唯一键冲突,会尝试在已有记录上加读锁,然后等待。

    官方文档:

    INSERT sets an exclusive lock on the inserted row. This lock is an index-record lock, not a next-key lock (that is, there is no gap lock) and does not prevent other sessions from inserting into the gap before the inserted row.
    Prior to inserting the row, a type of gap lock called an insert intention gap lock is set. This lock signals the intent to insert in such a way that multiple transactions inserting into the same index gap need not wait for each other if they are not inserting at the same position within the gap. Suppose that there are index records with values of 4 and 7. Separate transactions that attempt to insert values of 5 and 6 each lock the gap between 4 and 7 with insert intention locks prior to obtaining the exclusive lock on the inserted row, but do not block each other because the rows are nonconflicting.
    If a duplicate-key error occurs, a shared lock on the duplicate index record is set. This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclusive lock.
  • 相关阅读:
    Centos 7.6搭建Skywalking6.5+es6.2.4
    Skywalking入门介绍,skywalking6.5.0 +mysql (windows) 搭建
    使用springcloud gateway搭建网关(分流,限流,熔断)
    Elastalert
    Docker 部署ELK之Sentinl日志报警
    Docker 部署ELK
    基于sentry的前端错误监控日志系统(部署sentry服务器/前端项目部署)-让前端最快的定位到生产问题
    sentry之二:sentry配置钉钉和email
    sentry之一:sentry安装
    全链路追踪技术选型:pinpoint vs skywalking
  • 原文地址:https://www.cnblogs.com/gaogao67/p/10411948.html
Copyright © 2011-2022 走看看