딸기말차

[MSA] 16. Api Gateway 내 MicroService 등록 본문

Bootcamp/MSA

[MSA] 16. Api Gateway 내 MicroService 등록

딸기말차 2023. 10. 31. 10:45

엔코아 플레이데이터(Encore Playdata) Backend 2기 백엔드 개발 부트캠프 (playdata.io)

 

백엔드 개발 부트캠프

백엔드 기초부터 배포까지! 매력있는 백엔드 개발자 포트폴리오를 완성하여 취업하세요.

playdata.io


1. Kbo-Service 

기존 프로젝트에 새로운 마이크로 서비스를 만들어 유레카 서버에 추가, 컨테이너화 하여 minikube를 통해 관리하는 실습을 진행해 보았다.

 

해당 프로젝트의 구성정보는 다음과 같다.

프로젝트 생성


2. DB 연결 정보

AWS에 올라가 있는 DB를 연동시키기 위해 applicatiom.properties 를 작성하였다.

# application.properties
spring.datasource.url = jdbc:postgresql://[AWS Public IP]:5432/ostock_dev
spring.datasource.username = postgres
spring.datasource.password = postgres

spring.jpa.hibernate.ddl-auto=none
spring.jpa.database=POSTGRESQL
spring.jpa.show-sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

spring.database.driverClassName= org.postgresql.Driver
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

3. TeamName 을 통해 데이터 조회 API

1. Kbo Entity

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class Kbo {

    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "player_num", length = 30)
    private String playerNum;

    @Column(name = "name", length = 255)
    private String name;

    @Column(name = "position", length = 50)
    private String position;

    @Column(name = "team_name", length = 50)
    private String teamName;

    @Column(name = "birthday", length = 30)
    private String birthday;

    @Column(name = "career", length = 255)
    private String career;

    @Column(name = "height")
    private Integer height;

    @Column(name = "weight")
    private Integer weight;
}

2. KboRepository

public interface KboRepository extends JpaRepository<Kbo, Long> {

    List<Kbo> findByTeamName(String teamName);
}

3. KboController

@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/kbo")
public class KboController {

    private static final Logger log = LoggerFactory.getLogger(KboController.class);
    private final KboService kboService;

    @GetMapping("/hi")
    public String getHello() {
        log.info("[KboController getHello()] method start");
        return "Hi";
    }

    @GetMapping("/team/{team}")
    public ResponseEntity<List<Kbo>> getKboTeam(@PathVariable String team) {
        log.info("[KboController getKboTeam] team : {}", team);
        List<Kbo> result = kboService.findByTeamName(team);
        return ResponseEntity.ok(result);
    }
}

4. KboService

@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class KboService {

    private final KboRepository kboRepository;

    public List<Kbo> findByTeamName(String team){
        List<Kbo> teams = kboRepository.findByTeamName(team);
        return teams;
    }
}

5. API 요청 결과

API 요청 결과


4. ConfigServer 수정

1. kbo-service.properties 추가

spring.jpa.hibernate.ddl-auto=none
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.database.driverClassName= org.postgresql.Driver
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

server.port= 10000

spring.cloud.loadbalancer.ribbon.enabled = false
        
management.endpoints.web.exposure.include=*
management.endpoints.enabled-by-default=true

eureka.instance.preferIpAddress = true
eureka.client.registerWithEureka = true
eureka.client.fetchRegistry = true
eureka.client.serviceUrl.defaultZone = http://eurekaserver:8070/eureka/

kbo-service.properties

2. kbo-service-dev.properties 추가

# DataSource settings: set here your own configurations for the database 
spring.datasource.url = jdbc:postgresql://3.36.39.116:5432/ostock_dev
spring.datasource.username = postgres
spring.datasource.password = {cipher}f4609209a3e75d8ac79a5e3063ce151c2cd28aa431170bb06974b9421e807b6a

kbo-service-dev.properties

3. gateway-server.yml 수정

server:
  port: 8072
 
eureka:
  instance:
    preferIpAddress: true
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://eurekaserver:8070/eureka/
      
spring:
  cloud:
    loadbalancer.ribbon.enabled: false
    gateway:
      discovery.locator:
        enabled: true
        lowerCaseServiceId: true
      routes:
      - id: organization-service
        uri: lb://organization-service
        predicates:
        - Path=/organization/**
        filters:
        - RewritePath=/organization/(?<path>.*), /$\{path}
      - id: licensing-service
        uri: lb://licensing-service
        predicates:
        - Path=/license/**
        filters:
        - RewritePath=/license/(?<path>.*), /$\{path}
      - id: kbo-service
        uri: lb://kbo-service
        predicates:
        - Path=/kbo/**
        filters:
        - RewritePath=/kbo/(?<path>.*), /$\{path}
 
management:
  endpoints:
    web:
      exposure:
        include: "*"

load balancer 추가


5. Kdo-Service 파일 추가

yml 파일의 경우 필요에 따라 여러 파일이 필요할 수 있고, 그렇게 될 경우 어떤 설정부터 적용할 것인지 우선순위가 필요하다.

# 설정파일 적용 우선순위
1. application.yml
2. application-name.yml 
→ user-service.yml
3. application-name-<profile>.yml 
→ user-service-dev.yml

1. bootstrap.yml

spring:
  application:
    name: kbo-service
  profiles:
    active: dev
  cloud:
    config:
      uri: http://configserver:8071

2. Dockerfile

도커를 빌드하기 위해 필요한 Dockerfile을 작성한다.

#stage 1
#Start with a base image containing Java runtime
FROM openjdk:11-slim as build

# Add Maintainer Info
LABEL maintainer="Illary Huaylupo <illaryhs@gmail.com>"

# The application's jar file
ARG JAR_FILE

# Add the application's jar to the container
COPY ${JAR_FILE} app.jar

#unpackage jar file
RUN mkdir -p target/dependency && (cd target/dependency; jar -xf /app.jar)

#stage 2
#Same Java runtime
FROM openjdk:11-slim

#Add volume pointing to /tmp
VOLUME /tmp

#Copy unpackaged application to new container
ARG DEPENDENCY=/target/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app

#execute the application
ENTRYPOINT ["java","-cp","app:app/lib/*","com.example.kboservice.KboServiceApplication"]

6. 컨테이너 실행, API 호출

# docker-compose 를 통해 컨테이너들 실행
docker-compose up -d

docker-compose up -d

# Eureka Server 확인
http://localhost:8070/

eureka

# gateway를 통한 API 호출
http://localhost:8072/kbo-service/v1/kbo/team/두산 베어스

호출 결과 확인


7. 63일차 후기

새로운 서비스를 만들어 기존 클라우드 환경에 추가하는 작업을 진행하였다.

이를 위해 개발한 서비스 내에 bootstrap.yml 을 추가하여 설정 정보를 가져올 configServer의 위치, 가져올 파일 이름을 등록해주고 configServer 내에 해당 서비스를 위한 application.yml 을 추가, gateway route 정보를 추가하였다.

 

이렇게 설정정보가 외부에 있기 때문에, 마이크로서비스를 구축하기 위해서는 내 프로젝트 내에서만 수정하는 것에 그치는게 아니라 외부파일을 설정 후 가져오는 라인을 구축해야한다는 것을 알게되었다.

'Bootcamp > MSA' 카테고리의 다른 글

[MSA] 18. Ingress, PV / PVC  (0) 2023.11.02
[MSA] 17. Jenkins 설치  (0) 2023.11.01
[MSA] 15. Minikube, k9s 설치  (0) 2023.10.30
[MSA] 14. Rollback 전략, Bind Tool, AWS Instance  (0) 2023.10.27
[MSA] 13. alias, cordon, drain, AWS 활용  (0) 2023.10.26