Spring Cloud Eureka란?

2023. 10. 30. 13:38·웹
반응형

Spring Cloud Eureka

오늘은 스프링 클라우드 유레카 서버를 생성하고 설정하는 방법, 유레카 클라이언트가 연결설정 및 서버 인스턴스 정보를 받아오는 방법에 대해서 설명해보겠습니다.

유레카는 서버의 인스턴스 정보(ip, port, 상태 등..)를 담아두고 동적으로 관리하는 서버로써 MSA 환경에 특화되어 관리자 없이도 쉽게 서비스를 확장, 축소하고 그에따른 인스턴스를 자동으로 관리할 수 있습니다.

또한 서버의 주소를 여러 전략을 통하여 로드밸런싱 작업도 수행할 수 있습니다.

즉, 유레카를 사용하여 코드를 개발하면 관리자는 서버가 확장될 때마다 코드를 수정할 필요가 없고 동적으로 서버가 등록되어 관리되게 됩니다.

Eureka 서버 생성

dependency

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

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

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

netflix-eureka-server 디펜던시를 추가해줍니다.

@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {

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

}

@EnableEurekaServer : 어노테이션을 통해 유레카 서버를 설정합니다.

# application.yml 세팅

# 유레카 서버가 웹서비스의 성격으로 구동된다.
# 포트 번호 지정
server:
  port: 8761

# 마이크로서비스를 담당하는 스프링부트 프레임 워크에
# 각각의 마이크로서비스에 고유한 아이디를 부여하는 설명
spring:
  application:
    name: discoveryservice

# 유레카 클라이언트 설정
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

server의 포트는 8761을 사용한다.

eureka 서버는 클라이언트 역할을 수행하지 않으므로 클라이언트 등록에 관한 서비스를 기본값 true에서 false로 선언해주어야 한다.

이렇게 하면 Eureka Server가 실행된다.

Eureka 클라이언트 등록

dependency

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

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

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

eureka client 디펜던시를 추가해준다.

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://localhost:8761/eureka

Server port를 0으로 설정하면 실행할 때 랜덤포트를 선정하여 실행된다.

spring application name을 설정하여 eureka client에 등록되는 이름을 설정한다.

이렇게 설정하면 유레카서버로 마이크로서비스가 등록요청을 하여 등록한다.

defaultZone에 유레카 서버의 호스트네임:포트/eureka로 설정한다.

http://eureka-hostname:8761로 접속하면 아래와 같이 마이크로서비스가 등록됬음을 확인할 수 있다.

Eureka 클라이언트가 다른 서비스의 정보를 가져오는 방법

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

private final DiscoveryClient discoveryClient;

    public PostServiceImpl(
            @Autowired DiscoveryClient discoveryClient
    ){
        this.discoveryClient = discoveryClient;
    }

    public Boolean existUserAndBoard(Long userId, Long boardId) throws URISyntaxException {
        ServiceInstance userServer = discoveryClient.getInstances("USER-SERVICE").get(0);
        URI userUri = new URI(userServer.getUri()+"/user/exist/"+userId);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<?> httpEntity = new HttpEntity<>(httpHeaders);

        ServiceInstance boardServer = discoveryClient.getInstances("BOARD-SERVICE").get(0);
        URI boardUri = new URI(boardServer.getUri()+"/board/exist/"+boardId);
        if(restTemplate.exchange(userUri,HttpMethod.POST,httpEntity, Boolean.class).getBody()
                && restTemplate.exchange(boardUri,HttpMethod.POST,httpEntity, Boolean.class).getBody()){
            return true;
        }else{
            return false;
        }
   }

DiscoveryClient 인터페이스를 빈 주입받아 사용할 수 있다.

각각의 마이크로서비스가 RestTemplate로 Http요청을 보낼 때 필요한 정보들을 받을 수 있다.

discoveryClient.getInstances(”application-name”)을 통하여 해당 마이크로서비스의 서버 목록을 가져올 수 있다. (List)

ServiceInstance 객체로 부터 다양한 서버 정보를 가져와서 사용할 수 있다.

반응형

'웹' 카테고리의 다른 글

Spring Cloud Gateway JWT 인증, 인가 Filter 구현 및 적용  (1) 2023.11.13
Image 데이터를 RestTemplate로 통신하면서 발생한 에러  (0) 2023.11.13
Spring Boot에서 보안을 위한 JWT를 발급하는 방법  (1) 2023.10.27
JWT란?  (0) 2023.10.26
Spring Boot 이미지 받는 방법  (0) 2023.09.18
'웹' 카테고리의 다른 글
  • Spring Cloud Gateway JWT 인증, 인가 Filter 구현 및 적용
  • Image 데이터를 RestTemplate로 통신하면서 발생한 에러
  • Spring Boot에서 보안을 위한 JWT를 발급하는 방법
  • JWT란?
부기(창의)
부기(창의)
창의의 개발블로그입니다.
  • 부기(창의)
    창의
    부기(창의)
  • 전체
    오늘
    어제
    • 분류 전체보기 (222)
      • 고민 (1)
      • 데브옵스 (9)
      • AWS (3)
      • 웹 (13)
      • Docker (2)
      • Git (1)
      • JAVA (15)
      • OOP (3)
        • 디자인 패턴 (1)
      • 백준 (106)
        • JAVA (7)
      • Spring (23)
      • 개발 관련 (4)
      • 알고리즘 (4)
      • TIL (13)
      • 우아한 테크코스 (9)
        • 프리코스 지원과정 (6)
      • NextJS (3)
      • Computer Science (13)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • Github : https://github.com/chan⋯
  • 인기 글

  • 태그

    aws
    자바
    우테코 7기
    hibernate
    운영체제
    동시성
    백트래킹
    다이나믹 프로그래밍
    ec2
    OS
    페스타타북
    페스타북
    뉴진스
    SSR
    우테코 프리코스
    메모리
    java
    도커
    dp
    jvm
    우테코
    jpa
    spring
    완탐
    알고리즘
    백준
    Spring Boot
    완전탐색
    스레드
    스프링
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
부기(창의)
Spring Cloud Eureka란?
상단으로

티스토리툴바