namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Jobs\QueueTest;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\DB;
use App\Jobs\InsertData;
class TestController extends Controller
{
public function test()
{
dispatch(new InsertData($this->getQueueData()));
}
/**
* return a array.
*
* @return Array
*/
private function getQueueData()
{
return 'user' . str_random(3);
}
}
已经创建了队列任务,为App/jobs/InsertData,上方是我的控制器。
接下来是我的队列文件:
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class InsertData implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $username;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($username)
{
$this->username = $username;
}
private function luckUserList($username)
{
$user = DB::table('user_list')->where('username', $username)->first();
if (empty($user)) {
$state = DB::table('user_list')->insert(array('username' => $username));
}
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$data = DB::table('test')->find(1);
$number = $data->num;
if ($number > 0) {
$this->luckUserList($this->username);
--$number;
DB::table('test')->where('id', 1)->update(array('num' => $number));
} else {
Redis::hset(
array(
'user_list' => array($this->username)
)
);
}
}
}
!!!
接下来运行第一步,访问具体路由,也就是走到test方法中,laravel会将请求写入redis队列
使用AB工具
ab -n 1000 -c 500 http://laravel54.web/test
查看数量:
多次测试,结果应该是1000的,结果却不一致,难道我要用文件锁方式保证写入队列的一致性?这是第一步,就卡壳了,还没去执行队列,版本是laravel5.4,望兄弟帮忙看看,谢谢!
先确保真的能处理500并发请求,真的处理了1000个请求。
试试
ab -n 1000 -c 1
。