SW/앱플랫폼

앱 플랫폼 설계 : Vertx, postman Json 주고 받기 (예제)

얇은생각 2019. 3. 21. 07:30
반응형


Gradle Project를 우선 생성해줍니다.






임의의 프로젝트 이름을 입력하고 Finish를 클릭합니다.






build.gradle 수정

아래와 같이 build.gradle 파일을 수정해줍니다. 

/*
* This build file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* user guide available at https://docs.gradle.org/4.3/userguide/java_library_plugin.html
*/

//-------- 추가됨---------------------------------------
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:4.0.2"
}
}
//--------------------------------------------------


// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'

//-------- 추가됨 ------------------------------
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: "com.github.johnrengelman.shadow"
//--------------------------------------------------

// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
    //-------- 추가됨 ------------------------------
   mavenCentral()
    maven {
     url = 'http://oss.sonatype.org/content/repositories/snapshots/'
    }
    //--------------------------------------------------
}

dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'

// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:23.0'

// Use JUnit test framework
testImplementation 'junit:junit:4.12'
}

dependencies {
compile "io.vertx:vertx-core:3.6.3"
    //-------- 추가됨---------------------------------------
compile 'io.vertx:vertx-web:3.6.3'
}

jar {
manifest {
attributes 'Main-Class': 'Launcher'
}
}

version = '1.0.0'
shadowJar {
classifier = 'fat'
mergeServiceFiles {
include 'META-INF/services/io.vertx.core.spi.VerticleFactory'
}
}
//----------------------------------------------------------------------------








그래들 프로젝트를 새로고침하여 관련된 패키지들을 다운로드합니다. 적용이 잘 안된 경우에는 이클립스를 종료 후 다시 시작합니다.







웹 서버를 구동하기 위한 코드를 작성하기 위해 다음과 같이 파일을 추가합니다. 






Launcher.java 작성

아래와 같이 작성합니다. 

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

public class Launcher {
    public static void main(String[] args) {

        //학번을 인자로 넣지 않을 경우 사용법을 알려주고 끝낸다.
        if (args.length < 1) {
            System.out.println("java -jar hw1-1.0.0-fat.jar 학번");
            args = new String[] {"12345"};
        }

        //학번 = 첫번째 인자
        String id = args[0];
        
        Vertx vertx = Vertx.vertx();
        HttpServer server = vertx.createHttpServer();
        
        //vertx에서 제공하는 web 기능을 이용합니다.
        Router router = Router.router(vertx);

        //브라우져서에서 url입력했을때 hw1처럼 행동하게 처리
        router.route("/test").handler(req->{
            req.response().end("TEST Hello "+" @" +id);
        });

        //브라우져서에서 url입력했을때 hw1처럼 행동하게 처리
        router.route().method(HttpMethod.GET).handler(req->{
            req.response().end("Hello "+" @" +id);
        });
        
        
        //vertx web에서 제공하는 http body handler를 이용합니다.
        router.route().handler(BodyHandler.create());
        
        //우리의 handler를 만듭니다.
        router.route().handler(req->{
            //body를 json 형태로 가져옵니다.
            //body가 json이 아니거나, 아무것도 보내지 않았을경우 - 처리 아직 안함..(에러 유도)
            JsonObject json = req.getBodyAsJson();
            
            System.out.println("[Request body]");
            System.out.println(req.getBodyAsString());
            
            //다음 block함수로 json을 전달
            req.put("params", json);
            
            //다음 block함수로 제어권 넘김
            //이것을 써주지 않으면 아무런 응답을 주지 않고 call이 끝나게 됩니다.
            req.next();
        });
        
    

        router.route().handler(req -> {
            //보내준 json에 학번을 같이 넣어서 보내줍니다/
            HttpServerResponse response = req.response();
            
            //json에 학번 추가!
            JsonObject json = req.get("params");
            json.put("id", id);
            
            //응답을 보내줍니다.
            response.putHeader("content-type", "application/json");
            response.end(json.toString());
        });

        //http request 처리기 : Vertx가 만들어준 Handler로 설정
        server.requestHandler(router);

        //hw1과 port가 겹치지 않게 다른 포트를 이용해보겠습니다,.
        final int port = 8080 + 2;
        server.listen(port, handler -> {
            //서버 실행 상태
            if (handler.succeeded()) {
                System.out.println("http://127.0.0.1:" + port + "/ 또는 http://ServerIP:" + port + "/");
                System.out.println("학번 : " + id);
            } else {
                System.err.println("Failed to listen on port 8080");
            }
        });
        

    }
}








작성한 Launcher.java를 다음과 같이 실행합니다. 







Console에 실행 결과가 다음과 같이 나온다면 웹 서버가 구동된 상태입니다. 이제 postman을 활용하여 웹 서버와 통신을 해보도록 하겠습니다. 








구글에 postman을 검색합니다. 







해당 사이트에서 본인 운영체제에 맞게 postman을 다운로드 받아 설치합니다.







설치하고 실행한뒤 회원가입을 하면 위와 같은 화면을 확인할 수 있습니다. 







get 방식으로 해당 주소로 json 패킷을 전송합니다. 그러면 아래와 같이 반환되는 값을 확인할 수 있습니다.







이번에는 get 방식으로 수정된 주소로 빈 패킷을 전송합니다. 그러면 아래와 같이 웹 서버에서 반환해주는 값을 확인할 수 있습니다.







이번에는 post 방식으로 같은 주소로 빈 패킷을 전송합니다. 아까와는 다르게 서버 에러 반환값을 확인할 수 있습니다.







post 방식으로 위 주소로 다음과 같은 제이슨 패킷을 전송할 경우, 반환값으로 기존의 학번과 전송한 패킷이 반환되는 것을 확인할 수 있습니다. 






기존 프로젝트 Import 해서 활용하는 법



우선 프로젝트를 추가하기 위해 File - Import 를 클릭합니다.






해당 디렉토리에 있는 프로젝트를 추가하기 위해 Existing Projects into Workspace를 선택 후 Next를 클릭합니다. 






root directory - Browse를 클릭합니다. 프로젝트에 해당하는 폴더를 선택합니다.


해당 폴더를 선택 후, 아래 해당되는 프로젝트가 생성되었는 지 확인합니다. 잘 생성되었다면 Finish를 눌러줍니다.






프로젝트가 잘 추가가 되었다면 빌드에 필요한 패키지들을 자동으로 다운로드 받아옵니다. 그렇지 않은 경우, file - gradle - refresh gradle project를 클릭해 그래들 프로젝트를 새로고침합니다. 추가적으로 이클립스를 껐다 켜야 하는 경우가 있으므로 이클립스를 다시 시작해줍니다.

반응형