FrameWork/Spring Cloud

Service Discovery

태윤2 2021. 8. 24. 00:47

ServiceDiscovery

클라우드에서 인스턴스는 동적으로 할당되기 때문에 IP주소나 포트 정보가 정해지지 않은 데다가 오토스케일링도 일어나고 중지되고 복구되면서 네트워크 위치가 계속해서 바뀌게 됨

클라이언트나 API게이트웨이가 호출할 서비스를 찾는 메커니즘이 필요한데 이런 메커니즘을 서비스 디스커버리(Service Discovery)라고 함

  • 서비스 또는 서버의 위치를 파악해줌
  • 등록, 검색을 해줌

Spring Cloud Netflix Eureka

Eureka(유레카)란 로드밸런싱과 Midlle-tier server(Client와 Application server 사이) 장애시 장애 조치 처리를 목적으로 한 REST 기반 서비스다.(넥플릭스에서만듬)

 

서비스 디스커버리의 역할을 하는데 좀 더 자세히 말하자면 클라우드 환경에서 연결 정보(ip, hostname, port)의 Registering(등록)과 De-registering(해지)를 바로바로 적용할 수 있게 해주는 게 Eureka이다.

 

  • 구성

Eureka는 Eureka Client와 Eureka Server로 구성되어있다.

 

 

 

프로젝트 생성

 

  • application.yml
server:
  port: 8761

spring:
  jpa:
    # Caused by: org.h2.jdbc.JdbcSQLException: Table "CATALOG" not found; SQL statement:
    # https://stackoverflow.com/questions/67695069/spring-boot-datasource-initialization-error-with-data-sql-script-after-2-5-0-upg
    defer-datasource-initialization: true
  application:
    name: discoveryservice

eureka:
  client:
    # eureka 자신은 eureka 서버에 등록하지 않는 설정
    register-with-eureka: false
    fetch-registry: false
  • http://localhost:8761

Eureka Dashboard

 

user-service 프로젝트 생성

  • Application파일에 @EnableDiscoveryClient 추가
package com.example.userservice;

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

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

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

}
  • application.yml 설정
server:
  port: 9001

spring:
  application:
    name: user-service
eureka:
  client:
    # eureka 서버에 등록
    register-with-eureka: true
    # 외부에서 검색 가능한 형태
    fetch-registry: true
    # 서버의 위치 폴더 지정
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka

 

  • ecommerce 프로젝트를 실행시킨 뒤 user-service를 실행 

user-service프로젝트가 등록되있음
Run Configurations에 UserServiceApplication 한개 추가(Copy)

  • Vm Option 에 port 지정

서비스 추가됨

  • 터미널로 port를 변경해서 실행
./gradlew bootRun --args='--server.port=8888' # gradle
mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=9003' # mvn

 

  • build 삭제
./gradlew clean # gradle
mvn clean # mvn
  • build 후 jar 파일을 실행하기
java -jar -Dserver.port=9004 ./build/libs/user-service-0.0.1-SNAPSHOT.jar
  • 8888은 테스트용으로 추가한것 삭제 되기까지 시간이 걸려서 아직 나타나고있음

 

위 작업을 간단하게 해보자

 

랜덤 포트를 사용하는 설정을 application.yml에 추가

  • Application Configuration에서 추가했던 Applcation을 삭제
  • application.yml에 설정 추가

 

 

랜덤포트사용으로 두개의 서비스를 켰을때

  • reference

Eureka란

ServiceDiscovery란

SpringCloud로 개발하는 마이크로어플리케이션