使用redis 分布式操作


    public function joinShoppingGuides($userId, $dgId, $user_address, $user_consignee, $user_tel)
    {
        $this->key = "placeOrder-{$userId}";
        $good = $this->good->where('id', $dgId)->find();
        if (!$good || $good->status !== 1)  return $this->fail("此商品已经下架了");
        $price = $good->price;
        $type = $good->type;
        $orderNo = 'D' . setOrderNo();
        $where = [
            'good_id' => $dgId,
            'order_no' => $orderNo,
            'order_user_id' => $good['user_id'],
            'user_id' => $userId,
            'user_address' => $user_address,
            'user_consignee' => $user_consignee,
            'user_tel' => $user_tel,
            'status' => '1',
            'price' => $price
        ];
        if(!$this->threadLock()) return $this->fail("请勿频繁操作");
        try {
            Db::startTrans();
            switch (intval($type)){
                case Goods::AWARD:
                    $where['type1_award_param'] = json_encode($good['type_params']);
                    break;
                case Goods::TEAM:
                    $where['type2_winner'] = 0;
                    $res = $this->joinTeam($dgId,$where);
                    if($res !== true) {
                        Db::commit();
                        return $res;
                    }
                    break;
                case Goods::QIANG:
                    $res = $this->joinQing($dgId,$good);
                    if($res !== true) {
                        Db::commit();
                        return $res;
                    }
                    break;
            }
            $this->order->create($where);
            Db::commit();;
        }catch (\Throwable $e){
            Db::rollback();
           return $this->fail("下单失败");
        }
        $this->redis->del($this->key);
        return $this->success("下单成功");
    }

   private function threadLock(){
        if(!$this->redis->setnx($this->key,time())){
            $last = $this->redis->get($this->key);
            $space = time() - $last;
            if($space <= 5 ) return false;
        }
        return true;
    }

你可能感兴趣的:(redis,分布式)