Netflix的eureka注册中心简单使用

发布时间 2023-10-02 18:54:56作者: strongmore

使用

服务端

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
server:
  port: 9000
  servlet:
    context-path: /eureka-server

eureka:
  instance:
    hostname: localhost   # eureka 实例名称
  client:
    register-with-eureka: false # 不向注册中心注册自己
    fetch-registry: false       # 是否检索服务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

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

http://localhost:9000/eureka-server/

image

客户端

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
server:
  port: 8092
  servlet:
    context-path: /demo-eureka-client

eureka:
  instance:
    instance-id: demo-eureka-client2
    prefer-ip-address: true # 访问路径可以显示 IP
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka-server/eureka  # 注册中心访问地址
spring:
  application:
    name: demo-eureka-client

可以通过修改端口号和实例ID(instance-id)的值,使一个应用在本地运行多个实例

image

@SpringBootApplication
public class EurekaClientApplication {

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

}

原理分析

客户端

客户端通过AbstractJerseyEurekaHttpClient及子类JerseyReplicationClient来向注册中心发送请求,如注册实例,更新状态等

http://localhost:9000/eureka-server/eureka/apps/  GET   # 用来查询所有服务

服务端

使用Jersey来实现REST服务接口,如ApplicationsResource。EurekaServerAutoConfiguration中的jerseyFilterRegistration()方法定义了一个过滤器ServletContainer,类似SpringMVC的DispatcherServlet,做请求的分发,jerseyApplication()方法创建DefaultResourceConfig对象,使用Spring的类扫描来代替Jersey的扫描。

参考

Spring Cloud Eureka 源码解析