美文网首页
Spring Boot集成Eureka

Spring Boot集成Eureka

作者: 你慧快乐 | 来源:发表于2019-03-27 22:02 被阅读0次

服务端

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
    <dependency>
         <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-dependencies</artifactId>
          <version>Brixton.SR4</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
  </dependencies>

在应用启动类上添加@EnableEurekaServer注解,声明为Eureka Server

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
  public static void main(String[] args) {
    SpringApplication.run(EurekaApplication.class, args);
  }
}

配置文件application.yml中添加以下内容:

server:
  port: 8761                    # 指定该Eureka实例的端口
eureka:
  instance:
    hostname: 127.0.0.1         # 指定该Eureka实例的主机名
  client:
    registerWithEureka: false    #自身注册到Eureka Server上,默认为true
    fetchRegistry: false   #从其他Eureka Server获取注册信息,单节点设置为false,集群情况下可设置为true
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/  #多个地址用逗号分割,单节点可不配置
  server:
    enable-self-preservation: false   #调试时关闭eureka注册中心的保护机制

启动应用,访问http://localhost:8761

eureka-server

客户端

添加如下依赖:

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

在配置文件application.yml中添加如下配置:

server:
  port: 8000
spring:
  application:
    name: microservice-provider
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/    # 指定注册中心的地址
  instance:
    preferIpAddress: true
  • spring.application.name用于指定到Eureka Server上的应用名称
  • eureka.instance.prefer-ip-address = true表示将自己的ip注册到Eureka Server,若不配置或设置为false,表示注册服务器的hostname注册到Eureka Server
    在启动类上添加@EnableDiscoveryClient,声明为Eureka Client:
@SpringBootApplication
@EnableDiscoveryClient
public class UserProviderApplication {
  public static void main(String[] args) {
    SpringApplication.run(UserProviderApplication.class, args);
  }
}

也可使用@EnableEurekaClient注解替代@EnableDiscoveryClient,EnableEurekaClient只支持Eureka,而EnableDiscoveryClient是一个高度的抽象还支持Zookeeper和Consul

Eureka Server高可用

只需修改Eureka Server端口号启动多个实例,然后将eureka.client.serviceUrl.defaultZone地址相互配置为其他节点地址即可。而客户端无需配置多个defaultZone,只需配置一个,Eureka Server集群节点之间会相互同步

相关文章

网友评论

      本文标题:Spring Boot集成Eureka

      本文链接:https://www.haomeiwen.com/subject/kdxxbqtx.html