下面由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 <= 0) { return "卖光啦!!"; } //仓库减1 $product->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 < 50; i++ { wait.add(1) go func(w *sync.waitgroup) { defer wait.done() res, _ := client.request().gettostring("http://www.api/test1?id=1") fmt.println(res) }(&wait) } wait.wait()}
在数据库中查看库存
库存已超出
2.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(); } }
库存正常
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 <= 0) { return "卖光啦!!"; } //仓库减1 $product->decrement('num'); \db::commit(); return success; } catch (\exception $exception) { } }
库存正常
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 <= 0) { return "卖光啦!!"; } //修改前检查库存和之前是否一致,不一致说明已经有变动,则放弃更改 $res = \db::update('update `product` set num = num -1 where id = ? and num=?', [$id, $product->num]); if (!$res) { return '当前人数过多'; } return 'success'; }
库存正常
优化乐观锁
修改库存的sql修改为
\db::update('update `product` set num = num -1 where id = ? and num-1 >= 0', [$id]);
以上就是方案详解:使用laravel解决库存超出问题的详细内容。