티스토리 뷰

728x90

📦 Spring Boot + RESTHeart 연결 샘플

✅ 1. 프로젝트 기본 세팅

pom.xml

<dependencies>
    <!-- Spring Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- HTTP 요청용 라이브러리 (Spring WebClient) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <!-- JSON 직렬화 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>
  • 여기선 WebClient (Spring 5 이상)로 HTTP 호출할 겁니다.

✅ 2. application.yml (RESTHeart 서버 설정)

restheart:
  base-url: http://localhost:8080/testdb/testcollection

(※ RESTHeart가 localhost:8080에 떠 있고, testdb/testcollection을 조작할 거라고 가정합니다.)


✅ 3. RestHeartService.java (CRUD 로직)

package com.example.restheartdemo.service;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
@RequiredArgsConstructor
public class RestHeartService {

    private final WebClient webClient;

    @Value("${restheart.base-url}")
    private String baseUrl;

    // 문서 생성 (POST)
    public Mono<String> createDocument(String jsonBody) {
        return webClient.post()
                .uri(baseUrl)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(jsonBody)
                .retrieve()
                .bodyToMono(String.class);
    }

    // 문서 조회 (GET)
    public Mono<String> readDocument(String id) {
        return webClient.get()
                .uri(baseUrl + "/" + id)
                .retrieve()
                .bodyToMono(String.class);
    }

    // 문서 수정 (PATCH)
    public Mono<String> updateDocument(String id, String jsonBody) {
        return webClient.patch()
                .uri(baseUrl + "/" + id)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(jsonBody)
                .retrieve()
                .bodyToMono(String.class);
    }

    // 문서 삭제 (DELETE)
    public Mono<String> deleteDocument(String id) {
        return webClient.delete()
                .uri(baseUrl + "/" + id)
                .retrieve()
                .bodyToMono(String.class);
    }
}

✅ 4. WebClientConfig.java (WebClient Bean 등록)

package com.example.restheartdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        return WebClient.builder().build();
    }
}

✅ 5. RestHeartController.java (API 테스트용 Controller)

package com.example.restheartdemo.controller;

import com.example.restheartdemo.service.RestHeartService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/restheart")
@RequiredArgsConstructor
public class RestHeartController {

    private final RestHeartService restHeartService;

    @PostMapping
    public Mono<String> createDocument(@RequestBody String jsonBody) {
        return restHeartService.createDocument(jsonBody);
    }

    @GetMapping("/{id}")
    public Mono<String> readDocument(@PathVariable String id) {
        return restHeartService.readDocument(id);
    }

    @PatchMapping("/{id}")
    public Mono<String> updateDocument(@PathVariable String id, @RequestBody String jsonBody) {
        return restHeartService.updateDocument(id, jsonBody);
    }

    @DeleteMapping("/{id}")
    public Mono<String> deleteDocument(@PathVariable String id) {
        return restHeartService.deleteDocument(id);
    }
}

✅ 사용 방법

📌 문서 생성 (POST)

POST http://localhost:8080/api/restheart
Content-Type: application/json

{
  "name": "John",
  "age": 30
}

→ MongoDB testdb.testcollection에 문서가 삽입됩니다.


📌 문서 조회 (GET)

GET http://localhost:8080/api/restheart/{ObjectId}

→ 해당 MongoDB 문서를 조회합니다.


📌 문서 수정 (PATCH)

PATCH http://localhost:8080/api/restheart/{ObjectId}
Content-Type: application/json

{
  "age": 31
}

→ 해당 MongoDB 문서의 age를 수정합니다.


📌 문서 삭제 (DELETE)

DELETE http://localhost:8080/api/restheart/{ObjectId}

→ 해당 MongoDB 문서를 삭제합니다.


📑 중요한 주의사항

항목 주의점

항목 주의점
Content-Type 항상 application/json 사용
인증 필요한 경우 WebClient에 Authorization 헤더 추가
실패 처리 .onErrorResume 로 에러 핸들링 추가 가능
ObjectId 주의 MongoDB _id는 ObjectId 타입임 (String 형태로 다루기)

📢 요약

항목 설명
Framework Spring Boot (WebFlux 사용)
HTTP Client WebClient
CRUD 연동 방식 REST API 호출 (POST, GET, PATCH, DELETE)
MongoDB 조작 RESTHeart를 통해 MongoDB를 API로 조작
인증 추가 가능성 필요 시 Authorization 헤더 추가

 

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함