본문 바로가기
Java

[Java] Vert.x HTTP 기본 예제

by teamnova 2024. 3. 31.

 

오늘은 Java으로 Vert.x 프레임워크를 사용해보겠습니다. 

 

 

디렉토리 구조는 아래와 같습니다.

 

 

 

아래 코드는 터미널에서 curl을 통해 테스트해보시면 됩니다.

  GET 요청 (아이템 조회)
  curl -X GET http://localhost:8080/item/1

  POST 요청 (아이템 생성)
  curl -X POST http://localhost:8080/item -H "Content-Type: application/json" -d '{"name":"NewItem", "description":"Description of new item"}'

  PUT 요청 (아이템 업데이트)
  curl -X PUT http://localhost:8080/item/1 -H "Content-Type: application/json" -d '{"name":"UpdatedItem", "description":"Updated description"}'

  DELETE 요청 (아이템 삭제)
  curl -X DELETE http://localhost:8080/item/1

 

 

 

 

아래 파일은 HttpServerExample.java으로 파일을 생성하시면 됩니다.

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

import java.time.LocalDateTime;

public class HttpServerExample extends AbstractVerticle {

    @Override
    public void start() {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);

        // BodyHandler를 추가하여 요청 본문을 읽을 수 있게 함
        router.route().handler(BodyHandler.create());

        router.get("/").handler(this::handleRootRequest);
        router.get("/item/:id").handler(this::handleGetItem);
        router.post("/item").handler(this::handleCreateItem);
        router.put("/item/:id").handler(this::handleUpdateItem);
        router.delete("/item/:id").handler(this::handleDeleteItem);

        server.requestHandler(router).listen(8080, result -> {
            if (result.succeeded()) {
                System.out.println("Server is now listening!");
            } else {
                System.out.println("Failed to bind!");
            }
        });
    }

    private void logRequest(RoutingContext context) {
        String method = context.request().method().name();
        String uri = context.request().uri();
        String timestamp = LocalDateTime.now().toString();
        System.out.println("Received " + method + " request for " + uri + " at " + timestamp);
    }

    private void handleRootRequest(RoutingContext context) {
        logRequest(context);
        context.response()
                .putHeader("content-type", "text/plain")
                .end("Hello from Vert.x!");
    }

    private void handleGetItem(RoutingContext context) {
        try {
            logRequest(context);
            String itemId = context.request().getParam("id");
            context.response()
                    .putHeader("content-type", "application/json")
                    .end(new JsonObject().put("id", itemId).put("name", "Item " + itemId).encode());
        } catch (Exception e) {
            handleException(context, e);
        }
    }

    private void handleCreateItem(RoutingContext context) {
        try {
            logRequest(context);
            JsonObject item = context.getBodyAsJson();
            // 아이템 생성 로직 구현
            context.response()
                    .setStatusCode(201)
                    .putHeader("content-type", "application/json")
                    .end(new JsonObject().put("message", "Item created").put("item", item).encode());
        } catch (Exception e) {
            handleException(context, e);
        }
    }

    private void handleUpdateItem(RoutingContext context) {
        try {
            logRequest(context);
            String itemId = context.request().getParam("id");
            JsonObject item = context.getBodyAsJson();
            // 아이템 업데이트 로직 구현
            context.response()
                    .putHeader("content-type", "application/json")
                    .end(new JsonObject().put("message", "Item updated").put("id", itemId).put("item", item).encode());
        } catch (Exception e) {
            handleException(context, e);
        }
    }

    private void handleDeleteItem(RoutingContext context) {
        try {
            logRequest(context);
            String itemId = context.request().getParam("id");
            // 아이템 삭제 로직 구현
            context.response()
                    .putHeader("content-type", "application/json")
                    .end(new JsonObject().put("message", "Item deleted").put("id", itemId).encode());
        } catch (Exception e) {
            handleException(context, e);
        }
    }

    private void handleException(RoutingContext context, Exception e) {
        e.printStackTrace();
        context.response()
                .setStatusCode(500)
                .putHeader("content-type", "text/plain")
                .end("Internal Server Error");
    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new HttpServerExample());
    }
}

 

 

 

 

아래 파일은 pom.xml으로 만드시면 됩니다.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yourcompany</groupId>
    <artifactId>your-artifact</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <vertx.version>4.4.4</vertx.version> <!-- Vert.x 버전 -->
    </properties>

    <dependencies>
        <!-- Vert.x core dependency -->
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
        </dependency>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>4.4.4</version>
            <scope>compile</scope>
        </dependency>

        <!-- 추가적인 의존성이 필요한 경우 여기에 추가 -->
    </dependencies>

    <build>
        <plugins>
            <!-- 필요한 경우 Maven 플러그인 구성 추가 -->
        </plugins>
    </build>
</project>

 

 

실행 화면