SyncArticlesCommand.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare (strict_types = 1);
  3. namespace App\Command;
  4. use Hyperf\Command\Annotation\Command;
  5. use Swoole\Coroutine;
  6. use Hyperf\DbConnection\Db;
  7. use Hyperf\Elasticsearch\ClientBuilderFactory;
  8. use Psr\Container\ContainerInterface;
  9. use App\Service\DataSyncService;
  10. use Hyperf\Command\Command as HyperfCommand;
  11. use App\Service\ElasticsearchService;
  12. /**
  13. * @Command
  14. */
  15. class SyncArticlesCommand extends HyperfCommand
  16. {
  17. protected $dataSyncService;
  18. protected $elasticsearchService;
  19. public function __construct(ContainerInterface $container)
  20. {
  21. parent::__construct('sync:articles');
  22. $this->dataSyncService = $container->get(DataSyncService::class);
  23. $this->elasticsearchService = $container->get(ElasticsearchService::class);
  24. }
  25. public function configure()
  26. {
  27. parent::configure();
  28. $this->setName('sync:articles')
  29. ->setDescription('Synchronize articles to Elasticsearch');
  30. }
  31. public function handle()
  32. {
  33. Coroutine::create(function () {
  34. $this->line('========================= started.');
  35. // 检查索引是否存在
  36. $indexExists = $this->elasticsearchService->indexExists('articles');
  37. if (!$indexExists) {
  38. // 如果索引不存在,则创建索引
  39. try {
  40. $response = $this->elasticsearchService->createIndex();
  41. $this->line('Index created successfully: ' . json_encode($response));
  42. } catch (\Exception $e) {
  43. $this->error('Failed to create index: ' . $e->getMessage());
  44. return;
  45. }
  46. } else {
  47. $this->line('Index already exists.');
  48. }
  49. // 同步数据
  50. try {
  51. $this->dataSyncService->syncArticles();
  52. $this->line('Articles synchronization completed.');
  53. } catch (\Exception $e) {
  54. $this->error('Failed to synchronize articles: ' . $e->getMessage());
  55. }
  56. });
  57. $this->line('Articles synchronization started.');
  58. }
  59. }