搭建Eureka注册中心
eureka注册中心的启动就像启动一个Spring Boot服务一样,在依赖中引用eureka的starter包:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>
在application.yml配置文件中增加配置:
server:port: 7001eureka:instance:hostname: eureka7001.com # 当前节点的名称client:fetch-registry: false # 不注册自己register-with-eureka: false # 不检索自己service-url:defaultZone: http://eureka7002.com:7002/eureka/ # 配置其它节点地址,搭建集群时使用server:# 关闭自我保护机制,保证不可用服务立即被踢出enable-self-preservation: falseeviction-interval-timer-in-ms: 2000
在启动类中增加注解@EnableEurekaServer:
@SpringBootApplication@EnableEurekaServerpublic class EurekaMain7001 {public static void main(String[] args) {SpringApplication.run(EurekaMain7001.class, args);}}
启动之后通过浏览器http://localhost:7001/控制台查看:
使用Eureka注册中心
pom.xml增加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
在启动类上增加注解@EnableDiscoveryClient:
@SpringBootApplication@EnableEurekaClient@EnableDiscoveryClientpublic class PaymentMain8001 {public static void main(String[] args) {SpringApplication.run(PaymentMain8001.class, args);}}
在application.yml配置文件中增加Eureka注册中心的配置:
eureka:client:fetch-registry: trueregister-with-eureka: trueservice-url:defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eurekainstance:ip-address: 127.0.0.1instance-id: payment8001prefer-ip-address: true# 向eureka发送心跳间隔(默认是30秒)lease-renewal-interval-in-seconds: 1# eureka收到最后一次心跳后等待时间上限,超时将剔除服务(默认是90秒)lease-expiration-duration-in-seconds: 2
这样就可以把服务注册到Eureka中了:
