数据库-事务-乐观锁-调优

关系型数据库

基于关系代数理论

缺点:表结构不直观,实现复杂,速度慢
优点:健壮性高,社区庞大

示例:
    product表
            productId    productName    categoryId    price
        1    4            toyota        2            100000
        2    3            porsche        2            1000000
        3    2            addidas        1            500
        4    1            nike        null        600

    category
            categoryId    categoryName
        1    2            automobile
        2    1             shoe


    select * from 'product' join 'category'    没有条件会发生笛卡尔积

    select * from 'product'    p join 'category' c 
    on p.'categoryId' = c.'categoryId'

    左外连接,左表都有,
    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'

    右外连接
    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'

    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'
    group by p.'categoryId'

    select * from 'producet' p left join (
        select p.'categoryId', 'categoryName', MIN(p.'price') as min_price from 'product' p left join 'category' c
        on p.'categoryId' = c.'categoryId'
        group by p.'categoryId','categoryName') as cat_min
    on p.'categoryId' = cat_min.categoryId
    where p.'price' = cat_min.price

事务
    ACID
        Atomicity
        Consistency
        Isolation
        Durability

    事务的隔离级别
        Read uncommitted
        Read Committed
        Repeatable Reads
        Serializable

    product表
            productId    productName    categoryId    price         count
        1    4            toyota        2            100000
        2    3            porsche        2            1000000
        3    2            addidas        1            500         50
        4    1            nike        null        600

    set session transaction isolation level read committed;
    begin;
    set autocommit = 0;
    select count from 'product' where 'productId'=2;

    update 'product' set 'count'=49 where 'productId' = 2;

    select count from 'product' where 'productId'=2 for update;    //会被锁掉,事务做完才会运行
    commit;

    update 'product' where set count = count-1 where 'productId' = 2;


乐观锁

    演示:
        读取数据,记录Timestamp
        修改数据
        检查和提交数据

    select count from 'product' where 'productId' = 2;
    update 'product' set 'count' = 46 where 'productId' =2 and 'count'=47;    //and后这个就是乐观锁,设置46之前需要读到count为47


程序调优:
    改善数据访问方式以提升缓存命中率
    利用数据库连接池替代直接的数据库访问
    使用迭代替代递归
    合并多个远程调用批量发送
    共享冗余数据提高访问效率

猜你喜欢

转载自blog.csdn.net/weixin_42898914/article/details/85078717