Users Microservice (1)

김준영·2023년 3월 8일
1

Spring Cloud + MSA

목록 보기
6/9
post-thumbnail

Users Microservice


사용자(회원)에 관한 기능들을 모아둔 서비스이다.

비즈니스 로직은 Spring Boot와 Spring Cloud를 사용할 예정이다.

데이터베이스는 내장 데이터베이스인 H2를 사용할 예정이다.

Features

  • 신규 회원 등록
  • 회원 로그인
  • 상세 정보 확인
  • 회원 정보 수정/삭제
  • 상품 주문
  • 주문 내역 확인

APIs

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

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

greeting:
  message: Welcome to the Simple E-commerce

랜덤포트를 사용하기위해 서버 포트를 0으로 지정했다.

유레카에 등록하면 랜덤포트라고 해도 0번으로 여러 서비스가 뭉쳐서 보인다. 그래서 각 서비스를 분간하기 위해 instance-id를 지정했다.

유레카에 등록하고 정보를 받아오는것에 대해 true로 설정했다.

defaultZone은 유레카 서버 주소이다.

Controller


@RestController
@RequestMapping("/")
public class UserController {
    private Environment env;

    @Autowired
    private Greeting greeting;

    @Autowired
    public UserController(Environment env) {
        this.env = env;
    }

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

    @GetMapping("/welcome")
    public String welcome(){
//        return env.getProperty("greeting.message");
        return greeting.getMessage();
    }
}

health_check

간단한 서비스 상태를 나타내기위해 작성했다.

welcome

greeting:
  message: Welcome to the Simple E-commerce

간단한 서비스에 대해 알려주기위해 application.yml파일에 위 코드를 작성하고 2가지 방법으로 불러왔다.

  1. private Environment env;
    return env.getProperty("greeting.message");
  2. vo 패키지를 하나 만들고 거기에 Greeting이라는 자바파일을 하나 만든다.
package com.example.userservice.vo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class Greeting {

    @Value("${greeting.message}")
    private String message;

}

@Value 어노테이션을 사용하여 yml파일에 있는 메시지를 가져와 보여준다.

테스트

유레카 서버는 전에 작성했던 그 파일 그대로 사용했다.

유레카 서버를 킨 후, 위 파일을 실행하여 유레카 서버에 들어가면 등록이 되어있을것이다.

유저 서비스의 도메인으로 가서 /health_check, /welcome으로 정상 구동을 확인하면 끝난다.

profile
ㅎㅎ

0개의 댓글