什么是Eureka?
Spring Cloud Eureka 是Spring对Netflix公司的Eureka的二次封装的产品,它实现了服务治理的功能
首先搭建Eureka服务注册中心
新建Maven工程springcloud-eureka-7001
导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
编写相应配置
server:
port: 7001
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #是否向注册中心注册自己
fetch-registry: false
service-url: #监控页面
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
fetch-registry: false
:表示这就是注册中心
在主启动类上开启服务
package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServer_7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaServer_7001.class,args);
}
}
@EnableEurekaServer
:表示开启EurekaServer功能
测试:
访问成功!当前并没有服务注册进去
将
springcloud-provider-dept-8001
服务注册到注册中心
在
springcloud-provider-dept-8001
工程中导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
编写相应配置
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/#这就是注册中心提供的URL
instance:
instance-id: springcloud-provider-dept8001#别名
在主启动类中开启服务
package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
@EnableEurekaClient
:表示开启EurekaClient功能
测试:
服务成功注册到了Eureka中,Status下显示的就是配置的别名
EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY’RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.
这是因为Eureka的自我保护机制,Eureka server和client之间每隔30秒会进行一次心跳通信,如果Eureka server 在90秒内,没有接受到某个微服务的心跳,就会注销该实例。但是当网络发生故障的情况下,微服务和EurekaServer就无法通讯,但是微服务本身是健康的,此时不应该注销服务,而EurekaServer通过注销该服务来达到自我保护机制,当网络健康的时候,EurekaServer就会自动退出自我保护机制。
将
springcloud-consumer-dept-80
服务注册到注册中心
导入依赖与springcloud-provider-dept-8001
相同
编写配置
server:
port: 80
spring:
application:
name: springcloud-consumer-dept
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
instance:
instance-id: springcloud-consumer-dept-80
在主启动类上增加注解@EnableEurekaClient
开启EurekaClient功能
测试:
两个服务都成功注册进去了!