diff --git a/composer.json b/composer.json index b228feb..4ef3cb7 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "kakadu-dev/php-ijson-microservices", - "version": "1.1.4", + "version": "1.2.0", "description": "Package for create microservice architecture based on PHP.", "homepage": "https://github.com/kakadu-dev/php-ijson-microservices", "type": "library", diff --git a/src/Microservice.php b/src/Microservice.php index 6ec02c2..5beaaae 100644 --- a/src/Microservice.php +++ b/src/Microservice.php @@ -63,6 +63,9 @@ protected function __construct(string $name, array $options = [], $logDriver = f $this->name = $name; $this->options = array_merge($this->options, array_filter($options)); + // Detect SRV host + $this->expandSrv(); + MicroserviceException::$service = $name; if ($logDriver instanceof ILogDriver) { @@ -74,23 +77,29 @@ protected function __construct(string $name, array $options = [], $logDriver = f $this->_httpClient = $this->createHttpClient(); } - protected function __clone() - { - } - - public function __wakeup() - { - throw new \Exception("Cannot unserialize a microservice."); - } - /** - * Get microservice instance + * Detect SRV record and get dns record * - * @return Microservice + * @return void */ - public static function getInstance(): Microservice + private function expandSrv(): void { - return self::$_instance; + if (substr($this->options['ijson'], -4) !== '.srv') { + return; + } + + $part = explode('://', $this->options['ijson']); + $srvRecords = dns_get_record($part[1], DNS_SRV); + + // Sort + $priority = array_column($srvRecords, 'pri'); + $weight = array_column($srvRecords, 'weight'); + array_multisort($priority, SORT_ASC, $weight, SORT_ASC, $srvRecords); + + $host = $srvRecords[0]['target'] ?? null; + $port = $srvRecords[0]['port'] ?? null; + + $this->options['ijson'] = "$part[0]://$host:$port"; } /** @@ -107,6 +116,25 @@ private function createHttpClient(): HttpClient ]); } + protected function __clone() + { + } + + public function __wakeup() + { + throw new \Exception("Cannot unserialize a microservice."); + } + + /** + * Get microservice instance + * + * @return Microservice + */ + public static function getInstance(): Microservice + { + return self::$_instance; + } + /** * Create microservice *