文檔地址
1.建立命令類
php artisan make:console user#生成文件user.php
2.編寫文件php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use App\Models\Attention; use RedisFacade; class User extends Command { /** * The console command name. *自定義命令的 名稱 * @var string */ protected $name = 'user'; /** * The console command description. * * @var string */ protected $description = 'User'; /** * Execute the console command. *自定義命令被執行時,將會調用 fire 方法 * @return mixed */ public function fire() { $action = 'action' . ucfirst($this->argument('action')); if (method_exists($this, $action)) { $this->$action(); return false; } $this->error('action參數爲空.'); } /** * 用戶關注關係更新到redis * @return mixed #php artisan user -t redis -s 100 --usleep 0 attention */ protected function actionAttention() { if ($this->option('target') != 'redis') { $this->error('target 參數錯誤.'); return false; } $redis = RedisFacade::connection(); $usleep = $this->option('usleep'); $limit = $this->option('size'); $minId = 0; while (true) { $attention = Attention::where('id', '>', $minId) ->select('id', 'user_id', 'at_id', 'created_at') ->orderBy('id') ->take($limit) ->get(); $selectCount = count($attention); if (!$selectCount) { break; } //批量操做 $redis->pipeline(function($pipe) use($attention) { foreach ($attention as $v) { $pipe->hSet('follows:list:' . $v['user_id'], $v['at_id'], strtotime($v['created_at'])); $pipe->hSet('fans:list:' . $v['at_id'], $v['user_id'], strtotime($v['created_at'])); } }); if ($selectCount < $limit) { break; } //最後一個id $minId = $attention->last()->id; unset($attention); if ($usleep > 0) { usleep($usleep); } } $this->info('完成.'); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ['action', InputArgument::REQUIRED, 'Action name, eg: sync'], ]; } /** * Get the console command options. *默認參數可經過執行php artisan user -h 來查看 * @return array */ protected function getOptions() { return [ ['target', 't', InputOption::VALUE_OPTIONAL, 'Sync target', 'redis'], ['size', 's', InputOption::VALUE_OPTIONAL, 'Loop size', '100'], ['usleep', null, InputOption::VALUE_OPTIONAL, 'Loop usleep', '0'], ]; } }
3.註冊一個 Artisan 命令
vi app/Console/Kernel.phplaravel
protected $commands = [ 'App\Console\Commands\User', ];