外部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;
    }

}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值