Commit 3f929f96 authored by carlos's avatar carlos

服务注册修改

parent 88d40318
......@@ -8,6 +8,7 @@
namespace Meibuyu\Micro\Listener;
use Hyperf\Consul\Exception\ServerException;
use Hyperf\ServiceGovernance\Listener\RegisterServiceListener as BaseRegisterServiceListener;
class RegisterServiceListener extends BaseRegisterServiceListener
......@@ -30,7 +31,7 @@ class RegisterServiceListener extends BaseRegisterServiceListener
*/
$host = isset($server['local_ip']) ? $server['local_ip'] : $server['host'];
if (in_array($host, ['0.0.0.0', 'localhost'])) {
$host = $this->getInternalIp();
$host = $this->getRealInternalIp();
}
if (!filter_var($host, FILTER_VALIDATE_IP)) {
throw new \InvalidArgumentException(sprintf('Invalid host %s', $host));
......@@ -45,4 +46,58 @@ class RegisterServiceListener extends BaseRegisterServiceListener
return $result;
}
}
\ No newline at end of file
protected function getRealInternalIp()
{
if (method_exists(self::class, 'getInternalIp')) {
return $this->getInternalIp();
}
$ips = swoole_get_local_ip();
if (is_array($ips) && ! empty($ips)) {
return current($ips);
}
/** @var mixed|string $ip */
$ip = gethostbyname(gethostname());
if (is_string($ip)) {
return $ip;
}
throw new \RuntimeException('Can not get the internal IP.');
}
public function process(object $event)
{
$this->registeredServices = [];
$continue = true;
$env = $this->config->get('app_env');
while ($continue) {
try {
$services = $this->serviceManager->all();
$servers = $this->getServers();
foreach ($services as $serviceName => $serviceProtocols) {
foreach ($serviceProtocols as $paths) {
foreach ($paths as $path => $service) {
if (! isset($service['publishTo'], $service['server']) || $env == 'dev-mf') {
continue;
}
[$address, $port] = $servers[$service['server']];
switch ($service['publishTo']) {
case 'consul':
$this->publishToConsul($address, (int) $port, $service, $serviceName, $path);
break;
}
}
}
}
$continue = false;
} catch (ServerException $throwable) {
if (strpos($throwable->getMessage(), 'Connection failed') !== false) {
$this->logger->warning('Cannot register service, connection of service center failed, re-register after 10 seconds.');
sleep(10);
} else {
throw $throwable;
}
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment