Spring Cloud Eureka 是对Netflix公司的Eureka的二次封装,它实现了服务治理的功能;
1、Eureka Server是服务端,负责管理各各微服务结点的信息和状态。
2、在微服务上部署Eureka Client程序,远程访问Eureka Server将自己注册在Eureka Server。
3、微服务需要调用另一个微服务时从Eureka Server中获取服务调用地址,进行远程调用。
简单构建springcloud-eureka项目
父工程pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Eureka Server工程
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
启动类
@EnableEurekaServer//标识这是一个Eureka服务
@SpringBootApplication
public class GovernCenterApplication {
public static void main(String[] args) {
SpringApplication.run(GovernCenterApplication.class, args);
}
}
application.yml
server:
port: 7001 #服务端口
spring:
application:
name: springcloud-priovider #指定服务名
eureka:
client:
registerWithEureka: false #服务注册,是否将自己注册到Eureka服务中
fetchRegistry: false #服务发现,是否从Eureka中获取注册信息
serviceUrl: #Eureka客户端与Eureka服务端的交互地址,高可用状态配置对方的地址,单机状态配置自己(如果不配置则默认本机8761端口)
defaultZone: http://localhost:50101/eureka/
server:
enable‐self‐preservation: false #是否开启自我保护模式
eviction‐interval‐timer‐in‐ms: 60000 #服务注册表清理间隔(单位毫秒,默认是60*1000)
@EnableEurekaServer 需要在启动类上用@EnableEurekaServer标识此服务为Eureka服务
@EnableEurekaClient 需要在启动类上用@EnableEurekaClient标识此服务为EurekaClients服务用于服务注册
Eureka Client工程
pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
在application.yml配置
eureka:
client:
registerWithEureka: true #服务注册开关
fetchRegistry: true #服务发现开关
serviceUrl: #Eureka客户端与Eureka服务端进行交互的地址,多个中间用逗号分隔
defaultZone: ${
EUREKA_SERVER:http://localhost:50101/eureka/,http://localhost:50102/eureka/}
instance:
prefer-ip-address: true #将自己的ip地址注册到Eureka服务中
ip-address: ${
IP_ADDRESS:127.0.0.1}
instance-id: ${
spring.application.name}:${
server.port} #指定实例id
在启动类上添加注解 @EnableDiscoveryClient ,表示它是一个Eureka的客户端
刷新Eureka Server查看注册情况