본문 바로가기

MSA

스프링 디스커버리를 위한 Eureka 클라이언트 생성

1. 유레카 클라이언트 

유레카 클라이언트 프로젝트 생성

생성된 프로젝트의 Application.java 내 ServiceApplication 클래스 위에 @EnableDiscoveryClient 를 붙여주면 유레카 서버에서 클라이언트로 인식하며 통신합니다.

  • DiscoveryClientApplication
package com.example.discoveryclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class DiscoveryClientApplication {

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

}
  • yml 파일
server:
  port: 8003

spring:
  application:
    name: discovery-client
eureka:
  client:
    register-with-eureka: true # 클라이언트 서버를 유레카 서버에 등록하기
    fetch-registry: true #유레카 서버에서 서버 상태 지속적 감시
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka #8761은 유레카 디스커버리 서버의 주소 + /eureka =>이 주소에 http 통신을 넣으면서 감지해준다.

인텔리제이에서 확인
인스턴스 등록된 것을 확인할 수 있음.

 

 

2. 동일 프로젝트로 클라이언트 서버(인스턴스)  2개 이상 실행시키기

  • 인텔리제이에서 여러개 실행

실행 도구 옆에서 Edit Cconfiguration 클릭하여 아래 화면에서 복사 진행

Apply를 누르고 OK를 누르면 한 프로젝트로 인스턴스 2개 생성됨

 

3 . 한 프로젝트 내 2개의 클라이언트 서버끼리 포트 충돌 방지 = >로드밸런싱 등록

 

  3.1 서버 실행 단계에서 포트값을 새롭게 지정

  Configurations파일은 종료 후 재실행해도 설정 파일의 변경 없음을 보장함

  Run/Debug Configurations -> Modify options -> Add VM options

-Dserver.port=포트번호를 VM option에 입력

여기서 -D는 "백그라운드(detached)" 모드로  콘솔창을 숨기고 어플리케이션을 가동한다는 의미이고(인텔리제이 콘솔창은 하나뿐이므로, 두 개 이상을 한 창에서 돌리려면 콘솔창이 숨겨져야함)

server.port=포트번호는  application.yml에 적힌 포트번호를 해당 번호로 교체해서 쓰겠다는 의미입니다.

Instance Status에 2개가 실행중임을 볼 수 있다.

 

 3.2  각 서버 실행시마다 비어있는 포트를 기반으로 랜덤포트로 실행

server.port = 0으로 주면 0번이라는 포트가 존재하지 않기 랜덤포트 배정을 의미한다.

각 인스턴스별로 유레카에 보여지는 표기를 다르게 yml파일에 설정한다.

server:
  port: 0

spring:
  application:
    name: discovery-client
eureka:
  client:
    register-with-eureka: true # 유레카 서버에 등록하기
    fetch-registry: true # 유레카 서버에서 서버 상태 지속적 감시
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka #8761은 유레카 디스커버리 서버 port번호 + /eureka

  # 인스턴스별로 유레카에 보여지는 표기를 다르게 설정함
  instance:
    instance-id: ${spring.client.cloud.hostname}:${spring.application.instance_id:${random.value}}

인텔리제이 터미널에서 확인