写在前面:
Eureka是Netfilx开源的服务发现组件,本身是一个基于rest的服务,它包含client和server两部分。
Spirng Cloud将它集成在子项目Spirng Cloud Netfilx中,从而实现服务的注册和发现
1、eureka中的server和client的介绍及特点
- Eureka Server:提供服务发现的能力,各个微服务启动时,会向Eureka Server注册自己的信息例如(IP,端口号,服务名称等),Eureka会存储这些信息
- Eureka Client:是一个java的客户端用来简化Eureka Server的交互
- Eureka Client会缓存服务注册表中的信息。这种方式有一定的优势首先可以降低Eureka Server的压力,其次当所有的Eureka Server宕机服务调用方依然可以完成调用
2、服务注册与服务发现
- 服务注册:当微服务client启动时,向Eureka Server发起注册,并上报该节点的相关信息
- 服务发现:client从Eureka Server获取注册信息,然后发起调用
3、SpringBoot与SpringCloud版本匹配
4、Server(服务端)开发
注:
1、需要我们新建一个Springboot的moudle
注意:本次测试选择的是D版本,也就是Dalston版本,因此SpringBoot的版本应该选择1.5.x,不能选择2.0.x或以上的版本。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2、引入SpringCloud的相关依赖
相关依赖未进行开源,因此在pom文件中我们需要引入SpringCloud自己的版本库。
<!--仓库的位置-->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<!--引入版本号-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--eureka server的相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
3、开发入口类
入口类上面需要加入相关的注解
//@EnableDiscoveryClient //不仅支持Eureka作为注册中心还支持zookeeper
@EnableEurekaServer
@SpringBootApplication
public class EurekaServer {
public static void main(String[] args) {
SpringApplication.run(EurekaServer.class,args);
}
}
4、配置文件
#设置eureka server 的交互地址,之后的服务获取和服务注册都需要依赖于这个地址
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
#表示是否将自己注册到eureka上
eureka.client.register-with-eureka=false
#表示是否从eureka server上获取注册信息
eureka.client.fetch-registry=false
#应用服务名 微服务服务名
spring.application.name=eureka-server
#端口号
server.port=8761
5、Client(客户端)开发
1、步骤一同上
2、jar包有区别,版本号和仓库的相同
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
3、开发入口类
@EnableDiscoveryClient
@SpringBootApplication
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
4、配置文件
#设置eureka server 的交互地址,之后的服务获取和服务注册都需要依赖于这个地址
eureka.client.service-url.defaultZone=http://localhost:8761/eureka,http://localhost:8760/eureka
#应用服务名 微服务服务名
spring.application.name=eureka-client
#端口号
server.port=8762
6、成功验证
启动Server和Client的入口类函数之后,访问:
http://localhost:Server:端口号/
例如;http://localhost:8760/ 关于Server的端口号可以在开发Server的端口号中去查找
访问成功跳转的页面: