Spring Cloud + MSA (1)

김준영·2023년 3월 3일
1

Spring Cloud + MSA

목록 보기
1/9
post-thumbnail

Spring Cloud란?


MSA구성을 지원하는 Springboot기반 Framework이다.

간단한 예제로 사용법을 알아보자.

간단한 예제

version & dependency

Spring Boot version : 2.7.9

Dependency - gateway

  • spring-cloud-starter-gateway
  • spring-cloud-starter-netflix-eureka-client
  • lombok

Dependency - service

  • spring-cloud-starter-web
  • spring-cloud-starter-netflix-eureka-client
  • lombok

서버 application.yml(properties)

server:
  port: 8000

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:8761/eureka

spring:
  application:
    name: api-gateway-service
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first-service/**
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**

server 포트 번호는 8000번으로 정했다.

유레카에 등록하지 않고 또 유라카에 등록되는 서비스들의 정보를 갱신하지 않기 위해 false로 작성했다. defaultZone에 유레카 서버 url을 입력했다.

gateway를 통해 2개의 서버를 추가했다. first-service와 second-service.

서비스 application.yml(properties) & Controller

서비스 1

server:
  port: 8081

spring:
  application:
    name: first-service

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
package com.example.firstservice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/first-service")
public class FirstServiceController {

    @GetMapping("/welcome")
    public String welcome(){
        return "Welcome to the First service";
    }
}

서비스2


server:
  port: 8082

spring:
  application:
    name: second-service

eureka:
  client:
    fetch-registry: false
    register-with-eureka: false
package com.example.secondservice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/second-service")
public class SecondServiceController {

    @GetMapping("/welcome")
    public String welcome(){
        return "Welcome to the Second service";
    }

}

간단한 컨트롤러를 작성하여 apigateway와 각 서비스들을 실행시키면 밑에 결과가 나온다.

결과



localhost:8000으로 각 url에 맞게 응답이 온다.

profile
ㅎㅎ

0개의 댓글