首頁 > php框架 > Laravel > 主體

方案詳解:使用laravel解決庫存超出問題

藏色散人
發布: 2021-06-09 09:08:16
轉載
2475 人瀏覽過

以下由laravel教學專欄為大家介紹使用laravel解決庫存超出的幾個方案,希望對需要的朋友有幫助!

資料庫欄位

方案詳解:使用laravel解決庫存超出問題

1.錯誤的示範

    /**
     * 错误示范
     * Create by Peter Yang
     * 2021-06-08 10:57:59
     * @return string
     */
    function test1()
    {

        //商品id
        $id = request()->input('id');

        $product = Product::where('id', $id)->firstOrFail();

        if ($product->num decrement('num');

        return "success";

    }
登入後複製

使用go模擬並發

package mainimport (
    "fmt"
    "github.com/PeterYangs/tools/http"
    "sync")func main() {

    client := http.Client()

    wait := sync.WaitGroup{}

    for i := 0; i <p>在資料庫中查看庫存</p><p><img src="https://img.php.cn/upload/article/000/000/020/b3a44af246aab48e87b85467ea9f1568-1.png" alt="方案詳解:使用laravel解決庫存超出問題"><br><strong>庫存已超出</strong></p><h2>
<span class="header-link octicon octicon-link"></span>2.redis原子鎖定</h2><pre class="brush:php;toolbar:false">    /**
     * redis原子锁
     * Create by Peter Yang
     * 2021-06-08 11:00:31
     */
    function test2()
    {
        //商品id
        $id = request()->input('id');

        $lock = \Cache::lock("product_" . $id, 10);

        try {

            //最多等待5秒,5秒后未获取到锁,则抛出异常
            $lock->block(5);

            $product = Product::where('id', $id)->firstOrFail();

            if ($product->num decrement('num');

            return 'success';

        }catch (LockTimeoutException $e) {

            return '当前人数过多';

        } finally {

            optional($lock)->release();
        }
    }
登入後複製

庫存正常

方案詳解:使用laravel解決庫存超出問題

#3.mysql悲觀鎖定

    /**
     * mysql悲观锁
     * Create by Peter Yang
     * 2021-06-08 11:00:47
     */
    function test3()
    {

        //商品id
        $id = request()->input('id');

        try {
            \DB::beginTransaction();
            $product = Product::where('id', $id)->lockForUpdate()->first();

            if ($product->num decrement('num');

            \DB::commit();

            return "success";

        } catch (\Exception $exception) {

        }

    }
登入後複製

庫存正常

方案詳解:使用laravel解決庫存超出問題

4.mysql樂觀鎖定

    /**
     * mysql乐观锁
     * Create by Peter Yang
     * 2021-06-08 11:00:47
     */
    function test4()
    {

        //商品id
        $id = request()->input('id');

        $product = Product::where('id', $id)->first();

        if ($product->num num]);

        if (!$res) {

            return '当前人数过多';

        }

        return 'success';


    }
登入後複製

庫存正常

方案詳解:使用laravel解決庫存超出問題

優化樂觀鎖定

修改庫存的sql修改為

\DB::update('UPDATE `product` SET num = num -1 WHERE id = ? AND num-1 >= 0', [$id]);
登入後複製

以上是方案詳解:使用laravel解決庫存超出問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:learnku.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!