发现和注册 Spring Cloud 服务Discover and register your Spring Cloud services

服务发现是基于微服务的体系结构的关键要求。Service Discovery is a key requirement for a microservice-based architecture. 手动配置每个客户端会耗费时间,并引入人为错误的可能性。Configuring each client manually takes time and introduces the possibility of human error. Azure Spring Cloud 服务注册表解决了这一问题。Azure Spring Cloud Service Registry solves this problem. 配置后,服务注册表服务器将为应用程序的微服务控制服务注册和发现。Once configured, a Service Registry server will control service registration and discovery for your application's microservices. 服务注册表服务器维护已部署的微服务的注册表、启用客户端负载平衡,并从客户端分离服务提供程序,而无需依赖 DNS。The Service Registry server maintains a registry of the deployed microservices, enables client-side load-balancing, and decouples service providers from clients without relying on DNS.

使用 Spring Cloud 服务注册表注册应用程序Register your application using Spring Cloud Service Registry

必须在应用程序的 pom.xml 文件中包含若干依赖项,应用程序才能使用 Spring Cloud 服务注册表管理服务注册和发现。Before your application can manage service registration and discovery using Spring Cloud Service Registry, several dependencies must be included in the application's pom.xml file. 将 spring-cloud-starter-netflix-eureka-client 和 spring-cloud-starter-azure-spring-cloud-client 的依赖项添加到 pom.xml Include dependencies for spring-cloud-starter-netflix-eureka-client and spring-cloud-starter-azure-spring-cloud-client to your pom.xml

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>spring-cloud-starter-azure-spring-cloud-client</artifactId>
        <version>2.1.0</version>
    </dependency>

更新顶级类Update the top level class

最后,向应用程序的顶级类添加注释Finally, we add an annotation to the top level class of your application

   package foo.bar;

   import org.springframework.boot.SpringApplication;
   import org.springframework.cloud.client.SpringCloudApplication;

   @SpringCloudApplication
   public class DemoApplication {
       public static void main(String... args) {
           SpringApplication.run(DemoApplication.class, args);
       }
   }

Spring Cloud 服务注册表服务器终结点将作为环境变量注入到应用程序中。The Spring Cloud Service Registry server endpoint will be injected as an environment variable in your application. 现在,微服务将可以自行注册到服务注册表服务器并发现其他依赖性微服务。Microservices will now be able to register themselves with the Service Registry server and discover other dependent microservices.

请注意,将更改从服务器传播到所有微服务可能需要几分钟时间。Note that it can take a few minutes for the changes to propagate from the server to all microservices.