apollo.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. $this->line('apollo配置服务开启');
  50. $restart = true; //失败自动重启
  51. do {
  52. $error = $this->apollo->start(function () {
  53. $list = glob($this->save_dir . DIRECTORY_SEPARATOR . 'apolloConfig.*');
  54. $apollo = [];
  55. foreach ($list as $l) {
  56. $config = require $l;
  57. if (is_array($config) && isset($config['configurations'])) {
  58. $apollo = array_merge($apollo, $config['configurations']);
  59. }
  60. }
  61. if (!$apollo) {
  62. Log::error('Load Apollo Config Failed, no config available');
  63. }
  64. $tpl = file_get_contents($this->config_tpl);
  65. foreach ($apollo as $key =>$value){
  66. $tpl = str_replace('{'.$key.'}',$value,$tpl);
  67. }
  68. file_put_contents($this->config_file,$tpl);
  69. }); //此处传入回调
  70. if ($error) {
  71. Log::info("Apollo Hand error :" . $error);
  72. }
  73. } while ($error && $restart);
  74. }
  75. }