NacosDriver.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\ConfigNacos;
  12. use Hyperf\Collection\Arr;
  13. use Hyperf\ConfigCenter\AbstractDriver;
  14. use Hyperf\ConfigCenter\Contract\ClientInterface as ConfigClientInterface;
  15. use Hyperf\Nacos\Module;
  16. use Hyperf\Nacos\Protobuf\ListenHandler\ConfigChangeNotifyRequestHandler;
  17. use Hyperf\Nacos\Protobuf\Response\ConfigQueryResponse;
  18. use Psr\Container\ContainerInterface;
  19. class NacosDriver extends AbstractDriver
  20. {
  21. protected string $driverName = 'nacos';
  22. /**
  23. * @var Client
  24. */
  25. protected ConfigClientInterface $client;
  26. public function __construct(ContainerInterface $container)
  27. {
  28. parent::__construct($container);
  29. $this->client = $container->get(ClientInterface::class);
  30. }
  31. public function createMessageFetcherLoop(): void
  32. {
  33. if (! $this->config->get('config_center.drivers.nacos.client.grpc.enable', false)) {
  34. parent::createMessageFetcherLoop();
  35. return;
  36. }
  37. $application = $this->client->getClient();
  38. $listeners = $this->config->get('config_center.drivers.nacos.listener_config', []);
  39. foreach ($listeners as $key => $item) {
  40. $dataId = $item['data_id'];
  41. $group = $item['group'];
  42. $tenant = $item['tenant'] ?? '';
  43. $type = $item['type'] ?? null;
  44. $client = $application->grpc->get($tenant, Module::CONFIG);
  45. $client->listenConfig($group, $dataId, new ConfigChangeNotifyRequestHandler(function (ConfigQueryResponse $response) use ($key, $type) {
  46. $config = $this->client->decode($response->getContent(), $type);
  47. $prevConfig = $this->config->get($key, []);
  48. if ($config !== $prevConfig) {
  49. $this->syncConfig(
  50. [$key => $config],
  51. [$key => $prevConfig],
  52. );
  53. }
  54. }));
  55. }
  56. foreach ($application->grpc->moduleClients(Module::CONFIG) as $client) {
  57. $client->listen();
  58. }
  59. }
  60. protected function updateConfig(array $config): void
  61. {
  62. $root = $this->config->get('config_center.drivers.nacos.default_key');
  63. foreach ($config as $key => $conf) {
  64. if (is_int($key)) {
  65. $key = $root;
  66. }
  67. if (is_array($conf) && $this->config->get('config_center.drivers.nacos.merge_mode') === Constants::CONFIG_MERGE_APPEND) {
  68. $conf = Arr::merge($this->config->get($key, []), $conf);
  69. }
  70. $this->config->set($key, $conf);
  71. }
  72. }
  73. }