搭建eureka高可用注册中心


前言

搭建高可用的eureka注册中心花费了较长的时间,踩了很多坑,因此觉得有必要写一写。

概念


    高可用的注册中心是指开启多个注册中心,这些注册中心彼此之间相互注册。这样可以防止当某一个注册中心挂掉了服务还是可以在其他的注册中心继续注册。

1、pom.xml

<dependencies>
    <!--添加web支持 -->
    <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 可有可无 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--添加eureka服务器支持 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>
<!--springcloud由很多独立项目集成的,每个项目都有自己独立的版本号因此需要指明 -->
<dependencyManagement>
    <dependencies>
        <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Finchley.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
    </dependencies>
</dependencyManagement>
2、创建application-peer1.yml作为peer1的服务注册中心的配置文件
application-peer1.yml #注意文件名是-不是.
server:
  port: 9091
spring:
  profiles: peer1
  application:
    name: eurekaServer
eureka:
  instance:
    hostname: peer1 #此处名称对应文件名称
  client:
    register-with-eureka: true #高可用注册中心需要将自己作为客户端注册
    fetch-registry: true  #刷新开启
    serviceUrl:
      defaultZone: http://peer2:9092/eureka/  #peer2注册路径
3、创建application-peer2.yml作为peer2的服务注册中心的配置文件
application-peer2.yml #注意文件名是-不是.
server:
  port: 9092
spring:
  profiles: peer2
  application:
    name: eurekaServer
eureka:
  instance:
    hostname: peer2 #此处名称对应文件名称
  client:
    register-with-eureka: true #高可用注册中心需要将自己作为客户端注册
    fetch-registry: true  #刷新开启
    serviceUrl:
      defaultZone: http://peer1:9091/eureka/  #peer1注册路径
    注意:yml格式和properties格式的区别,yml格式读取会按照文件中顺序读取。yml有格式要求:1、叶子节点冒号后空一格2、子节点与父节点空两格不是一个tab
4、让peer1和peer2 hostname生效
windows:
    C:\Windows\System32\drivers\etc\hosts #需要获取管理权限才能修改hosts文件
    127.0.0.1 peerl
    127.0.0.1 peer2
Centos:
    /etc/hosts
    127.0.0.1 peerl
    127.0.0.1 peer2
设置完成后:ping peer1和peer2如果能够ping通即配置成功
5、在启动类中添加服务中心注解
@EnableEurekaServer
@SpringBootApplication
public class ServercenterApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServercenterApplication.class, args);
    }

}
6、启动
打包后:
java -jar servercenter-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1&
java -jar servercenter-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
未打包:
    启动时在program arguments添加参数--spring.profiles.active=peer1
7、总结
    注意细节,越简单的东西往往越容易疏忽。