JSCODE Logo
프로그래밍 과외블로그후기멘토진
회사명 : JSCODE대표 : 박재성사업자 등록번호 : 244-22-01557통신판매업 : 제 2023-인천미추홀-0381 호
학원 명칭 : 제이에스코드(JSCODE)원격학원학원설립ㆍ운영 등록번호 : 제6063호

서울특별시 구로구 경인로 20가길 11(오류동, 아델리아)

Copyright ⓒ 2025 JSCODE - 최상위 현업 개발자들의 프로그래밍 교육 All rights reserved.

이용약관개인정보처리방침
← 블로그 목록으로 돌아가기

[실습] 특정 게시글 조회 API 만들기

JSCODE 박재성
JSCODE 박재성
2025-12-06
author
JSCODE 박재성
category
MSA
createdAt
Dec 6, 2025
series
비전공자도 이해할 수 있는 MSA 입문/실전
slug
practice-create-post-lookup-api
type
post
updatedAt
Dec 6, 2025 05:43 AM

✅ 특정 게시글 조회 API 만들기

board-service에서 아래 코드 작성하기
  1. Response DTO 만들기
    1. dto/BoardResponseDto
      public class BoardResponseDto { private Long boardId; private String title; private String content; private UserDto user; public BoardResponseDto(Long boardId, String title, String content, UserDto user) { this.boardId = boardId; this.title = title; this.content = content; this.user = user; } public Long getBoardId() { return boardId; } public String getTitle() { return title; } public String getContent() { return content; } public UserDto getUser() { return user; } }
       
      dto/UserDto
      public class UserDto { private Long userId; private String name; public UserDto(Long userId, String name) { this.userId = userId; this.name = name; } public Long getUserId() { return userId; } public String getName() { return name; } }
      • 게시글 조회 API의 응답값으로 userId와 name만 필요하기 때문에 위와 같이 코드를 작성했다.
       
  1. user-service의 API와 통신할 코드 작성하기
    1. 이 프로젝트에서는 외부 API 통신을 할 때 RestClient라는 라이브러리를 사용할 것이다. ‘MSA니까 반드시 WebClient를 써야돼’라는 건 없다. RestTemplate를 써도 되고 WebClient를 써도 되고 FeignClient를 써도 된다. API 통신을 할 수 있는 라이브러리라면 어떤 라이브러리를 사용해도 상관없다.
      resources/application.yml
      server: port: 8081 spring: datasource: url: jdbc:mysql://localhost:3307/board-db # DB 주소 username: root # DB 계정 password: password # DB 비밀번호 driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true client: user-service: url: http://localhost:8080
       
      dto/UserResponseDto (사용자 조회 API 응답값을 담을 DTO)
      public class UserResponseDto { private Long userId; private String email; private String name; public Long getUserId() { return userId; } public String getEmail() { return email; } public String getName() { return name; } }
       
      client/UserClient
      @Component public class UserClient { private final RestClient restClient; public UserClient( @Value("${client.user-service.url}") String userServiceUrl ) { this.restClient = RestClient.builder() .baseUrl(userServiceUrl) .build(); } public UserResponseDto fetchUser(Long userId) { return this.restClient.get() .uri("/users/{userId}", userId) .retrieve() .body(UserResponseDto.class); } }
       
  1. Service 로직 작성하기
    1. service/BoardService
      @Service public class BoardService { private final BoardRepository boardRepository; private final UserClient userClient; public BoardService(BoardRepository boardRepository, UserClient userClient) { this.boardRepository = boardRepository; this.userClient = userClient; } ... public BoardResponseDto getBoard(Long boardId) { // 게시글 불러오기 Board board = boardRepository.findById(boardId) .orElseThrow(() -> new IllegalArgumentException("게시글을 찾을 수 없습니다.")); // user-service로부터 사용자 정보 불러오기 UserResponseDto userResponseDto = userClient.fetchUser(board.getUserId()); // 응답값 조합하기 UserDto userDto = new UserDto( userResponseDto.getUserId(), userResponseDto.getName() ); BoardResponseDto boardResponseDto = new BoardResponseDto( board.getBoardId(), board.getTitle(), board.getContent(), userDto ); return boardResponseDto; } }
       
  1. Controller 로직 작성하기
    1. @RestController @RequestMapping("/boards") public class BoardController { private final BoardService boardService; public BoardController(BoardService boardService) { this.boardService = boardService; } ... @GetMapping("/{boardId}") public ResponseEntity<BoardResponseDto> getBoard(@PathVariable Long boardId) { BoardResponseDto boardResponseDto = boardService.getBoard(boardId); return ResponseEntity.ok(boardResponseDto); } }
       
  1. 서버 재실행시킨 후 잘 작동하는 지 확인해보기
    1. notion image
      DB가 분리되어 있는 MSA 환경에서 사용자 정보를 포함해 게시글 정보를 잘 조회해왔다.
 
 

✅ 정리

notion image
  1. 특정 게시글 조회 API 주소(ex. GET localhost:8081/boards/1)로 요청을 보낸다.
  1. 게시글 서비스에서 사용자 정보가 필요해서, 사용자 서비스(ex. GET localhost:8080/users/1)로부터 데이터를 조회해온다.
  1. 사용자 서비스로부터 받아온 사용자 정보를 활용해 응답할 데이터를 조합한다.
  1. 사용자에게 응답한다.
 
author
JSCODE 박재성
category
MSA
createdAt
Dec 6, 2025
series
비전공자도 이해할 수 있는 MSA 입문/실전
slug
type
series-footer
updatedAt
Dec 6, 2025 05:45 AM
📎
이 글은 비전공자도 이해할 수 있는 MSA 입문/실전 강의의 수업 자료 중 일부입니다.