ContentFeedCreate.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Repositories\FeedRepositories;
  4. use App\Repositories\ProductSkuRepository;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\Log;
  7. use PhpAmqpLib\Connection\AMQPStreamConnection;
  8. class ContentFeedCreate extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'content:feed';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'virus通知异步处理-feed生成,帖子数据统计';
  22. protected $connection;
  23. protected $channel;
  24. protected $queue = 'content_feed_queue';
  25. /**
  26. * Create a new command instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct(FeedRepositories $feedRepositories)
  31. {
  32. parent::__construct();
  33. $this->feedRepositories = $feedRepositories;
  34. }
  35. public function getConnection()
  36. {
  37. $conn = false;
  38. if ($this->connection) {
  39. return $this->connection;
  40. }
  41. for ($i = 0; $i < 3; $i++) {
  42. $connection = $this->createConn();
  43. if ($connection) {
  44. $conn = $connection;
  45. break;
  46. }
  47. Log::info("create amqp conn retry=" . $i);
  48. }
  49. return $conn;
  50. }
  51. public function createConn()
  52. {
  53. try {
  54. $connection = new AMQPStreamConnection(env('MQ_HOST'), env('MQ_PORT'), env('MQ_USERNAME'), env('MQ_PWD'), env('MQ_VHOST'));
  55. } catch (\Exception $exception) {
  56. Log::info("AMQP connection Error" . $exception->getMessage());
  57. $connection = false;
  58. }
  59. return $connection;
  60. }
  61. /**
  62. * Execute the console command.
  63. *
  64. * @return mixed
  65. */
  66. public function handle()
  67. {
  68. $this->connection = $this->getConnection();
  69. $this->channel = $this->connection->channel();
  70. $this->channel->queue_declare($this->queue, false, true, false, false);
  71. $callback = function ($msg) {
  72. $param = \GuzzleHttp\json_decode($msg->body,true);
  73. $this->line('收到消息'.$msg->body);
  74. $this->feedRepositories->contentCreate($param);
  75. $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  76. };
  77. $this->channel->basic_qos(null, 1, null);
  78. $this->channel->basic_consume($this->queue, '', false, false, false, false, $callback);
  79. while (count($this->channel->callbacks)) {
  80. $this->channel->wait();
  81. }
  82. $this->channel->close();
  83. $this->connection->close();
  84. }
  85. }