thinkphp6悲观锁使用方法

文章描述:

业务逻辑的实现过程中,往往需要保证数据访问的排他性。如在金融系统的日终结算处理中,我们希望针对某个时间点的数据进行处理,而不希望在结算进行过程中(可能是几秒种,也可能是几个小时),数据再发生变化。此时,我们就需要通过一些机制来保证这些数据在某个操作过程中不会被外界修改,这样的机制,在这里,也就是所谓的 “ 锁 ” ,即给我们选定的目标数据上锁,使其无法被其他程序修改。 ThinkPHP支持两种锁机制:即通常所说的 “ 悲观锁( Pessimistic Locking ) ”和 “ 乐观锁( Optimistic Locking ) ” 。

应用场景商品进行购买

商品goods表,假设商品的id为1,购买数量为1,status为1表示上架中,2表示下架。现在用户购买此商品,在不是高并发的情况下处理逻辑是:

1.查找此商品的信息;
2.检查商品库存是否大于购买数量;
3.修改商品库存和销量;

如果在高并发访问的情况下很可能会出现问题。如果商品库存是100个,高并发的情况下可能会有1000个同时访问,在到达第2步的时候,都会检测通过。这样会出现商品库存是-900个的情况。显然着不满足需求!!!

商品表

CREATE TABLE `goods` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `status` tinyint(1) NOT NULL DEFAULT '1',
  `total` int(11) NOT NULL DEFAULT '0',
  `sell` int(11) NOT NULL DEFAULT '100',
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

商品数据

INSERT INTO `test`.`goods`(`id`, `name`, `status`, `total`, `sell`, `price`) VALUES (1, '商品', 1, 100, 0, 9.90);

订单表

CREATE TABLE `orders` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL DEFAULT '0',
  `create_time` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '1',
  `goods_id` int(11) NOT NULL DEFAULT '0',
  `order_no` varchar(200) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

 

不加锁

public function demo()
    {
        $num = 1;
        $goods_id = 1;
        Db::startTrans();
        try {
            $where = [];
            $where['id'] = $goods_id;
            $where['status'] = 1;
            $goods_info = Db::table('goods')->where($where)->find();
            if (empty($goods_info)) {
                return '商品不存在';
            }
            $total = $goods_info['total'];
            $sell = $goods_info['sell'];
            if ($total < $num) {
                return '库存不足';
            }
            $data['total'] = $total-$num;
            $data['sell'] = $sell+$num;
            $res = Db::table('goods')->where(['id'=>$goods_id])->update($data);
            $order_data = [];
            $order_data['uid'] = rand(1000,9999);
            $order_data['status'] = 1;
            $order_data['create_time'] = date('Y-m-d H:i:s');
            $order_data['goods_id'] = $goods_id;
            $order_data['order_no'] = date('YmdHis').rand(1000,10000);
            $order_res = Db::table('orders')->insert($order_data);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo $e->getMessage();
            exit('rollback');
        }
        echo '请求成功';
    }

加锁

    public function index()
    {
        $num = 1;
        $goods_id = 1;
        Db::startTrans();
        try {
            $where = [];
            $where['id'] = $goods_id;
            $where['status'] = 1;
            $goods_info = Db::table('goods')->lock(true)->where($where)->find();
            if (empty($goods_info)) {
                return '商品不存在';
            }
            $total = $goods_info['total'];
            $sell = $goods_info['sell'];
            if ($total < $num) {
                return '库存不足';
            }
            $data['total'] = $total-$num;
            $data['sell'] = $sell+$num;
            $res = Db::table('goods')->where(['id'=>$goods_id])->update($data);
            $order_data = [];
            $order_data['uid'] = rand(1000,9999);
            $order_data['status'] = 1;
            $order_data['goods_id'] = $goods_id;
            $order_data['order_no'] = date('YmdHis').rand(1000,10000);
            $order_data['create_time'] = date('Y-m-d H:i:s');
            $order_res = Db::table('orders')->insert($order_data);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo $e->getMessage();
            exit('rollback');
  
        }
        echo '请求成功';
    }

 

 

 

 

发布时间:2022/04/28

发表评论