AddNoticeRule.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\NoticeRule;
  4. use App\Service\RabbitMqUtil;
  5. use App\Traits\PostTrait;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Database\QueryException;
  8. use Illuminate\Support\Carbon;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use PhpAmqpLib\Connection\AMQPStreamConnection;
  12. class AddNoticeRule extends Command
  13. {
  14. use PostTrait;
  15. /**
  16. * The name and signature of the console command.
  17. *
  18. * @var string
  19. */
  20. protected $signature = 'notice:add';
  21. /**
  22. * The console command description.
  23. *
  24. * @var string
  25. */
  26. protected $description = '添加发送通知';
  27. /**
  28. * Create a new command instance.
  29. *
  30. * @return void
  31. */
  32. public function __construct(NoticeRule $noticeRule, RabbitMqUtil $rabbitMqUtil)
  33. {
  34. parent::__construct();
  35. $this->noticeRule = $noticeRule;
  36. $this->rabbitMqUtil = $rabbitMqUtil;
  37. }
  38. /**
  39. * Execute the console command.
  40. *
  41. * @return mixed
  42. */
  43. public function handle()
  44. {
  45. $this->line("开始添加发送通知");
  46. $this->noticeRule
  47. ->where('notice_type', 0)
  48. ->where('notice_status', 0)
  49. ->where('send_time', '<', Carbon::now()->toDateTimeString())
  50. ->whereNotNUll('send_time')
  51. ->chunk(100, function($notices){
  52. foreach($notices as $notice){
  53. DB::beginTransaction();
  54. try{
  55. $notice->notice_status = 1;
  56. $noticeUsers = json_decode($notice->notice_users, true);
  57. if(isset($noticeUsers['category']) && $noticeUsers['category']){
  58. $uids = $this->getCategoryUids(json_encode($noticeUsers['category']));
  59. Log::debug('uids'.json_encode($uids));
  60. if(!$uids){
  61. DB::rollBack();
  62. Log::error('获取关注分类用户失败:');
  63. }
  64. $noticeUsers['category_uids'] = $uids;
  65. $notice->notice_users = json_encode($noticeUsers);
  66. }
  67. $notice->save();
  68. DB::commit();
  69. $this->rabbitMqUtil->push('add_notice_rule', $notice);
  70. Log::info('添加发送通知成功:'.$notice->id);
  71. }catch (QueryException $exception){
  72. DB::rollBack();
  73. Log::error('添加发送通知失败:'.$exception->getMessage());
  74. }
  75. }
  76. });
  77. $this->line("添加发送消息结束");
  78. }
  79. }