我们需要通过启动代码在客户端应用程序上设置Eureka服务器URL,但是似乎没有办法。

我们提供了一种机制,用于通过UDP多播广播在网络上发现Eureka服务器。服务器将有关Eureka服务器运行的IP地址和端口的信息发送回客户端。但是我们不知道如何通过代码在Eureka客户端应用程序中设置此URL。看来,设置Eureka服务器URL的唯一方法是application.property文件中的属性eureka.client.serviceUrl.defaultZone

    // Server - start a new thread with UDP packet detection and reply mechanism
    LocationService.listenAndReplyToEurekaClients(thisServerPort);

    // Server - application start
    SpringApplication.run(EurekaServerApplication.class, args);




    // Client - send UDP packet and receive reply with Eureka server IP and port
    Response response  = LocationService.findEurekaServerAddress(5, 3, TimeUnit.SECONDS);

    var hostProtocol = "http";

    var eurekaUrl = new URL(
            hostProtocol,
            response.getEurekaAddress(),
            response.getEurekaPort(),"").toString();



我们想将此eurekaURL设置为客户端,然后再开始向Eureka服务器注册。

最佳答案

在这种情况下,我们可以做以下事情-

扩展EurekaClientConfigBean并重写getEurekaServerServiceUrls方法。方法返回String列表,该列表不过是eureka实例的所有URL的列表。您需要在响应中设置具有IP和端口的URL。

稍后使用-DiscoveryClient(ApplicationInfoManager applicationInfoManager,EurekaClientConfig配置)创建发现客户端。 (肯定是一个Bean)。

那应该工作。

您可以将ApplicationInfoManager创建为-

ApplicationInfoManager applicationInfoManager =
        initializeApplicationInfoManager(webAppInstanceConfig);


其中WebAppInstanceConfig是-

class WebAppInstanceConfig extends MyDataCenterInstanceConfig {// Override all the needed properties from MyDataCenterInstanceConfig}

10-07 12:40