应用
使用 Spring-Cloud 必须引入 SpringBoot,并且两者版本有一个对应关系,这个对应关系可以在官网查到。
Spring Cloud | Spring Boot |
---|---|
Hoxton | 2.2.x |
Greenwich | 2.1.x |
Finchley | 2.0.x |
Edgware | 1.5.x |
Dalston | 1.5.x |
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
服务端
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
配置文件
server:
port: 5000
eureka:
server:
#关闭自我保护机制
enable-self-preservation: false
#设置清理间隔(单位:毫秒 默认是60*1000)
eviction-interval-timer-in-ms: 4000
remote-region-connection-idle-timeout-seconds: 6000
instance:
hostname: jonkee1
client:
# 不把自己作为一个客户端注册到自己身上
registerWithEureka: false
# 不需要从服务端获取注册信息
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
启动类很简单,加上@EnableEurekaServer
注解可以启动一个 eureka server 服务。
@SpringBootApplication
@EnableEurekaServer
public class EurekaServer {
public static void main(String[] args) {
SpringApplication.run(EurekaServer.class);
}
}
打开http://jonkee1:5000/
可以看到 eureka 监控面板。
客户端
引入依赖
<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>
配置文件
server:
port: 6000
eureka:
client:
serviceUrl:
#eureka服务端提供的注册地址 参考服务端配置的这个路径
defaultZone: http://jonkee1:5000/eureka/
instance:
#此实例注册到eureka服务端的唯一的实例ID
instance-id: client-0
#是否显示IP地址
prefer-ip-address: true
#eureka客户需要多长时间发送心跳给eureka服务器,表明它仍然活着,默认为30 秒 (与下面配置的单位都是秒)
leaseRenewalIntervalInSeconds: 6
#Eureka服务器在接收到实例的最后一次发出的心跳后,需要等待多久才可以将此实例删除,默认为90秒
leaseExpirationDurationInSeconds: 30
spring:
application:
#此实例注册到eureka服务端的name
name: client
启动类同样很简单,加上@EnableEurekaClient
就可以了。
@SpringBootApplication
@EnableEurekaClient
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class);
}
}
此时刷新 eureka 监控面板就能看到这个客户端已经注册进去了。
集群搭建
不管是 Eureka 服务端的集群还是客户端的集群,本质上都是客户端的集群。
server:
port: 5001
eureka:
server:
#关闭自我保护机制
enable-self-preservation: false
#设置清理间隔(单位:毫秒 默认是60*1000)
eviction-interval-timer-in-ms: 4000
remote-region-connection-idle-timeout-seconds: 6000
instance:
hostname: jonkee1
client:
# 不把自己作为一个客户端注册到自己身上
registerWithEureka: false
# 不需要从服务端获取注册信息
fetchRegistry: false
serviceUrl:
# 在这里配上其它 eureka 服务器的地址就行了
defaultZone: http://jonkee2:5002/eureka,http://jonkee3:5003/eureka