Skip to content

Commit

Permalink
thinkphp5+redis 秒杀
Browse files Browse the repository at this point in the history
  • Loading branch information
chen committed Sep 24, 2018
0 parents commit 8f4a84b
Show file tree
Hide file tree
Showing 32 changed files with 925 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea
composer.lock
*.log
thinkphp
/runtime
42 changes: 42 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
sudo: false

language: php

branches:
only:
- stable

cache:
directories:
- $HOME/.composer/cache

before_install:
- composer self-update

install:
- composer install --no-dev --no-interaction --ignore-platform-reqs
- zip -r --exclude='*.git*' --exclude='*.zip' --exclude='*.travis.yml' ThinkPHP_Core.zip .
- composer require --update-no-dev --no-interaction "topthink/think-image:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-migration:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-captcha:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-mongo:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-worker:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-helper:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-queue:^1.0"
- composer require --update-no-dev --no-interaction "topthink/think-angular:^1.0"
- composer require --dev --update-no-dev --no-interaction "topthink/think-testing:^1.0"
- zip -r --exclude='*.git*' --exclude='*.zip' --exclude='*.travis.yml' ThinkPHP_Full.zip .

script:
- php think unit

deploy:
provider: releases
api_key:
secure: TSF6bnl2JYN72UQOORAJYL+CqIryP2gHVKt6grfveQ7d9rleAEoxlq6PWxbvTI4jZ5nrPpUcBUpWIJHNgVcs+bzLFtyh5THaLqm39uCgBbrW7M8rI26L8sBh/6nsdtGgdeQrO/cLu31QoTzbwuz1WfAVoCdCkOSZeXyT/CclH99qV6RYyQYqaD2wpRjrhA5O4fSsEkiPVuk0GaOogFlrQHx+C+lHnf6pa1KxEoN1A0UxxVfGX6K4y5g4WQDO5zT4bLeubkWOXK0G51XSvACDOZVIyLdjApaOFTwamPcD3S1tfvuxRWWvsCD5ljFvb2kSmx5BIBNwN80MzuBmrGIC27XLGOxyMerwKxB6DskNUO9PflKHDPI61DRq0FTy1fv70SFMSiAtUv9aJRT41NQh9iJJ0vC8dl+xcxrWIjU1GG6+l/ZcRqVx9V1VuGQsLKndGhja7SQ+X1slHl76fRq223sMOql7MFCd0vvvxVQ2V39CcFKao/LB1aPH3VhODDEyxwx6aXoTznvC/QPepgWsHOWQzKj9ftsgDbsNiyFlXL4cu8DWUty6rQy8zT2b4O8b1xjcwSUCsy+auEjBamzQkMJFNlZAIUrukL/NbUhQU37TAbwsFyz7X0E/u/VMle/nBCNAzgkMwAUjiHM6FqrKKBRWFbPrSIixjfjkCnrMEPw=
file:
- ThinkPHP_Core.zip
- ThinkPHP_Full.zip
skip_cleanup: true
on:
tags: true
32 changes: 32 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

ThinkPHP遵循Apache2开源协议发布,并提供免费使用。
版权所有Copyright © 2006-2017 by ThinkPHP (http://thinkphp.cn)
All rights reserved。
ThinkPHP® 商标和著作权所有者为上海顶想信息科技有限公司。

Apache Licence是著名的非盈利开源组织Apache采用的协议。
该协议和BSD类似,鼓励代码共享和尊重原作者的著作权,
允许代码修改,再作为开源或商业软件发布。需要满足
的条件:
1. 需要给代码的用户一份Apache Licence ;
2. 如果你修改了代码,需要在被修改的文件中说明;
3. 在延伸的代码中(修改和有源代码衍生的代码中)需要
带有原来代码中的协议,商标,专利声明和其他原来作者规
定需要包含的说明;
4. 如果再发布的产品中包含一个Notice文件,则在Notice文
件中需要带有本协议内容。你可以在Notice中增加自己的
许可,但不可以表现为对Apache Licence构成更改。
具体的协议参考:http://www.apache.org/licenses/LICENSE-2.0

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ThinkPHP 5.0

1 change: 1 addition & 0 deletions application/.htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
deny from all
104 changes: 104 additions & 0 deletions application/admin/controller/Order.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php
namespace app\admin\controller;
use app\admin\model\Good;
use app\admin\model\Order as OrderModel;
use app\admin\model\Redis;
use app\admin\model\User;
use app\admin\model\Good as GoodModel;
use think\db;
use think\log;
class Order extends \think\Controller{

public $goodTotal = 1000;
public $good_id = 1;

/**
* 秒杀请求接口
* http://tp5.120.com/admin/order/sekillApi
*/
public function sekillApi(){

$good_total_redis = OrderModel::getGoodTotal();
if ($good_total_redis <= 0){
echo "抢购活动已经完毕了";
exit;
}
//模拟用户是否登录
$uid = User::getUserId();
if (!$uid){
echo "请登录!";
exit;
}else{
//这里可以使用redis lpush 尽量减少数据库操作
if(User::getUserOrder($uid)){
echo "你已经购买了!,记录重复购买用户日记";
file_put_contents("repeat.txt", "$uid.\n", FILE_APPEND);
exit;
}
}
//抢到了 -- 减去库存
if(OrderModel::setDecRedisLlen() ===false){
echo '抢购活动已经完毕了';
exit;
}

//生成订单
$order_id = OrderModel::buildOrderId($uid);
//插入订单
$order_status = OrderModel::addOrder($uid,$order_id,$this->good_id);
if ($order_status){
//mysql库存;
if (GoodModel::setDecQueryCounts()){
echo "抢购成功";
exit;
}
}
echo "抢购失败日记";
file_put_contents("error.txt", "$uid.\n", FILE_APPEND);
exit;
}

/**
* 增加redis 队列 和 随便设置商品数量
*/
public function addRedisNumber(){

Redis::getConn()->lTrim(Redis::$good_total_field,1,0);
for ($i = 1;$i <= $this->goodTotal;$i++){
Redis::getConn()->lPush(Redis::$good_total_field,1);
}
db('Good')->where(['id'=>$this->good_id])->update(['counts'=>$this->goodTotal]);
print_r(Redis::getConn()->lLen(Redis::$good_total_field));

}

public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ad_bd568ce7058a1091"></think>';
}

/**
* swoole 客户端
* @return string
*/
public function send(){
$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
$ret = $client->connect("192.168.1.120", 9500);

if(empty($ret)){
echo 'error!connect to swoole_server failed';
} else {
//这里只是简单的实现了发送的内容
$send = $client->send('我是客户端,我发送了消息~__');
//等待服务端返回诗句
if ($send){
//recv返回客户端消息,应该等服务端返回数据才执行,否则会报错
$recv = $client->recv();
}else{
$recv = "服务端返回失败!";
}

return $send."--".$recv;
}
}
}
38 changes: 38 additions & 0 deletions application/admin/model/Good.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
/**
* Author: ekk0
* Date: 2018/9/24 17:56
*/
namespace app\admin\model;
use app\admin\model\Redis;
use app\admin\controller\Order;

class Good extends \think\Model
{
// 设置当前模型对应的完整数据表名称
protected $table = 'good';


/**
* 查询mysql库存剩余数量
* @param $uid
*/
static public function QueryGoodTotal(){
$good_count = Good::where(['id'=>(new Order())->good_id])->sum("counts");
if($good_count <= 0){
return 0;
}else{
return (int) $good_count;
}
}
/**
* 减去库存
*/
static public function setDecQueryCounts(){
if(Good::where(['id'=>(new Order())->good_id])->setDec('counts') !==false){
return true;
}
return false;
}

}
70 changes: 70 additions & 0 deletions application/admin/model/Order.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* Author: ekk0
* Date: 2018/9/24 17:56
*/
namespace app\admin\model;
use app\admin\model\Redis;

class Order extends \think\Model
{
// 设置当前模型对应的完整数据表名称
protected $table = 'order';
/**
* 生产订单号
* @param int $uid
* @return int
*/
static public function buildOrderId($uid = 0){

if((int) $uid > 0){
$order = $uid.time().mt_rand(1000,9999);
return (int) $order;
}
}
/**
* 写入订单
* @param $uid
* @param $order_id
*/
static public function addOrder($uid ,$order_id ,$good_id){

$data['good_id'] = $good_id;
$data['order_id'] = $order_id;
$data['uid'] = $uid;
$data['add_time'] = time();
if(Order::insert($data) !==false){
//dump(self::getLastSql());
return self::getLastInsID();
}
return false;
}


/**
* 查询redis队列数量
*/
static public function getGoodTotal(){
$good_count = (Redis::getConn())->lLen(Redis::$good_total_field);
if($good_count <= 0){
return 0;
}else{
return (int) $good_count;
}
}


/**
* 减去redis库存
* @param int $good_id
* @return bool
*/
static public function setDecRedisLlen(){
if(Redis::getConn()->lPop(Redis::$good_total_field)!==false){
return true;
}
return false;
}


}
34 changes: 34 additions & 0 deletions application/admin/model/Redis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
/**
* Author: ekk0
* Date: 2018/9/24 18:03
*/
namespace app\admin\model;

class Redis{
static public $good_total_field = 'good_total_number';
private static $_instance = null;

private function __construct(){
self::$_instance = new \Redis();
$config = config('redis');
self::$_instance->connect($config['host'],$config['port']);

if(isset($config['password'])){
self::$_instance->auth($config['password']);
}
}

//获取静态实例
static public function getConn(){
if(!self::$_instance){
new self;
}
return self::$_instance;
}

/*
* 禁止clone
*/
private function __clone(){}
}
34 changes: 34 additions & 0 deletions application/admin/model/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
/**
* Author: ekk0
* Date: 2018/9/24 17:56
*/
namespace app\admin\model;

class User extends \think\Model{

// 设置当前模型对应的完整数据表名称
protected $table = 'user';

/**
* 模拟用户,数据越小测试用户重复购买越大
* @return int
*/
static public function getUserId(){
$uid = mt_rand(1,999999999);
return (int) $uid;
}

/**
* 判断用户是否已经购买
*/
static public function getUserOrder($uid){
$user_order_find = Order::field('uid')->where(['uid'=>$uid])->find();
if($user_order_find){
return true;
}else{
return false;
}
}

}
12 changes: 12 additions & 0 deletions application/command.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <[email protected]>
// +----------------------------------------------------------------------

return [];
Loading

0 comments on commit 8f4a84b

Please sign in to comment.