반응형

본 내용은 인프런의 이도원 님의 강의 "Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)" 내용을 바탕으로 정리한 내용입니다.

 

EurekaDiscoveryService 프로젝트 생성

  • Spring Boot : 3.2.6
  • Java : 17
  • Project Name : EurekaDiscoveryService
  • Dependencies : Eureka Server

EurekaDiscoveryServiceApplication

package com.example.EurekaDiscoveryService;  

import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;  

@SpringBootApplication
@EnableEurekaServer
public class EurekaDiscoveryServiceApplication {  

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

}
  • Eureka 서버로 사용하기 위해 @EnableEurekaServer을 추가한다.
  • EnableEurekaServerSpring Cloud Netflix Eureka에서 Eureka 서버를 설정할 때 사용하는 애노테이션이다.
  • Eureka는 서비스 디스커버리를 제공하는 도구로, 마이크로서비스 아키텍처에서 개별 서비스들이 동적으로 자신의 위치를 등록하고 다른 서비스의 위치를 검색할 수 있도록 도와줍니다.

applcaition.yml

server:  
  port: 8761  

spring:  
  application:  
    name: EurekaDiscoveryService  

eureka:  
  client:  
    register-with-eureka: false  
    fetch-registry: false
  • 서버 포트를 8761로 설정하고, 클라이언트로서 작동하지 않도록 설정.

GatewayService 생성

  • Spring Boot : 3.2.6
  • Java : 17
  • Project Name : GatewatService
  • Dependencies : Spring Boot DevTools, Eureka Discovery Client, Gateway

application.yml

server:  
  port: 8080  

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

spring:  
  application:  
    name: GatewayService  
  cloud:  
    gateway:  
      default-filters:  
        - name: GlobalFilter  
          args:  
            baseMessage: Spring Cloud Gateway GlobalFilter  
            preLogger: true  
            postLogger: true  
      routes:  
        - id: UserService # 사용자 서비스  
          uri: lb://UserService  
          predicates:  
            - Path=/userService/**  
        - id: CatalogService # 제품 서비스  
          uri: lb://CatalogService  
          predicates:  
            - Path=/catalogService/**  
        - id: OrderService # 주문 서비스  
          uri: lb://OrderService  
          predicates:  
            - Path=/orderService/**
  • 라우팅 설정으로 /userService/**, /catalogService/**, /orderService/**와 같은 URL 요청을 각각의 마이크로서비스로 전달.
  • 포트가 아닌 url naming을 통해 편하게 접근이 가능하다.

UserService 프로젝트 생성

  • Spring Boot : 3.2.6
  • Java : 17
  • Project Name : UserService
  • Dependencies : Spring Boot DevTools, Lombok, Spring Web, Eureka Discovery Client

UserService 기능

  • 회원가입
  • 로그인
  • 회원정보 조회
  • 회원 정보 수정 및 삭제

UserServiceApplication 수정

package com.example.UserService;  

import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;  

@SpringBootApplication  
@EnableDiscoveryClient  
public class UserServiceApplication {  

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

}
  • @EnableDiscoveryClient: 마이크로서비스로 Eureka 서버에 등록되도록 설정.

application.yml

server:  
  port: 0 # 랜덤포트  

spring:  
  application:  
    name: UserService  
  datasource:  
    driverClassName: org.mariadb.jdbc.Driver  
    url: jdbc:mariadb://localhost:3306/shop_db?characterEncoding=UTF-8&serverTimezone=UTC  
    username: root  
    password: 1234  

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

logging:  
  level:  
    com.example.UserService: DEBUG  

greeting:  
  message: Welcome to the Simple E-Commerce.
  • 랜덤 포트(port: 0)를 사용하여 다중 인스턴스 실행 가능.
  • MariaDB 설정 포함.
  • Eureka 클라이언트 설정을 통해 서버와 통신.
  • 사용자 정의 메시지(greeting.message) Welcome message 추가.

UserControler

package com.example.UserService.controller;  

import com.example.UserService.controller.vo.Greeting;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.core.env.Environment;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  

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

    // application.yml 의 프로퍼티 값을 사용한다.  
    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";  
    }  

    /**  
     * http://book-m3o2tu0464:49221/welcome 호출시 프로퍼티 greeting.message 값이 출력된다.  
     * @return  
     */  
    @GetMapping("/welcome")  
    public String welcome(){  
        //return env.getProperty("greeting.message");  
        return greeting.getMessage();  
    }  
}
  • /health_check: 서비스 상태 확인.
  • /welcome: greeting.message 값을 반환.

Greeting

package com.example.UserService.controller.vo;  

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

@Component  
@Data  
public class Greeting {  
    @Value("${greeting.message}") // application.yml 값을 가져온다.  
    private String message;  
}
  • @Value를 사용하여 application.yml의 프로퍼티 값을 읽어오기 위한 컴포넌트.

h2 데이터베이스 연동

pom.xml

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->  
<dependency>  
    <groupId>com.h2database</groupId>  
    <artifactId>h2</artifactId>  
    <version>1.3.176</version>  
    <scope>runtime</scope>  
</dependency>
  • h2 라이브러리 추가

application.yml

spring:  
  application:  
    name: UserService  
  h2: # h2 데이터베이스 설정  
    console:  
      enabled: true  
      settings:  
        web-allow-others: true  # 외부접속 허용
      path: /h2-console
  • h2 데이터 베이스 설정 추가

※ h2 데이터 베이스 화면 호출 시 계속 404 에러 나와서 마리아 DB로 넘어왔다.

users 테이블 create 문

-- shop_db.users definition

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `name` varchar(50) NOT NULL,
  `user_id` varchar(255) NOT NULL,
  `encrypted_pwd` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `user_id` (`user_id`),
  UNIQUE KEY `encrypted_pwd` (`encrypted_pwd`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
반응형

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

[MSA] MicroService 구현(Spring Security)  (0) 2024.11.26
[MSA] MicroService 구현(회원가입 구현)  (0) 2024.11.26
[MSA] Gateway Filter  (0) 2024.06.29
[MSA] Spring Cloud Gateway  (0) 2024.06.29
[MSA] 스프링 클라우드란?  (0) 2023.07.24

+ Recent posts