网上说那些获取port的博客,大部分都是扎堆的xxxx。基本都不看源码的乱写
网上基本上就是用Environment @LocalServerPort @Value 来获取配置文件里的port ---- (md,spring boot基础知识你用在Spring cloud xxx,脑子有病) 这些只针对配置文件里写死的端口有效,但是在微服务中我们通常使用动态port,没法获取。
这里我分享另一种方法,针对Eueka为注册中心方法(其余的类似)
源码:
类EurekaAutoServiceRegistration中有这么一段源码
// only initialize if nonSecurePort is greater than 0 and it isn't already running // because of containerPortInitializer below if (!this.running.get() && this.registration.getNonSecurePort() > 0) { this.serviceRegistry.register(this.registration); this.context.publishEvent( new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig())); this.running.set(true); }
这里说是如果nonSecurePort比0大的时候,并且没有运行的时候在这里面注册,并且触发InstanceRegisterEvent(euerka客户端注册事件)事件,将注册服务配置信息传入。 debug模式下我们可以很清楚的看到里面的配置信息