MSA 8일차 - Chap05. 마이크로서비스 개별 기능 구현

Kim Hyen Su·2023년 10월 19일
0
post-custom-banner

5. 마이크로서비스 개별 기능 개발

🎇 회원 서비스 (추가)

회원 정보 조회 시, 주문 내역까지 함께 조회되도록 해야한다.

List<Order> orderList;

위 내용을 연관관계로 추가해야 한다.

OrderList를 따로 얻어와서 RespnseDTO에 우선 넣어주는 방향으로 진행하면 된다.

🎇 상품 서비스

기본 설정

application.yml
server:
  port: 0

spring:
  application:
    name: item-service
  datasource:
    driver-class-name: ${driver-class-name}
    url: ${url}
    username: ${username_}
    password: ${password}
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true
  profiles:
    active: db


eureka:
  client:
    fetch-registry: true # 동기적으로 마이크로서비스들과 통신 여부
    register-with-eureka: true #유레카 서버에 클라이언트 등록 여부
    service-url:
      default-zone: http://127.0.0.1:8761/eureka
  instance:
    instance-id:${spring.application.name}:${spring.application.instance-id:${random.value}}

*db 관련 설정들은 application-db 라는 프로필에 별도로 민감 정보를 저장한 상태이다.

  • 유레카 서버 등록
  • 랜덤 포트 지정 설정
  • db 연동
  • jpa 설정

Item Entitiy

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name="item")
@Getter @NoArgsConstructor
@AllArgsConstructor @Builder
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String productId;
    private String productName;
    private Long stock;
    private Long pricePerItem;

}

ItemRepository

import com.playdata.itemservice.domain.Item;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item,Long> {
    Item findByProductId(String uuid);
}

ItemService

import com.playdata.itemservice.domain.Item;
import com.playdata.itemservice.dto.RequestCreateItemDto;
import com.playdata.itemservice.dto.ResponseItemDto;
import com.playdata.itemservice.repository.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class ItemService {
    private final ItemRepository itemRepository;

    public void createItem(RequestCreateItemDto dto){
        itemRepository.save(dto.toEntity());
    }

    public List<Item> findItems(){
        return itemRepository.findAll();
    }

    public ResponseItemDto findItemById(String uuid){
        Item item = itemRepository.findByProductId(uuid);
        Optional.ofNullable(item).orElseThrow(()->{
            throw new RuntimeException("등록 되지 않은 물품 입니다.");
        });
        ResponseItemDto dto = new ResponseItemDto(item);
        return dto;
    }
}

DTO

RequestCreateItemDto
import com.playdata.itemservice.domain.Item;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.UUID;

@Getter @Setter @AllArgsConstructor
@NoArgsConstructor
public class RequestCreateItemDto {
    private String productName;
    private Long stock;
    private Long pricePerItem;

    public Item toEntity(){
        return Item.builder()
                .productId(UUID.randomUUID().toString())
                .productName(this.productName)
                .stock(this.stock)
                .pricePerItem(this.pricePerItem)
                .build();
    }
}

ResponseItemDto

import com.playdata.itemservice.domain.Item;
import lombok.*;

@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Builder
public class ResponseItemDto {
    private String productId;
    private String productName;
    private Long stock;
    private Long pricePerItem;
    private String userId;
    private String orderId;

    public ResponseItemDto(Item item){
        productId = item.getProductId();
        productName = item.getProductName();
        stock = item.getStock();
        pricePerItem = item.getPricePerItem();
    }
}

ItemController

import com.playdata.itemservice.domain.Item;
import com.playdata.itemservice.dto.RequestCreateItemDto;
import com.playdata.itemservice.dto.ResponseItemDto;
import com.playdata.itemservice.service.ItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item-service")
@RequiredArgsConstructor
public class ItemController {

    private final ItemService itemService;

    @GetMapping("health-check")
    public String checkHealth(){
        return "server is available!!";
    }

    @PostMapping("items")
    public ResponseEntity<String> registerItem(@RequestBody RequestCreateItemDto dto){
        itemService.createItem(dto);
        return ResponseEntity.status(201).body("아이템 등록에 성공했습니다.");
    }

    @GetMapping("items/all")
    public ResponseEntity<List<Item>> getAllItems(){
        List<Item> itemList = itemService.findItems();
        return ResponseEntity.status(200).body(itemList);
    }

    @GetMapping("items/{uuid}")
    public ResponseEntity<ResponseItemDto> getOne(@PathVariable String uuid){
        ResponseItemDto dto = itemService.findItemById(uuid);
        return ResponseEntity.status(200).body(dto);
    }
}

🎇 주문 서비스

기본 설정

application.yml
server:
  port: 0

spring:
  application:
    name: item-service
  datasource:
    driver-class-name: ${driver-class-name}
    url: ${url}
    username: ${username_}
    password: ${password}
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true
  profiles:
    active: db


eureka:
  client:
    fetch-registry: true # 동기적으로 마이크로서비스들과 통신 여부
    register-with-eureka: true #유레카 서버에 클라이언트 등록 여부
    service-url:
      default-zone: http://127.0.0.1:8761/eureka
  instance:
    instance-id:${spring.application.name}:${spring.application.instance-id:${random.value}}

*db 관련 설정들은 application-db 라는 프로필에 별도로 민감 정보를 저장한 상태이다.

  • 유레카 서버 등록
  • 랜덤 포트 지정 설정
  • db 연동
  • jpa 설정

Order Entity

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;

import java.time.LocalDateTime;

@Entity
@Table(name="orders")
@Getter @NoArgsConstructor @AllArgsConstructor
@Builder
public class Order {
    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String orderId;

    private Long count;

@CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

String userId;
String productId;
}

OderRepository

import com.playdata.orderservice.domain.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order,Long> {

}

OrderService

import com.playdata.orderservice.dto.RequestCreateOrderDto;
import com.playdata.orderservice.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class OrderService {
    private final OrderRepository orderRepository;

    public void createOrder(RequestCreateOrderDto dto){
        orderRepository.save(dto.toEntity());
}
}

DTO

RequestCreateOrderDto
import com.playdata.orderservice.domain.Order;
import lombok.*;

import java.time.LocalDateTime;
import java.util.UUID;

@Getter @Setter @NoArgsConstructor
@AllArgsConstructor @Builder
public class RequestCreateOrderDto {

    private String orderId;
    private Long count;
    private LocalDateTime createdAt;

String userId;
String productId;

    public Order toEntity(){
        return Order.builder()
                .count(this.count)
                .orderId(UUID.randomUUID().toString())
                .userId(this.userId)
                .productId(this.productId)
                .build();
}
}

OrderController

import com.playdata.orderservice.dto.RequestCreateOrderDto;
import com.playdata.orderservice.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("order-service")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

@GetMapping("health-check")
    public String healthCheck(){
        return "order-service server is available";
}

    @PostMapping("orders")
    public ResponseEntity<String> create(@RequestBody RequestCreateOrderDto requestCreateOrderDto){
        orderService.createOrder(requestCreateOrderDto);
        return ResponseEntity.status(HttpStatus.CREATED).body("주문이 완료되었습니다."); //201
}
}
profile
백엔드 서버 엔지니어
post-custom-banner

0개의 댓글