本篇内容介绍了“laravel怎么解决库存超出问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
数据库字段
2021-06-08 10:57:59
* @return string
*/
function test1()
{
//商品id
$id = request()->input('id');
$product = Product::where('id', $id)->firstOrFail();
if ($product->num <= 0) {
return "卖光啦!!";
}
//库存减1
$product->decrement('num');
return "success";
}
使用 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()
}
在数据库中查看库存
库存已超出
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();
}
}
库存正常
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) {
}
}
库存正常
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`, [$id, $product->num]);
if (!$res) {
return '当前人数过多';
}
return 'success';
}
库存正常
优化乐观锁
修改库存的 sql 修改为
\DB::update('UPDATE `product`, [$id]);
2021-06-15 15:18:31
* @return string
*/
function test5()
{
//商品id
$id = request()->input('id');
$num = Redis::command('get', ['product_' . $id]);
if ($num <= 0) {
return "卖完啦!";
}
//减库存
$re = Redis::command('decrby', ['product_' . $id, 1]);
//减多了回滚
if ($re < 0) {
Redis::command('incrby', ['product_' . $id, 1]);
return "卖完啦!";
}
return 'success';
}
“laravel怎么解决库存超出问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.51cto.com/u_15052623/5752299