php 秒杀并发怎么做,PHP实现高并发下的秒杀功能–Laravel
namespace App\Http\Controllers\SecKill;
use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class SecKillController extends Controller
{
/**
* 往redis的隊(duì)列中添加庫(kù)存(用於測(cè)試的數(shù)據(jù))
*
*/
public function setAddRedis(){
$store=150;
$res=Redis::llen('goods_store');
echo $res;
$count=$store-$res;
for($i=0;$i
Redis::lpush('goods_store',1);
}
echo Redis::llen('goods_store');
}
//生成唯一訂單號(hào)
public function build_order_no(){
return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
/**
* 使用redis隊(duì)列,因?yàn)閜op操作是原子的,即使有很多用戶(hù)同時(shí)到達(dá),也是依次執(zhí)行,推薦使用(mysql事務(wù)在高并發(fā)下性能下降很厲害,文件鎖的方式也是)
* @param $goods_id
* @return string
*/
public function getGood($goods_id){
$price =10;
$count = Redis::lpop("goods_store");
if(!$count){
return "error:no store redis";
}
$order_sn=$this->build_order_no();
DB::insert('insert into ih_order (order_sn,user_id,goods_id,price) values (?, ?,?,?)', [$order_sn, rand(1,15),$goods_id,$price]);
$res = DB::update('update in_store set store_number = store_number-1 where goods_id = ?', [$goods_id]);
if($res){
return "庫(kù)存減少成功";
} else{
return "庫(kù)存減少失敗";
}
}
public function doLog($log){
file_put_contents("test.txt",$log.'\r\n',FILE_APPEND);
}
/**
*
* desc 在事務(wù)中對(duì)數(shù)據(jù)進(jìn)行加鎖,當(dāng)事務(wù)進(jìn)行提交(commit)或者回滾(rollBack)時(shí)都會(huì)取消鎖。
* 單純的開(kāi)啟一個(gè)事務(wù),并不會(huì)對(duì)事務(wù)中的數(shù)據(jù)進(jìn)行加鎖,只會(huì)保證數(shù)據(jù)的完整性.其他數(shù)據(jù)是否可以訪問(wèn),不能保證數(shù)據(jù)庫(kù)的數(shù)據(jù)單一操作
* @param $goods_id
* @return bool
*/
public function getGoodByMysql($goods_id){
// 開(kāi)啟事務(wù)
DB::beginTransaction();
try {
// 需要處理的邏輯 doSomething;
$res = DB::table("in_store")->where(['goods_id'=>$goods_id])->sharedLock()->first();
//對(duì)事務(wù)中數(shù)據(jù)進(jìn)行加鎖(悲觀鎖)
if($res->store_number) {
$store_number = $res->store_number-1;
$num = DB::table('in_store')->where('goods_id',$goods_id)->decrement('store_number');
if($num) {
// 提交事務(wù)
DB::commit();
$msg = "減少庫(kù)存成功";
} else {
$msg = "減少庫(kù)存失敗";
}
} else {
$msg ="庫(kù)存不夠";
}
DB::rollBack();
return $msg;
} catch (Exception $e) {
// 數(shù)據(jù)回滾, 當(dāng)try中的語(yǔ)句拋出異常。
DB::rollBack();
return false;
// 執(zhí)行一些提醒操作等等...
}
}
}來(lái)源:http://www.icode9.com/content-1-56851.html
總結(jié)
以上是生活随笔為你收集整理的php 秒杀并发怎么做,PHP实现高并发下的秒杀功能–Laravel的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 做环评需要多少钱啊?
- 下一篇: php签名墙,肺功能检查质量控制网