공부/Spring

Spring Cloud로 개발하는 마이크로서비스 애플리케이션_Users Microservice-1-1

데부한 2023. 2. 25. 21:39
반응형

 

 

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

Users Microservice 개요

APIs

기능 URI(API Gateway 사용 시) URI(API Gateway 미사용 시) HTTP Method
사용자 정보 등록 /user-service/users /users POST
전체 사용자 조회 /user-service/users /users GET
사용자 정보,
주문 내역 조회
/user-service/users/{user_id} /users/{user_id} GET
작동 상태 확인 /user-service/users/health_check /users/health_check GET
환영 메시지 /user-service/users/welcome /users/welcome GET

 

 

Users Microservice - 프로젝트 생성

강의에서는 Maven을 사용했고 나는 Gradle을 선택했다. Java 버전은 강의에서 11, 나는 17을 선택했다.

 

강의에선 Spring Boot 버전을 2.4.2를 선택했고, 나는 원래 2.7.X대 버전을 선택하려했으나 3.0.X 버전을 경험해보고 싶어서 3.0.3을 선택했다.

Dependencies는 총 4가지를 추가했다.

  • Lombok
  • Spring Boot DevTools
  • Spring Web
  • Eureka Discovery Client

 

 

application class

애플리케이션 클래스에 유레카 사용을 위한 어노테이션을 추가한다.

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication { ... }

 

 

application.yml

server:
  port: 0

spring:
  application:
    name: user-service

eureka:
  instance:
    instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka

서버 포트는 랜덤 포트를 사용한다.

 

 

Controller 생성

 

@RestController
@RequestMapping("/")
public class UserController {

    @GetMapping("/health_check")
    public String status() {
        return "It's Working in User Service";
    }
}

 

 

mac 터미널로 유레카 서버 구동

이클립스를 여러 개 띄워놓고 사용하면 메모리를 많이 사용하게 되므로 터미널에서 유레카 서버를 구동한다.

프로젝트 폴더로 이동 후 아래 명령어를 입력하면 서버가 구동된다.

./gradlew bootrun

 

구동 후 유레카 페이지가 잘 뜨는지 확인한다.

http://127.0.0.1:8761/

페이지가 정상적으로 보이면 user-service를 실행한다.

유레카 대시보드 페이지 새로고침하면 인스턴스가 등록된 걸 볼 수 있다.

 

저 초록색 링크를 클릭하면 404 페이지를 볼 수 있다. 주소 창에 포트 뒤에 있는 주소는 다 날려버리고 /health-check를 입력해서 작성한 컨트롤러를 호출한다.

 

Welcome 메세지 설정

application.yml에 아래 코드를 추가한다. 참고로 아래 코드는 기존 스프링부트에 등록되어있는 설정들이 아니라 사용자가 임의로 작성하는 설정이다.

greeting:
  message: Welcome to the Simple E-commerce.

 

그리고 컨트롤러에 아래 코드를 추가한다.

public class UserController {

    private Environment env;

    @Autowired
    public UserController(Environment env){
        this.env = env;
    }
    
    //... 생략
    
    @GetMapping("/welcome")
    public String welcome() {
        return env.getProperty("greeting.message");
    }
 }

Environment 객체를 사용해 application.yml에 있는 설정을 가져온다. 의존성 주입은 생성자 주입을 사용한다. 필드 주입보다 생성자 주입 방법을 더 권장하는데, IoC 컨테이너는 생성자에 전달하기 전에 생성자에 제공된 모든 인스턴스가 사용한지 확인하기 때문에 NullPointException을 방지할 수 있어 모든 종속성이 로드 되었는지 확인하기 위한 코드를 작성할 필요가 없기 때문이다.

서버 재실행 후 크롬에서 확인한다.

 

 

application.yml 값을 가져오는 다른 방법

Greeting.java 생성

 

@Component
@Data
public class Greeting {
    
    @Value("${greeting.message}")
    private String message;
    
}

@Value 어노테이션으로 application.yml에 있는 값을 가져올 수 있다. Bean을 만들었으니 이제 컨트롤러에서 사용하면 된다.

 

public class UserController {

    private Environment env;

    private Greeting greeting;

    @Autowired
    public UserController(Environment env, Greeting greeting){
        this.env = env;
        this.greeting = greeting;
    }
    
    //생략...
    
    @GetMapping("/welcome")
    public String welcome() {
        //return env.getProperty("greeting.message");
        return greeting.getMessage();
    }
 }

 

 

서버 재실행 후 크롬에서 확인한다.

 

 

 

Users Microservice - H2 데이터베이스 연동

  • build.gradle에 dependencies 추가
runtimeOnly 'com.h2database:h2' // 실행시에만 필요한 라이브러리이기 때문에 runtimeOnly 로 지정

 

  • application.yml h2 설정
spring:
  application:
    name: user-service
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
      path: /h2-console

web-allow-others : 웹에서 접속 허용할지?

path: 웹 브라우저에서 h2 접속을 위한 주소

 

서버 재실행 후 크롬에서 확인한다.

http://192.168.0.2:64092/h2-console 입력

위 상태에서 Test Connection 버튼을 클릭하면 mem:testdb를 찾을 수 없다는 에러가 발생한다.

H2 데이터베이스에서 1.4.198 버전부터 보안상의 문제로 자동 데이터베이스 생성 기능을 막아두었다고 한다. 그렇기 때문에 DB 파일이 생성되지 않고 있어 에러가 발생하는 것이다. 강의에서는 1.4.198 이전 버전으로 낮추는 방법을 선택했다. 나는 구글링으로 좀 더 나은 방법을 찾았다.

 

JPA를 이용한 테이블 생성

강의 목차를 보면 어차피 JPA를 사용하기 때문에 JPA 더미 데이터를 이용해 DB 생성을 유도했다.

  •  application.yml
spring:
  application:
    name: user-service
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
      path: /h2-console
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true

JPA 관련 설정을 추가한다.

 

  • build.gradle

JPA 디펜던시를 추가한다.

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

 

  • Entity 생성
@Entity
public class Dummy {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
}

 

서버 재실행 후 h2 페이지로 접속

Test Connection을 누르면 성공했다는 메시지를 볼 수 있다.

 

 

 


- 출처 : 인프런 Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) 강의

반응형