名字服务Polaris之Spring中服务注册原理

简介

Polaris名字服务作为服务治理的一员,具有服务注册,服务发现,路由等相关特性。广泛应用于微服务开发中。

在现代微服务架构中,对于服务发布来说,需要有灰度发布、蓝绿部署、金丝雀部署等等场景,那么对于一个系统来说,怎么做呢?这对于一个服务治理框架来说,支持各种各样的路由策略是必要的。

Polaris就具有非常灵活的路由转发功能:

1. 支持常规的url路由

2. 支持header路由

3. 支持各种自定义规则路由

服务注册

今天我们要说的是Polaris的服务注册机制,其实跟其他的服务治理框架没啥区别,原理都差不多。这里以Spring框架来举例说明。

下面从源码分析开始:

public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistration


北极星继承了springcloud的服务注册类

public abstract class AbstractAutoServiceRegistration
      implements AutoServiceRegistration, ApplicationContextAware,
      ApplicationListener

AbstractAutoServiceRegistration这个类实现了ApplicationListener接口。
该接口监听了WebServerInitializedEvent事件

public void onApplicationEvent(WebServerInitializedEvent event) {
   bind(event);
}


@Deprecated
public void bind(WebServerInitializedEvent event) {
   ApplicationContext context = event.getApplicationContext();
   if (context instanceof ConfigurableWebServerApplicationContext) {
      if ("management".equals(((ConfigurableWebServerApplicationContext) context)
            .getServerNamespace())) {
         return;
      }
   }
   this.port.compareAndSet(0, event.getWebServer().getPort());
   this.start();
}


public void start() {
   if (!isEnabled()) {
      if (logger.isDebugEnabled()) {
         logger.debug("Discovery Lifecycle disabled. Not starting");
      }
      return;
   }


   // only initialize if nonSecurePort is greater than 0 and it isn't already running
   // because of containerPortInitializer below
   if (!this.running.get()) {
      this.context.publishEvent(
            new InstancePreRegisteredEvent(this, getRegistration()));
      register();
      if (shouldRegisterManagement()) {
         registerManagement();
      }
      this.context.publishEvent(
            new InstanceRegisteredEvent<>(this, getConfiguration()));
      this.running.compareAndSet(false, true);
   }


}

当web服务启动完成时就会回调执行上面的那些方法,最终就会走到register方法中,而北极星覆写了该方法:

@Override
protected void register() {
   if (!this.registration.isRegisterEnabled()) {
      LOG.debug("Registration disabled.");
      return;
   }
   if (this.registration.getPort() <= 0) {
      this.registration.setPort(getPort().get());
   }
   super.register();
}

该方法根据bootstrap.yml中的配置,向北极星服务器进行注册

你可能感兴趣的:(spring,java,后端,开发语言)