123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace App\Console\Commands;
- use App\Repositories\FeedRepositories;
- use App\Repositories\ProductSkuRepository;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\Log;
- use PhpAmqpLib\Connection\AMQPStreamConnection;
- class ContentFeedCreate extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'content:feed';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'virus通知异步处理-feed生成,帖子数据统计';
- protected $connection;
- protected $channel;
- protected $queue = 'content_feed_queue';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct(FeedRepositories $feedRepositories)
- {
- parent::__construct();
- $this->feedRepositories = $feedRepositories;
- }
- public function getConnection()
- {
- $conn = false;
- if ($this->connection) {
- return $this->connection;
- }
- for ($i = 0; $i < 3; $i++) {
- $connection = $this->createConn();
- if ($connection) {
- $conn = $connection;
- break;
- }
- Log::info("create amqp conn retry=" . $i);
- }
- return $conn;
- }
- public function createConn()
- {
- try {
- $connection = new AMQPStreamConnection(env('MQ_HOST'), env('MQ_PORT'), env('MQ_USERNAME'), env('MQ_PWD'), env('MQ_VHOST'));
- } catch (\Exception $exception) {
- Log::info("AMQP connection Error" . $exception->getMessage());
- $connection = false;
- }
- return $connection;
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $this->connection = $this->getConnection();
- $this->channel = $this->connection->channel();
- $this->channel->queue_declare($this->queue, false, true, false, false);
- $callback = function ($msg) {
- $param = \GuzzleHttp\json_decode($msg->body,true);
- $this->line('收到消息'.$msg->body);
- $row = $this->feedRepositories->feedCreate($param);
- $this->line('处理消息'.$row);
- if($row){
- $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
- }
- };
- $this->channel->basic_qos(null, 1, null);
- $this->channel->basic_consume($this->queue, '', false, false, false, false, $callback);
- while (count($this->channel->callbacks)) {
- $this->channel->wait();
- }
- $this->channel->close();
- $this->connection->close();
- }
- }
|