[MSA] Spring Cloud Netflix Eureka 를 사용한 서비스 디스커버리 구현

Leo·2022년 11월 21일
0

Spring Cloud Netflix Eureka란?

  • 넷플릭스에서 MSA를 위해 Spring Cloud에 기부한 오픈 소스
  • MSA구조에서 인스턴스의 상태를 동적으로 관리하는 서버가 필요해졌고 이를 보통 서비스 디스커버리 서버로 칭하고 넷플릭스는 Eureka라는 이름으로 공개
  • Service 인스턴스의 위치는 인스턴스가 생성될 때 regitry에 등록되고, 인스턴스가 종료될 때 registry에서 삭제됨

시작 전 구성

유레카를 이용한 서비스 디스커버리를 구현하기 위해서 하나는 디스커버리 서버, 나머지는 클라이언트로 구성해보자.

디스커버리 서버 구성하기

스프링 부트로 프로젝트를 생성하고 dependencies를 추가

implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'

메인에서 @EnableEurekaServer 추가하여 서버를 활성화

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryserviceApplication {

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

}

application.yml 파일에서 서버를 설정

server:
  port: 8761

spring:
  application:
    name: discoveryservice

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

spring.application.name
MSA에서 이 서비스를 식별하는 id

eureka.client.register-with-eureka
유레카 서버에 자기 자신을 클라이언트로 등록하지 않도록 하는 설정
해당 서버는 자기 자신을 클라이언트로써 디스커버리 서버에 등록하지 않도록 false로 설정

eureka.client.fetch-registry
클라이언트로써 eureka 서버에서 eureka 레지스트리 정보를 가져올지 여부를 설정
위 설정과 마찬가지로 클라이언트가 아니므로 false로 설정

여기까지가 서비스 디스커버리 서버 설정의 끝!
서버를 올리고 http://localhost:8761로 접속하면 아래와 같은 메인화면이 나타남
클라이언트 설정이 안되었으므로 사용가능 인스턴스는 없다고 나타남

클라이언트 설정

서버와 동일하게 스프링부트로 프로젝트를 만들고 dependencies를 추가

implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'

메인에서 아래와 같이 @EnableDiscoveryClient 어노테이션 삽입

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

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

}

마지막으로 application.yml 파일에서 설정을 해줌

server:
  port: 0

spring:
  application:
    name: user-service

eureka:
  instance:
    instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}}
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka
  • 서버포트를 0으로 설정하면 랜덤하게 포트가 설정
  • spring.application.name는 유레카 서버에 등록되는 서비스 명
  • instance-id는 유레카 서버 메인에서 나타나는 status값인데 현재 서버포트를 랜덤포트 0으로 등록했으므로 서버에서 조회 시 동일한 id로 나타나므로 유니크한 아이디로 구성
  • service-url는 해당 클라이언트가 등록될 유레카 서버를 입력
  • 동일하게 여러개의 프로젝트를 실행하여 디스커버리 서버에 잘 등록되었는지 확인

https://github.com/leaflife84/discoveryservice - 서버
https://github.com/leaflife84/DiscoveryClient - 클라이언트

0개의 댓글