[spring-cloud: 服务注册]-源码解析
扩展接口
ServiceRegistry
ServiceRegistry
接口定义了服务注册、注销、状态管理等基本操作,用于服务的生命周期管理。
public interface ServiceRegistry<R extends Registration> {void register(R registration);void deregister(R registration);void close();void setStatus(R registration, String status);<T> T getStatus(R registration);}
Registration
ServiceInstance
接口定义了服务实例的基本信息和行为,如获取服务ID、主机、端口、元数据等。
public interface Registration extends ServiceInstance {}
public interface ServiceInstance {default String getInstanceId() {return null;}String getServiceId();String getHost();int getPort();boolean isSecure();URI getUri();Map<String, String> getMetadata();default String getScheme() {return null;}}
RegistrationLifecycle
RegistrationLifecycle
接口定义了服务注册生命周期的各个钩子方法,用于在注册前后、停止前后执行自定义操作,并支持定义执行顺序。
public interface RegistrationLifecycle<R extends Registration> extends Ordered {int DEFAULT_ORDER = 0;void postProcessBeforeStartRegister(R registration);void postProcessAfterStartRegister(R registration);void postProcessBeforeStopRegister(R registration);void postProcessAfterStopRegister(R registration);default int getOrder() {return DEFAULT_ORDER;}}
RegistrationManagementLifecycle
RegistrationManagementLifecycle
接口扩展了 RegistrationLifecycle
,定义了管理服务注册的生命周期钩子方法,用于在管理服务注册的开始和停止前后执行自定义操作。
public interface RegistrationManagementLifecycle<R extends Registration> extends RegistrationLifecycle<R> {void postProcessBeforeStartRegisterManagement(R registrationManagement);void postProcessAfterStartRegisterManagement(R registrationManagement);void postProcessBeforeStopRegisterManagement(R registrationManagement);void postProcessAfterStopRegisterManagement(R registrationManagement);}
核心代码
AutoServiceRegistration
public interface AutoServiceRegistration {}
AbstractAutoServiceRegistration
public abstract class AbstractAutoServiceRegistration<R extends Registration> implements AutoServiceRegistration, ApplicationContextAware, ApplicationListener<WebServerInitializedEvent> {private static final Log logger = LogFactory.getLog(AbstractAutoServiceRegistration.class);private final ServiceRegistry<R> serviceRegistry;private final boolean autoStartup = true;private final AtomicBoolean running = new AtomicBoolean(false);private final int order = 0;private final AtomicInteger port = new AtomicInteger(0);private ApplicationContext context;// context.getEnvironment()private Environment environment;private AutoServiceRegistrationProperties properties;private List<RegistrationManagementLifecycle<R>> registrationManagementLifecycles = new ArrayList<>();private List<RegistrationLifecycle<R>> registrationLifecycles = new ArrayList<>();protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry, AutoServiceRegistrationProperties properties) {this.serviceRegistry = serviceRegistry;this.properties = properties;}@Override@SuppressWarnings("deprecation")public void onApplicationEvent(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 belowif (!this.running.get()) {this.context.publishEvent(new InstancePreRegisteredEvent(this, getRegistration()));registrationLifecycles.forEach(registrationLifecycle -> registrationLifecycle.postProcessBeforeStartRegister(getRegistration()));register();this.registrationLifecycles.forEach(registrationLifecycle -> registrationLifecycle.postProcessAfterStartRegister(getRegistration()));if (shouldRegisterManagement()) {this.registrationManagementLifecycles.forEach(registrationManagementLifecycle -> registrationManagementLifecycle.postProcessBeforeStartRegisterManagement(getManagementRegistration()));this.registerManagement();registrationManagementLifecycles.forEach(registrationManagementLifecycle -> registrationManagementLifecycle.postProcessAfterStartRegisterManagement(getManagementRegistration()));}this.context.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));this.running.compareAndSet(false, true);}}protected boolean shouldRegisterManagement() {if (this.properties == null || this.properties.isRegisterManagement()) {return getManagementPort() != null && ManagementServerPortUtils.isDifferent(this.context);}return false;}protected abstract boolean isEnabled();@PreDestroypublic void destroy() {stop();}protected abstract R getRegistration();protected abstract R getManagementRegistration();protected void register() {this.serviceRegistry.register(getRegistration());}protected void registerManagement() {R registration = getManagementRegistration();if (registration != null) {this.serviceRegistry.register(registration);}}protected void deregister() {this.serviceRegistry.deregister(getRegistration());}protected void deregisterManagement() {R registration = getManagementRegistration();if (registration != null) {this.serviceRegistry.deregister(registration);}}public void stop() {if (this.getRunning().compareAndSet(true, false) && isEnabled()) {this.registrationLifecycles.forEach(registrationLifecycle -> registrationLifecycle.postProcessBeforeStopRegister(getRegistration()));deregister();this.registrationLifecycles.forEach(registrationLifecycle -> registrationLifecycle.postProcessAfterStopRegister(getRegistration()));if (shouldRegisterManagement()) {this.registrationManagementLifecycles.forEach(registrationManagementLifecycle -> registrationManagementLifecycle.postProcessBeforeStopRegisterManagement(getManagementRegistration()));deregisterManagement();this.registrationManagementLifecycles.forEach(registrationManagementLifecycle -> registrationManagementLifecycle.postProcessAfterStopRegisterManagement(getManagementRegistration()));}this.serviceRegistry.close();}}}
自动注册
1. EnableDiscoveryClient
@EnableDiscoveryClient
注解用于启用服务发现客户端功能,并通过 autoRegister
属性控制是否自动注册本地服务到服务注册中心。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(EnableDiscoveryClientImportSelector.class)
public @interface EnableDiscoveryClient {/*** If true, the ServiceRegistry will automatically register the local server.* @return - {@code true} if you want to automatically register.*/boolean autoRegister() default true;}
EnableDiscoveryClientImportSelector
EnableDiscoveryClientImportSelector
类根据 @EnableDiscoveryClient
注解的配置动态决定是否导入服务自动注册配置,灵活控制服务的自动注册行为。
@Order(Ordered.LOWEST_PRECEDENCE - 100)
public class EnableDiscoveryClientImportSelector extends SpringFactoryImportSelector<EnableDiscoveryClient> {@Overridepublic String[] selectImports(AnnotationMetadata metadata) {String[] imports = super.selectImports(metadata);AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));boolean autoRegister = attributes.getBoolean("autoRegister");if (autoRegister) {List<String> importsList = new ArrayList<>(Arrays.asList(imports));importsList.add("org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");imports = importsList.toArray(new String[0]);}else {Environment env = getEnvironment();if (env instanceof ConfigurableEnvironment configEnv) {LinkedHashMap<String, Object> map = new LinkedHashMap<>();map.put("spring.cloud.service-registry.auto-registration.enabled", false);MapPropertySource propertySource = new MapPropertySource("springCloudDiscoveryClient", map);configEnv.getPropertySources().addLast(propertySource);}}return imports;}@Overrideprotected boolean isEnabled() {return getEnvironment().getProperty("spring.cloud.discovery.enabled", Boolean.class, Boolean.TRUE);}@Overrideprotected boolean hasDefaultFactory() {return true;}}
3. AutoServiceRegistrationAutoConfiguration
自动配置类,用于在应用启动时检查并确保 AutoServiceRegistration
组件是否存在。如果启用了 failFast
配置且没有找到 AutoServiceRegistration
bean,它会抛出 IllegalStateException
,防止应用继续启动。
@Configuration(proxyBeanMethods = false)
@Import(AutoServiceRegistrationConfiguration.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public class AutoServiceRegistrationAutoConfiguration implements InitializingBean {@Autowired(required = false)private AutoServiceRegistration autoServiceRegistration;@Autowiredprivate AutoServiceRegistrationProperties properties;@Overridepublic void afterPropertiesSet() {if (this.autoServiceRegistration == null && this.properties.isFailFast()) {throw new IllegalStateException("Auto Service Registration has " + "been requested, but there is no AutoServiceRegistration bean");}}}
4. AutoServiceRegistrationConfiguration
服务注册配置类,启用了 AutoServiceRegistrationProperties
属性配置,负责配置自动注册的相关设置,确保自动注册功能按配置启用或禁用。
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public class AutoServiceRegistrationConfiguration {}
5. AutoServiceRegistrationProperties
配置属性类,存储与自动注册相关的属性,如是否启用自动注册、是否将管理服务作为服务注册、是否在缺少 AutoServiceRegistration
时快速失败等。
@ConfigurationProperties("spring.cloud.service-registry.auto-registration")
public class AutoServiceRegistrationProperties {/** Whether service auto-registration is enabled. Defaults to true. */private boolean enabled = true;/** Whether to register the management as a service. Defaults to true. */private boolean registerManagement = true;/*** Whether startup fails if there is no AutoServiceRegistration. Defaults to false.*/private boolean failFast = false;// ...
}