欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

Redis 版 秒杀练习

程序员文章站 2022-05-07 09:33:23
...
跳至 [1] [全屏预览]
connect('127.0.0.1', 6379);

$UserID = (int) $_GET['UserID'];
$ActivityID = (int) $_GET['ActivityID'];

// 库存检查
if ($redis->decr('Amount') incr('Amount');
	echo '{ "exception" : "InvalidNumberException" }';
	exit;
}

// 直接入库
$NoRepeat = $redis->hSet('UserList', $UserID, sprintf('{ "ActivityID" : %d, "Milliseconds" : "%.0f" }', $ActivityID, round(microtime(true) * 1000)) );
if (!$NoRepeat) {
	
	// 还原库存
	$redis->incr('Amount');
	echo '{ "exception" : "SaveInvalidException" }';
	exit;
}

echo sprintf('{ "errno" : 0 , "data" : { "UserID" : %d, "Milliseconds": %.0f } }', $UserID, round(microtime(true) * 1000));
exit;