版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuyu19911016520/article/details/84888669
Spring Cloud Eureka 它是通过封装 Netflix 开源的Eureka,一款基于 Rest 的服务发现与注册组件,包括 Eureka Server 和 Eureka Client,最新版本为2018年8月发布的1.9.4版本,最新的2.x版本已经不再开源,但是1.9版本已经够用了,不要太过担心
为什么需要服务注册中心?先看几张服务之间调用图
- 项目A写死项目B的IP和端口进行服务间调用
- 如果项目B再以同样的方式访问项目C,当项目B的IP和端口放生变化时,整个调用就会失败
- 当有了Eureka注册中心后,会是什么样子,请看简图
上图就是为什么会有注册中心的原因
除了Eureka外,还有Consul注册中心,Spring Cloud 也集成 Consul
有了上面的理论基础后,我们进行代码实践
通过IDEA创建Maven工程,删除src目录,再添加2个Module,分别是eureka-server 、eureka-client
- eureka-server 的 pom.xml内容如下(为了篇幅,只显示主要部分,想看全部代码的可以下载):
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
eureka-server的启动主类,添加一个 @EnableEurekaServer注解即可
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
eureka-server的application.properties配置文件如下:
server.port=10025
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
- eureka-client 的 pom.xml内容如下,其他和eureka-server相同:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka-client的启动主类,添加一个 @EnableDiscoveryClient注解即可
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
eureka-client的application.properties配置文件如下:
server.port=9500
#服务的实例名,服务间的调用通过此名字调用
spring.application.name=eureka-client
#填写eureka注册中心地址,把自己注册到注册中心去
eureka.client.serviceUrl.defaultZone=http://localhost:10025/eureka/
好了,分别启动 eureka-server、eureka-client,然后访问 http://localhost:10025/,可以看到eureka-client服务实例已经注册到注册中心了,后面还有该实例的 IP与端口
一个简单的注册中心就搞定了,当然此时它还不能用于生产环境,后面演示注册中心高可用与安全
源码已上传到码云,https://gitee.com/zhuyu1991/spring-cloud/