Springboot War包部署下nacos无法注册问题
如果需要解决方法,请直接看9. 如何在WAR包部署下成功注册nacos部分
1. @EnableDiscoveryClient的使用
在项目中需要使用nacos进行服务治理时,需要在启动类上添加该注解来实现服务的自动注册
/**
* Annotation to enable a DiscoveryClient implementation.
* @author Spencer Gibb
*/
@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;
}
autoRegister默认是注册的,引入EnableDiscoveryClientImportSelector.class
2. EnableDiscoveryClientImportSelector类的作用
首先将源码贴出来,该类继承SpringFactoryImportSelector(用来选择与泛型相关的配置,加载其相应实现)
/**
* @author Spencer Gibb
*/
@Order(Ordered.LOWEST_PRECEDENCE - 100)
public class EnableDiscoveryClientImportSelector
extends SpringFactoryImportSelector<EnableDiscoveryClient> {
@Override
public 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 (ConfigurableEnvironment.class.isInstance(env)) {
ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
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;
}
@Override
protected boolean isEnabled() {
return getEnvironment().getProperty("spring.cloud.discovery.enabled",
Boolean.class, Boolean.TRUE);
}
@Override
protected boolean hasDefaultFactory() {
return true;
}
}
1.在selectImports(AnnotationMetadata)方法中获取@EnableDiscoveryClient中的autoRegister参数,如过为True则将
org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration加入加载列表中。
2.当autoRegister=false时,设spring.cloud.service-registry.auto-registration.enabled=false,这样跟注册相关的类将不会自动装配,因为自动注册相关的类都有一个条件装配@ConditionalOnProperty(value ="spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)。
3.AutoServiceRegistrationConfiguration
@Configuration
@EnableConfigurationProperties(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public class AutoServiceRegistrationConfiguration {
}
@ConditionOnProperty为条件装配,只有spring.cloud.service-registry.auto-registration.enabled=true时才装配。
该类更像是一个信号量,用来若其加载则会加载其后的那些注册类
4.NacosDiscoveryAutoConfiguration
/**
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@Configuration
@EnableConfigurationProperties
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
AutoServiceRegistrationAutoConfiguration.class })
public class NacosDiscoveryAutoConfiguration {
@Bean
public NacosServiceRegistry nacosServiceRegistry(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosServiceRegistry(nacosDiscoveryProperties);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosRegistration nacosRegistration(
NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
return new NacosRegistration(nacosDiscoveryProperties, context);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosAutoServiceRegistration nacosAutoServiceRegistration(
NacosServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
return new NacosAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
}
}
该类的类加载条件为
@ConditionalOnNacosDiscoveryEnabled即配置中spring.cloud.nacos.discovery.enabled=true
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) 对应项目中是否使用到@EnableDiscoveryClient且其autoRegistry是否为true。
加载顺序为@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class,AutoServiceRegistrationAutoConfiguration.class })
意味着若AutoServiceRegistrationConfiguration.class,AutoServiceRegistrationAutoConfiguration.class加载失败则不进行该类的加载。
同时,在该类中创建NacosServiceRegistry,NacosRegistration,NacosAutoServiceRegistration三个类,后续的注册调用主要依赖于这三个类进行。
5. NacosServiceRegistry
该类主要实现org.springframework.cloud.client.serviceregistry.ServiceRegistry中的方法
如void register(R registration);方法和void deregister(R registration);方法。其中register中通过层层调用,通过api方式请求nacos的服务。
这里的R泛型的策略是
ServiceRegistry接口
/**
* Contract to register and deregister instances with a Service Registry.
*
*/
public interface ServiceRegistry<R extends Registration> {
/**
* Registers the registration. A registration typically has information about an
* instance, such as its hostname and port.
* @param registration registration meta data
*/
void register(R registration);
/**
* Deregisters the registration.
* @param registration registration meta data
*/
void deregister(R registration);
/**
* Closes the ServiceRegistry. This is a lifecycle method.
*/
void close();
/**
* Sets the status of the registration. The status values are determined by the
* individual implementations.
* @param registration The registration to update.
* @param status The status to set.
* @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
*/
void setStatus(R registration, String status);
/**
* Gets the status of a particular registration.
* @param registration The registration to query.
* @param <T> The type of the status.
* @return The status of the registration.
* @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
*/
<T> T getStatus(R registration);
}
6. NacosRegistration
该类主要用来做注册信息的管理实现了Registration, ServiceInstance接口
7. NacosAutoServiceRegistration
该类主要用来调用NacosServiceRegistry中的registry方法进行注册
public class NacosAutoServiceRegistration
extends AbstractAutoServiceRegistration<Registration> {
private static final Logger log = LoggerFactory
.getLogger(NacosAutoServiceRegistration.class);
private NacosRegistration registration;
public NacosAutoServiceRegistration(ServiceRegistry<Registration> serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties);
this.registration = registration;
}
@Deprecated
public void setPort(int port) {
getPort().set(port);
}
@Override
protected NacosRegistration getRegistration() {
if (this.registration.getPort() < 0 && this.getPort().get() > 0) {
this.registration.setPort(this.getPort().get());
}
Assert.isTrue(this.registration.getPort() > 0, "service.port has not been set");
return this.registration;
}
@Override
protected NacosRegistration getManagementRegistration() {
return null;
}
@Override
protected void register() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
log.debug("Registration disabled.");
return;
}
if (this.registration.getPort() < 0) {
this.registration.setPort(getPort().get());
}
super.register();
}
@Override
protected void registerManagement() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
return;
}
super.registerManagement();
}
@Override
protected Object getConfiguration() {
return this.registration.getNacosDiscoveryProperties();
}
@Override
protected boolean isEnabled() {
return this.registration.getNacosDiscoveryProperties().isRegisterEnabled();
}
@Override
@SuppressWarnings("deprecation")
protected String getAppName() {
String appName = registration.getNacosDiscoveryProperties().getService();
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
}
}
该类中的register()方法最终会调用super.register();
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 boolean autoStartup = true;
private AtomicBoolean running = new AtomicBoolean(false);
private int order = 0;
private ApplicationContext context;
private Environment environment;
private AtomicInteger port = new AtomicInteger(0);
private AutoServiceRegistrationProperties properties;
@Deprecated
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry,
AutoServiceRegistrationProperties properties) {
this.serviceRegistry = serviceRegistry;
this.properties = properties;
}
protected ApplicationContext getContext() {
return this.context;
}
@Override
@SuppressWarnings("deprecation")
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();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
this.environment = this.context.getEnvironment();
}
@Deprecated
protected Environment getEnvironment() {
return this.environment;
}
@Deprecated
protected AtomicInteger getPort() {
return this.port;
}
public boolean isAutoStartup() {
return this.autoStartup;
}
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);
}
}
public void stop() {
if (this.getRunning().compareAndSet(true, false) && isEnabled()) {
deregister();
if (shouldRegisterManagement()) {
deregisterManagement();
}
this.serviceRegistry.close();
}
}
}
该类继承了一个springboot的监听ApplicationListener器用来监听WebServerInitializedEvent该事件。
当该事件完成后将调用onApplicationEvent()方法,并调用bind(WebServerInitializedEvent)方法。
在bind(WebServerInitializedEvent)方法中调用start()方法,并在start()方法中调用register()方法。
private final ServiceRegistry<R> serviceRegistry;
@Deprecated
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry,
AutoServiceRegistrationProperties properties) {
this.serviceRegistry = serviceRegistry;
this.properties = properties;
}
protected void register() {
this.serviceRegistry.register(getRegistration());
}
其中ServiceRegistry其实现类就是NacosServiceRegistry
8.WebServerInitializedEvent
该事件将在应用上下文完成刷新并准备好之后发布。主要用来获取正在运行的服务器本地端口。
public abstract class WebServerInitializedEvent extends ApplicationEvent {
protected WebServerInitializedEvent(WebServer webServer) {
super(webServer);
}
/**
* Access the {@link WebServer}.
* @return the embedded web server
获取嵌入式的web服务器(即SpringBoot中内置的tomcat)
*/
public WebServer getWebServer() {
return getSource();
}
/**
* Access the application context that the server was created in. Sometimes it is
* prudent to check that this matches expectations (like being equal to the current
* context) before acting on the server itself.
* @return the applicationContext that the server was created from
获取服务创建时的上下文。有时会谨慎的检查配置是否复合预期(如 正在作用的是否是当前上下文)
*/
public abstract WebServerApplicationContext getApplicationContext();
/**
* Access the source of the event (an {@link WebServer}).
* @return the embedded web server
访问事件源
*/
@Override
public WebServer getSource() {
return (WebServer) super.getSource();
}
}
可以看到该类主要是获取Springboot内置的tomcat端口。当使用外置tomcat时,该事件并不能获取到对应的服务信息。所以也无法在nacos中注册成功。
9. 如何在WAR包部署下成功注册nacos
实现ApplicationRunner接口,在应用启动成功后完成某些初始化工作。
@Component
public class NacosConfig implements ApplicationRunner {
@Autowired(required = false)
private NacosAutoServiceRegistration registration;
@Value("${baseConfig.nacos.port}")
Integer port;
@Override
public void run(ApplicationArguments args) {
if (registration != null && port != null) {
Integer tomcatPort = port;
try {
tomcatPort = new Integer(getTomcatPort());
} catch (Exception e) {
e.printStackTrace();
}
registration.setPort(tomcatPort);
registration.start();
}
}
/**
* 获取外部tomcat端口
*/
public String getTomcatPort() throws Exception {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String port = objectNames.iterator().next().getKeyProperty("port");
return port;
}
}
实现一个监听
@Component
public class NacosListener implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
String property = event.getApplicationContext().getEnvironment().getProperty("server.port");
registration.setPort(Integer.valueOf(property));
nacosAutoServiceRegistration.start();
}
}
@EventListener(ApplicationReadyEvent.class)
public void onWebServerReady(ApplicationReadyEvent event) {
String property = event.getApplicationContext().getEnvironment().getProperty("server.port");
registration.setPort(Integer.valueOf(property));
nacosAutoServiceRegistration.start();
}
参考地址:
实现ApplicationRunner接口:https://my.oschina.net/yuhuashang/blog/3086167
源码:127.0.0.1
@EnableDiscoveryClient 注解如何实现服务注册与发现:https://blog.csdn.net/z694644032/article/details/96706593
Springboot War包部署下nacos无法注册问题的更多相关文章
- SpringBoot war包部署到Tomcat服务器
(1)pom.xml文件修改<packaging>war</packaging>,默认是jar包,<build>节点中增加<finalName>spri ...
- spring-boot war包部署(二)
环境 jdk 8 tomcat 8.5 sts 4.4.2 maven 3.6.1 背景 有时候,服务器已经有了,我们必须要使用 war 包进行部署,所以需要 spring boot 支持打包和部署成 ...
- SpringBoot之打成war包部署到Tomcat
正常情况下SpringBoot项目是以jar包的形式,正常情况下SpringBoot项目是以jar包的形式,并且SpringBoot是内嵌Tomcat服务器,所以每次重新启动都是用的新的Tomcat服 ...
- SpringBoot项目war包部署
服务部署 记录原因 将本地SpringBoot项目通过war包部署到虚拟机中,验证服务器部署. 使用war包是为了方便替换配置文件等. 工具 对象 版本 Spring Boot 2.4.0 VMwar ...
- springboot 学习之路 5(打成war包部署tomcat)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- Windows下war包部署到Linux下Tomcat出现的问题
最近,将Windows下开发的war包部署到Linux下的Tomcat时报了一个错误:tomcat error in opening zip file.按理说,如果正常,当把war包复制到webapp ...
- 【Spring Boot项目】Win7+JDK8+Tomcat8环境下的War包部署
一.pom.xml及启动类修改 pom.xml Step1:指定打包类型 <!-- 打包类型 jar 或 war --> <packaging>war</packagin ...
- springboot项目war包部署及出现的问题Failed to bind properties under 'mybatis.configuration.mapped-statements[0].
1.修改pom文件 修改打包方式 为war: 添加tomcat使用范围,provided的意思即在发布的时候有外部提供,内置的tomcat就不会打包进去 <groupId>com.scho ...
- Web项目打成war包部署Tomcat时运行startup.bat直接闪退部署失败解决方案
即上篇通过将web项目打成war包部署到Tomcat服务器,解决mysql问题后,又出现了新问题,真是一波三折,所以将解决过程分享给大家,希望能帮助到小伙伴们~ 将打好的war包拷贝到Tomcat的w ...
随机推荐
- ReactiveCocoa详解
最近看了大神的博客后,感觉该对ReactiveCocoa做一个了断了. 首先大致的对以下关于ReactiveCocoa内容做一个简单的总结,其他的后续更新 1.ReactiveCocoa的操作思想 2 ...
- Java类加载器初识
类加载器基本概念 类加载器(class loader)用来加载 Java 类到 Java 虚拟机中.一般来说,Java虚拟机使用Java类的方式如下:Java 源程序(.java 文件)在经过 Jav ...
- final、finally、 finalize区别
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11444366.html final final可以用来修饰类.方法.变量,分别有不同的意义,final ...
- 【leetcode】1080. Insufficient Nodes in Root to Leaf Paths
题目如下: Given the root of a binary tree, consider all root to leaf paths: paths from the root to any l ...
- python基本数据预处理语法函数(2)
1.字符串格式化方法format的用法: < ^ > #分别为左对齐.居中.右对齐 '{:>18,.2f}'.format(70305084.0) #:冒号+空白填充+右对齐+固定宽 ...
- DGA域名检测
一.DGA域名原理 僵尸网络(Botnet):互联网上在蠕虫.木马.后门工具等,传统恶意代码形态的基础上发展.融合而产生的一种新型攻击方法. DNS(Domain Name System) :基于 U ...
- 使用WebAPI流式传输大文件(在IIS上大于2GB)
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- locate 定位配置文件
[root@VM_58_118_centos syhuo.net]# locate redis.conf /etc/redis.conf /etc/redis.conf_bak_20191008 /u ...
- 《Javascript设计模式与开发实践》关于设计模式典型代码的整理:单例模式、策略模式、代理模式、迭代器模式、发布-订阅模式、命令模式、组合模式
1.单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点. 使用闭包封装私有变量// 使用闭包创建单例var user = (function () { var _name = 'sven' ...
- [CSP-S模拟测试94]题解
A.凉宫春日的忧郁 高精硬上似乎跑不过,其实可以都取个$log$.那么只需要比较$y\times log ^x$和$\sum \limits _{i=1}^y log^i$就好了. #include& ...