1 服务发现:Eureka客户端
服务发现是基于微服务架构的关键原则之一。尝试手动配置每个客户机或某种形式的约定可能很难做到,而且可能很脆弱。Eureka是Netflix服务发现的服务器和客户端。服务器可以配置和部署为高度可用,每个服务器将注册服务的状态复制到其他服务器。
1.1 怎样在项目中引入Eureka客户端
要在项目中包含Eureka客户端,请使用groupId为org.springframework.cloud、artifactId为spring-cloud-starter-netflix-eureka-client的依赖配置。
1.2 Eureka服务注册
当客户端向Eureka注册时,它提供有关自身的元数据,如主机、端口、健康检查URL、主页和其他详细信息。Eureka从某个服务的每个实例获取心跳检测消息。如果心跳检测在可配置的时间表上发生故障,则Eureka通常会从注册表中删除该实例。
使用Spring Initializr创建一个SpringBoot项目,项目名称为Client,以下为一个简单的Eureka客户端示例:
@EnableEurekaClient //Eureka客户端注解
@SpringBootApplication
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
application.yml 配置
spring
application
name: client //配置客户端服务名称,可在eureka服务注册中心显示
server
port: 9010 //配置客户端端口
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9001/eureka/
2 服务发现:Eureka服务器
2.1 怎样在项目中引入Eureka服务器
要在项目中包含Eureka服务器,请使用groupId为org.springframework.cloud、artifactId为spring-cloud-starter-netflix-eureka-server的依赖配置。
2.2 如何启动一个Eureka服务器
使用Spring Initializr创建一个SpringBoot项目,项目名称为EurekaServer,以下为一个简单的Eureka服务器示例:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
application.yml 配置
spring
application
name: eureka-server //配置服务器服务名称
server:
port: 9001
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
3 验证
EurekaServer服务和Client服务启动之后,打开浏览器,访问 http://localhost:9090 ,即可打开Eureka服务注册中心,查看已经注册的服务