1 说明
前段时间面试的时候,一直被问到如何设计一个秒杀活动,但是无奈没有此方面的实际经验,所以只好凭着自己的理解和一些资料去设计这么一个程序
主要利用到了redis的string和set,string主要是利用它的k-v结构去对库存进行处理,也可以用list的数据结构来处理商品的库存,set则用来确保用户进行重复的提交
其中我们最主要解决的问题是
-防止并发产生超抢/超卖
2 流程设计

3 代码
3.1 服务端代码
class MiaoSha{
const MSG_REPEAT_USER = '请勿重复参与';
const MSG_EMPTY_STOCK = '库存不足';
const MSG_KEY_NOT_EXIST = 'key不存在';
const IP_POOL = 'ip_pool';
const USER_POOL = 'user_pool';
/** @var Redis */
public $redis;
public $key;
public function __construct($key = '')
{
$this->checkKey($key);
$this->redis = new Redis(); //todo 连接池
$this->redis->connect('127.0.0.1');
}
public function checkKey($key = '')
{
if(!$key) {
throw new Exception(self::MSG_KEY_NOT_EXIST);
} else {
$this->key = $key;
}
}
public function setStock($value = 0)
{
if($this->redis->exists($this->key) == 0) {
$this->redis->set($this->key,$value);
}
}
public function checkIp($ip = 0)
{
$sKey = $this->key . self::IP_POOL;
if(!$ip || $this->redis->sIsMember($sKey,$ip)) {
throw new Exception(self::MSG_REPEAT_USER);
}
}
public function checkUser($user = 0)
{
$sKey = $this->key . self::USER_POOL;
if(!$user || $this->redis->sIsMember($sKey,$user)) {
throw new Exception(self::MSG_REPEAT_USER);
}
}
public function checkStock($user = 0, $ip = 0)
{
$num = $this->redis->decr($this->key);
if($num < 0 ) {
throw new Exception(self::MSG_EMPTY_STOCK);
} else {
$this->redis->sAdd($this->key . self::USER_POOL, $user);
$this->redis->sAdd($this->key . self::IP_POOL, $ip);
//todo add to mysql
echo 'success' . PHP_EOL;
error_log('success' . $user . PHP_EOL,3,'/var/www/html/demo/log/debug.log');
}
}
/**
* @note:此种做法不能防止并发
* @func checkStockFail
* @param int $user
* @param int $ip
* @throws Exception
*/
public function checkStockFail($user = 0,$ip = 0) {
$num = $this->redis->get($this->key);
if($num > 0 ){
$this->redis->sAdd($this->key . self::USER_POOL, $user);
$this->redis->sAdd($this->key . self::IP_POOL, $ip);
//todo add to mysql
echo 'success' . PHP_EOL;
error_log('success' . $user . PHP_EOL,3,'/var/www/html/demo/log/debug.log');
$num--;
$this->redis->set($this->key,$num);
} else {
throw new Exception(self::MSG_EMPTY_STOCK);
}
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
