前言
在分布式架构系统中,服务的注册与发现是需要解决的问题之一,
其实在服务的注册与发现是两个过程,eureka客户端注册到eureka服务端,eureka服务端能够发现新增的或是发生故障的eureka客户端。
实现这种过程采用的是一种心跳机制。
而在spring cloud netflix系列技术栈中我们通过eureka来解决服务注册与发现的问题。
使用eureka时,我们会接触到eureka服务端(eureka注册中心),eureka客户端这样的名词。
我们通过下面eureka服务端和eureka客户端的创建过程来体会一下它们之间的不同
创建eureka服务端(eureka注册中心)
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- Application启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class,args);
}
}
- application.yml
# 配置应用程序的名称,让被人发现(eureka是通过服务名称来完成服务的注册与发现的)
spring:
application:
name: spring-cloud-netflix-eureka
server:
port: 8761
eureka:
instance:
# eureka服务端服务器地址(IP)
hostname: localhost
client:
# registerWithEureka,fetchRegistry的值为false表明这是eureka服务端,而非eureka客户端
registerWithEureka: false
fetchRegistry: false
serviceUrl:
# 设置eureka服务端的地址(IP:PORT)
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
创建eureka客户端
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- Application启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class,args);
}
}
- application.yml
spring:
application:
# 服务名称,eureka通过服务名称完成服务的注册与发现
name: spring-cloud-netflix-eureka-client
server:
port: 8762
eureka:
client:
serviceUrl:
# 指向Eureka服务端的地址
defaultZone: http://localhost:8761/eureka/
总结
我们通过比较eureka服务端与eureka客户端的创建过程,会发现它们使用相同的依赖,在application启动类中使用相同的注解@EnableEurekaServer来开启服务,只是在application.yml中通过 registerWithEureka: false
fetchRegistry: false
这两个属性来区分谁是服务端,谁是客户端。
eureka是通过心跳机制来维持服务的注册与发现的。