一、Eureka服务端
-
引入maven依赖
<parent>
<groupId>com.yk</groupId>
<artifactId>cloud-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-eureka-server</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
-
激活eureka服务
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
-
配置eureka
spring:
application:
name: spring-cloud-eureka-server
server:
port: 801
eureka:
client:
##让自己不需要注册在上面禁止客户端注册,表明自己是一个eureka server
register-with-eureka: false
fetch-registry: false
- 启动
如果在配置eureka的时候没有加上register-with-eureka: false、fetch-registry: false,启动过一小会,会看到控制台报错。但是不影响运行。
通过异常信息可以看出:是因为eureka Server既是服务器也是客户端。默认也是需要配置注册中心地址。为什么是在启动之后报错,因为存在一个心跳检测机制。
二、Eureka客户端
- 引入maven依赖
<parent>
<groupId>com.yk</groupId>
<artifactId>cloud-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-eureka-client</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
- 激活eureka客户端
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableEurekaClient //只能是Eureka
//@EnableDiscoveryClient 可以是其他注册中心。如zookeeper、Consul
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
- 配置eureka客户端
spring:
application:
name: spring-cloud-eureka-client
server:
port: 802
eureka:
client:
service-url:
# 注册到注册中心
defaultZone: http://localhost:801/eureka/
#显示服务器IP加端口
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
- 启动服务端和客户端
三、Eureka服务的高可用
3.1注册中心的相互注册
- 服务端配置
是在上面演示的服务端上修改的代码
spring:
application:
name: spring-cloud-eureka-server
server:
#使用启动命令覆盖默认的801
port: 801
eureka:
client:
##让自己不需要注册在上面禁止客户端注册,表明自己是一个eureka server
register-with-eureka: false
fetch-registry: false
service-url:
#服务注册
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
instance:
hostname: localhost
通过idea可以启动不端口的两个项目,首先启动完第一个之后。按照
这样就可以启动两个实例
3.1客户端注册两个注册中心
- 客户端配置
spring:
application:
name: spring-cloud-eureka-client
server:
port: 802
eureka:
client:
service-url:
# 注册到注册中心
defaultZone: http://localhost:801/eureka/,http://localhost:803/eureka/
#显示服务器IP加端口
instance:
hostname: localhost
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
3.3实现高可用
如果Eureka客户端配置多个Eureka注册服务器,那么默认情况只有第一台注册服务器上面会显示客户端信息。当第一台可用的注册服务器Down掉之后,那么客户端应用才会选择下一个台可用的注册服务器
- 这个时候关掉第一台注册服务器
可以看到客户端会自动重试,然后寻找下一台注册服务器
- 修改Client获取元信息的时间间隔和同步间隔
默认30秒,可以通过eureka.client.registryFetchIntervalSeconds:、eureka.client.instanceInfoReplicationIntervalSeconds:这两个来设置获取应用元信息时间间隔和同步时间间隔。