<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/6/13 * Time: 9:13 */ namespace App\Console\Commands; use App\Models\MessageRule; use App\Service\RabbitMqUtil; use Illuminate\Console\Command; use Illuminate\Database\QueryException; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use PhpAmqpLib\Connection\AMQPStreamConnection; class AddMessageRule extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'message:add'; /** * The console command description. * * @var string */ protected $description = '添加发送消息'; /** * Create a new command instance. * * @return void */ public function __construct(MessageRule $messageRule, RabbitMqUtil $rabbitMqUtil) { parent::__construct(); $this->messageRule = $messageRule; $this->rabbitMqUtil = $rabbitMqUtil; } /** * Execute the console command. * * @return mixed */ public function handle() { $this->line("开始添加发送消息"); $this->messageRule ->where('message_status', 0) ->where('send_time', '<', Carbon::now()->toDateTimeString()) ->whereNotNUll('send_time') ->chunk(100, function($messages){ foreach($messages as $message){ DB::beginTransaction(); try{ $this->rabbitMqUtil->push('add_message_rule', $message); $message->message_status = 1; $message->save(); DB::commit(); Log::info('添加发送消息成功:'.$message->id); }catch (QueryException $exception){ DB::rollBack(); Log::error('添加发送消息:'.$exception->getMessage()); } } }); $this->line("添加发送消息结束"); } }