美文网首页
redis实现秒杀优惠券2019-04-04

redis实现秒杀优惠券2019-04-04

作者: 她城无池 | 来源:发表于2019-04-04 22:09 被阅读0次

1.模拟上传一个批次的优惠券

public function upload()
    {
        $quanId = isset($_GET['quanId']) ? $_GET['quanId'] : '';
        $count =  isset($_GET['count']) ? $_GET['count'] : '';

        if (empty($quanId) || empty($count)) {
            return $this->response(-1, '参数不合法');
        }

        // 模拟一个批次ID,实际上应该走数据库去生成
        $batchId = time();

        $result = QuanService::upload($quanId, $batchId, $count);
        if (empty($result)) {
            return $this->response(1, '服务端异常');
        }
        return $this->response(0, '生成成功', $result);
    }
 public static function upload($quanId, $batchId, $count)
    {
        $coupons = [];

        // 为批次模拟生成count个券码
        for ($i = 0; $i < $count; ++$i) {
            $bytes = openssl_random_pseudo_bytes(8);
            $coupon = base_convert(bin2hex($bytes), 16, 32);
            $coupons[] = $coupon;
        }

        // 投递券码
        $batchSize = QuanModel::uploadBatchToRedis($quanId, $batchId, $coupons);
        return ['batchId' => $batchId, 'batchSize' => $batchSize, 'coupons' => $coupons];
    }
}

\Redis出现找不到的情况,原因是没有安装php_redis和php_igbinary扩展;
$redisMaster->multi(\Redis::PIPELINE);中的multi参数,默认为multi()表示一次一个,开启事务。如果为PIPELINE则为高效处理,批量处理。zCard:返回有序集 key 的基数。

 public static function uploadBatchToRedis($quanId, $batchId, $coupons)
    {
        $redisMaster = Redis::master('default');

        $quanKey = "QUAN_{" . $quanId . "}"; // {quanid} redis hash tags
        $batchKey = "BATCH_{" . $quanId . "}_" . $batchId; // {quanid} redis hash tags
        //$tran = $redisMaster->multi(2);

        $tran = $redisMaster->multi(\Redis::PIPELINE);
        // 券码加入集合
        foreach ($coupons as $coupon) {
            $tran->zAdd($batchKey, 0, $coupon);
        }
        // 批次加入优惠券
        $tran->hSet($quanKey, $batchKey, json_encode(['online' => true]));
        $tran->exec();

        return $redisMaster->zCard($batchKey);
    }

传参quanId为5,count为10;

运行结果为: 1554383964(1).png

2.composer reqiure myf/core(需要php版本大于5.6)

3.下载安装lua,因为是基于lua写的。
4.下载安装redis,redis manger。
5.下载安装php_redis扩展,php_igbinary扩展;

相关文章

网友评论

      本文标题:redis实现秒杀优惠券2019-04-04

      本文链接:https://www.haomeiwen.com/subject/refciqtx.html