秒杀场景中的超卖情况是如果避免了的?
先看一下面
数据库字段
function test1()
{
//商品id
$id = request()->input('id');
$product = Product::where('id', $id)->firstOrFail();
if ($product->num <= 0) {
return "卖光啦!!";
}
//库存减1
$product->decrement('num');
return "success";
}
上面的写法看似没有问题,先存mysql库中的数量是否大于0,然后再减去1,然而在高并发下,就会出问题
用go模拟一下并发
package main
import (
"fmt"
"github.com/PeterYangs/tools/http"
"sync"
)
func main() {
client := http.Client()
wait := sync.WaitGroup{}
for i := 0; i < 50; i++ {
wait.Add(1)
go func(w *sync.WaitGroup) {
defer w.Done()
res, _ := client.Request().GetToString("http://www.api/test1?id=1")
fmt.Println(res)
}(&wait)
}
wait.Wait()
}
哦豁
超卖了
解法如下:
1. redis
/**
* 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 <= 0) {
return "卖光啦!!";
}
//库存减1
$product->decrement('num');
return 'success';
}catch (LockTimeoutException $e) {
return '当前人数过多';
} finally {
optional($lock)->release();
}
}
2. 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 <= 0) {
return "卖光啦!!";
}
//库存减1
$product->decrement('num');
\DB::commit();
return "success";
} catch (\Exception $exception) {
}
}
3. 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 <= 0) {
return "卖光啦!!";
}
//修改前检查库存和之前是否一致,不一致说明已经有变动,则放弃更改
$res = \DB::update('UPDATE `product` SET num = num -1 WHERE id = ? AND num=?', [$id, $product->num]);
if (!$res) {
return '当前人数过多';
}
return 'success';
}