BehaviorRecord.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Repositories\BehaviorRecordRepositories;
  4. use App\Repositories\ProductSkuRepository;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\Log;
  7. use PhpAmqpLib\Connection\AMQPStreamConnection;
  8. class BehaviorRecord extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'behavior:record';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = '记录行为账本';
  22. protected $connection;
  23. protected $channel;
  24. protected $PRODUCT_STOCK_MYSQL_QUEUE = 'behavior_record_queue';
  25. /**
  26. * Create a new command instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct(BehaviorRecordRepositories $behaviorRecordRepositories)
  31. {
  32. parent::__construct();
  33. $this->behaviorRecordRepositories = $behaviorRecordRepositories;
  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->PRODUCT_STOCK_MYSQL_QUEUE, false, true, false, false);
  71. $callback = function ($msg) {
  72. $param = \GuzzleHttp\json_decode($msg->body,true);
  73. $row = $this->behaviorRecordRepositories->addRecord($param);
  74. if($row){
  75. $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  76. }
  77. };
  78. $this->channel->basic_qos(null, 1, null);
  79. $this->channel->basic_consume($this->PRODUCT_STOCK_MYSQL_QUEUE, '', false, false, false, false, $callback);
  80. while (count($this->channel->callbacks)) {
  81. $this->channel->wait();
  82. }
  83. $this->channel->close();
  84. $this->connection->close();
  85. }
  86. }