Eureka简介
Eureka是Netflix开源的服务发现组件,本身是一个基于Rest的服务。它包含Server和Client两部分。
Spring Cloud将它集成在子项目Spring Clound Netflix中,从而实现微服务的注册和发现。
编写服务注册中心Eureka Server
1、创建springboot项目并添加EurekaServer的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2、编写启动类 ,使用@EnableEurekaServer 注解声明 Eureka Server
//开启EurekaServer服务注册中心
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3、在配置文件application.yml中添加以下内容
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
- 配置文件详解
- server.prot:端口设置
- eureka.client.register-with-eureka:表示是否将自己注册到
Eureka Server,默认为true。由于当前应用是Eureka Server,故设为false - eureka.client.fetch-registry:表示是否从Eureka Server获取注册信息,默认为true。
因当前应用是单节点的eureka server,不需要同步其它的Eureka Server节点的数据,故设为false。 - eureka.client.service-url.defaultZone:设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖此地址
默认为:http://localhost:8761;多个地址可使用,号分隔
启动服务并访问http://localhost:8761
如下图所示
由图可见No instances avaiable,因为没有任何微服务实例注册到Eureka Server中,所以没有实例被发现。
将微服务注册到Eureka Server上
1、 创建springboot项目并添加Eureka Client的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2、 编写启动类,使用@EnableEurekaClient注解 声明Eureka Client
//声明Eureka Client
@EnableEurekaClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3、在配置文件application.yml中添加以下内容
server:
port: 8762
spring:
application:
name: hello-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
- 配置文件详解
- spring.application.name:注册到EurekaServer上的名称
- eureka.client.service-url.defaultZone:注册服务地址
启动服务再次访问http://localhost:8761
由图可见,hello-service微服务已成功注册到Eureka Server上