Spring cloud Eureka 服务治理(搭建服务注册中心)

时间:2022-12-02 16:42:37

服务之类是微服务架构中最为核心的基础模块,它主要用来实现各个微服务实例的自动化注册和发现。

 

1. 服务注册

在服务治理框架中,通常会构建一个注册中心,每个服务单元向注册中心登记自己提供的服务,将主机、端口、版本号、通信协议等一些

附加信息告知服务中心,注册中心按服务名分类组织服务清单。

 

2. 服务发现

由于在服务治理框架下运作,服务间的调用不在通过指定具体的地址实例地址来实现,而是通过想服务名发起请求调用。

 

使用Spring Cloud Eureka 来搭建服务注册中心

 

<1>. 首先我们通过Spring Initializer 创建一个基础工程,命名为eureka-server

Spring cloud Eureka 服务治理(搭建服务注册中心)

 

 

<2>. 在Pom中添加如下依赖

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

 

 

<3>. 添加注解 @EnableEurekaServer 启动注册中心

@EnableEurekaServer   // 开启服务注册服务
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaServerApplication.class).web(true).run(args);
    }
}

 

 

<4>. 在application.properties 中增加如下配置

server.port= 1111

eureka.instance.hostname= localhost
# 不需要向注册中心注册自己
eureka.client.register-with-eureka=false
# 不需要去检索服务
eureka.client.fetch-registry=false

eureka.client.serviceUrl.defaultZone= http://${eureka.instance.hostname}:${server.port}/eureka

 

<5>. 启动服务并访问http://localhost:1111/ 可以看到如下服务注册页面

Spring cloud Eureka 服务治理(搭建服务注册中心)