apollo.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Log;
  5. use Org\Multilinguals\Apollo\Client\ApolloClient;
  6. class Apollo extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'apollo';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Apollo配置服务';
  20. private $apollo;
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. $this->save_dir = storage_path('apollo');
  30. $this->config_tpl = config_path() . '/customer.tpl';
  31. $this->config_file = config_path() . '/customer.php';
  32. $this->apollo = new ApolloClient(
  33. config('apollo.config_server'),
  34. config('apollo.app_id'),
  35. config('apollo.namespaces')
  36. );
  37. $this->apollo->save_dir = $this->save_dir;
  38. if(!is_dir($this->save_dir)){
  39. mkdir($this->save_dir);
  40. }
  41. }
  42. /**
  43. * Execute the console command.
  44. *
  45. * @return mixed
  46. */
  47. public function handle()
  48. {
  49. Log::debug('apollo test');
  50. $this->line('apollo配置服务开启');
  51. $restart = true; //失败自动重启
  52. do {
  53. $error = $this->apollo->start(function () {
  54. $list = glob($this->save_dir . DIRECTORY_SEPARATOR . 'apolloConfig.*');
  55. $apollo = [];
  56. foreach ($list as $l) {
  57. $config = require $l;
  58. if (is_array($config) && isset($config['configurations'])) {
  59. $apollo = array_merge($apollo, $config['configurations']);
  60. }
  61. }
  62. if (!$apollo) {
  63. Log::error('Load Apollo Config Failed, no config available');
  64. }
  65. $tpl = file_get_contents($this->config_tpl);
  66. foreach ($apollo as $key =>$value){
  67. $tpl = str_replace('{'.$key.'}',$value,$tpl);
  68. }
  69. file_put_contents($this->config_file,$tpl);
  70. }); //此处传入回调
  71. if ($error) {
  72. Log::info("Apollo Hand error :" . $error);
  73. }
  74. } while ($error && $restart);
  75. }
  76. }