Spring Service Discovery with Netflix Eureka

광부·2024년 5월 21일
0

Spring

목록 보기
5/8

MSA의 구성에 필수적인 Service Discovery에 대해 배워보았다.

Service Discovery란?

  • 다양한 MSA 들의 호스트 네임과 포트 번호를 일일이 알 수 없기에
  • Client-Server구조로
  • Client에서 Server에게 자신의 {Hostname}:{Port}ServiceName을 전달하고
  • 서버에서는 이를 매핑시켜주는 서비스
  • 즉, 서버에 등록된 서비스 이름을 사용하여 접근할 수 있기에 Location Transparency가 향상된다.

Eureka Server

필요한 의존성

ext {
    set('springCloudVersion', "2023.0.1")
}

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

Eureka Server 설정(application.yml)

server:
  port: 8761

eureka:
  client:
    register-with-eureka: false //자기자신을 디스커버리 서버에 등록하지 않도록 false
    fetch-registry: false //30초 마다 레지스트리 정보를 가져오는 옵션, 서버에서는 이미 가지고 있기에 false

Eureka Server 활성화

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryserviceApplication {

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

}

@EnableEurekaServer 어노테이션을 사용하여 활성화 시켜준다. 기본 포트는 8761 번이다.

Eureka Client

Eureka에 서비스를 등록하기 위해서는 서비스에서 EurekaClient 라이브러리를 사용하여 등록을 수행한다.

의존성

ext {
    springCloudVersion = "2023.0.1"
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:$springCloudVersion"
    }
}

Eureka Client 설정(application.yml)

spring:
  application:
    name: secondServer
server:
  port: 8082
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka

Eureka Server와 다른 점은 spring.application.name에 이름을 명시해야 하는 것과

register-with-eureka, fetch-registry의 값을 true로 설정해야 한다.

그리고 service-url에 eureka 서버의 주소를 알려줘야 한다.

github 참고)
https://github.com/ajou20658/spring-cloud-toy/tree/master/eureka-server

profile
백엔드 주니어 개발자

0개의 댓글