外部tomcat使用nacos如何注册
我的微服务注册不了
项目环境
spring boot 2.16
spring cloud alibaba 2.1.1
nacos-server 1.0
当项目在tomcat里启动以后,在nacos控制台并没有看到服务实例相关信息。我才意识到,可能在tomcat容器中运行的项目并不能向nacos注册
为什么会这样
抱着这个疑问,我去github官方仓库对issues进行了查找,发现很早以前就有这样的问题。问题的原因说是可能因为spring boot 达成的war包会有额外配置,换而言之当你使用外部的tomcat时候,因为缺少响应的配置,所以nacos不会自动注册。
解决方案
其实这个issues已经有了解决方案 #341
主要是以下代码
@Component
public class NacosConfig implements ApplicationRunner {
@Autowired(required = false)
private NacosAutoServiceRegistration registration;
@Value("${server.port}")
Integer port;
@Override
public void run(ApplicationArguments args) {
if (registration != null && port != null) {
registration.setPort(port);
registration.start();
}
}
}
分析以下这个类,主要是实现了ApplicationRunner接口,当项目启动后,查询nacos的注册bean是否存在,如果存在的话,设置一下端口,进行注册行为。
好,我是按照这样写的,但是发现启动以后注册的信息有问题。
注册端口和实际端口不一致
打开nacos控制台,之前没有的实例信息出现了,但是新的问题也跟着出现了。
端口使用的是我在配置文件里写的端口,而真正的tomcat端口是另外一个。
这个时候我们发现,这样的写法是不行的。之后,在网上再次进行了搜索,重新修改了配置类,才最终实现了外部tomcat注册nacos的功能
最终效果
/**
* 让外部tomcat中的程序也能向nacos注册
* @author shichenyang
*/
@Configuration
public class NacosConfig implements ApplicationRunner {
@Autowired(required = false)
private NacosAutoServiceRegistration registration;
@Value("${server.port}")
Integer port;
@Override
public void run(ApplicationArguments args) throws Exception {
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("org.apache.coyote.http11.Http11AprProtocol")));
String port = objectNames.iterator().next().getKeyProperty("port");
return port;
}
}