Vert.x3 시작~웹 응용 프레임워크 Apex

12839 단어 Vert.xRxJavaJava
Vert.x는 공식 페이지에서
JVM에서 재사용 어플리케이션을 구축하는 도구 번들입니다.
@timfox씨를 중심으로 지금 목표는 2015년 6월 22일입니다.version3을 개발합니다.이 기고문을 포함하여 몇 차례의 Vert로 나누었다.나는 x3의 이동 샘플을 실시하고 싶다.

개요


이번에 우리는 간단한 REST 서버를 이동하기 위해 공식 웹 응용 프레임워크Apex를 사용할 것이다.
Vert.x core HTTP, TCP, 파일 시스템의 접근 등 낮은 수준의 기능만 실현했고 이를 바탕으로 Apex는 웹 응용 프로그램 구축에 필요한 많은 기능을 제공했다.Node.js가 말한 Express, 루비가 말한 Sinatra와 같은 라이브러리입니다.
이번에는 간편하게 ON 메모리에 데이터를 저장하고, 데이터베이스에 데이터를 저장한 샘플은 다음 투고에서 소개할 예정이다.

전제 조건


Vert.x3 Java8이 필요합니다. 미리 Java8을 설치하십시오.다음 명령을 사용하여 Java8이 설치되었는지 확인할 수 있습니다.
$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
또한 인터리제이(IntelliJ)를 전제로 해설을 진행하고, Eclipse) 등 다른 IDE라면 적당히 다시 읽어달라.

절차.


초기 복제


먼저 원형 항목을 복제한다.
$ git clone https://github.com/p-baleine/vertx-gradle-template.git simple-rest-server
$ cd simple-rest-server
$ git remote rm origin # origin削除

IntelliJ를 통해 가져오기


IntelliJ를 시작하려면 Welcome 대화 상자에서 [Import Project]를 선택하고 클론을 생성할 디렉토리를 선택합니다.
Import Project 대화 상자에서 [Import project from external model]을 선택하고 [Gradle]을 선택하고 [Next]를 클릭한 다음 화면에서 [Finish]를 클릭합니다.

ServerVerticle


시작점인 ServerVerticle을 구현합니다.
IntelliJ에서 Project 등급 제도com.example.helloworld에서 패키지를 마우스 오른쪽 단추로 클릭하고 Refactor→Rename을 선택하여 com.example.simple로 이름을 바꿉니다.
IntelliJ로 프로젝트 등급 제도com.example.simple에서 포장된 HelloWorldVerticle를 오른쪽 단추로 클릭하고 [Refactor]→[Rename]를 선택하여 ServerVerticle로 이름을 바꿉니다.

Apex를 사용해야 하기 때문에build을 사용합니다.gradle을 열고 dependencies에 Apex를 추가합니다.
...
dependencies {
    compile 'io.vertx:vertx-core:3.0.0-milestone4'
    compile 'io.vertx:vertx-apex:3.0.0-milestone4' // 追加
}
...
IntelliJ에서 "View"→"Tool Windows"→"Gradle"을 선택하고Gradle Project 보기를 표시한 후 동기화 아이콘을 눌러 의존 관계를 읽습니다.com.example.simple 아래의 ServerVerticle 편집 내용은 다음과 같습니다.
package com.example.simple;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.apex.Router;
import io.vertx.ext.apex.RoutingContext;
import io.vertx.ext.apex.handler.BodyHandler;

import java.util.HashMap;
import java.util.Map;

public class ServerVerticle extends AbstractVerticle {

  private Map<String, JsonObject> store = new HashMap<String, JsonObject>() {
    {
      put("1", new JsonObject().put("id", "1").put("name", "Egg Whisk").put("price", 150));
      put("2", new JsonObject().put("id", "2").put("name", "Tea Cosy").put("price", 100));
      put("3", new JsonObject().put("id", "3").put("name", "Spatula").put("price", 30));
    }
  };

  @Override
  public void start() throws Exception {
    Router router = Router.router(vertx);

    router.route().handler(BodyHandler.create());

    router.get("/products").handler(this::handleListProduct);

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
  }

  private void handleListProduct(RoutingContext routingContext) {
    JsonArray result = new JsonArray();
    store.values().forEach(result::add);
    routingContext.response()
        .putHeader("Content-Type", "application/json")
        .end(result.encode());
  }
}

애플리케이션 시작


IntelliJ의 Run→Edit Configuration....탭
Run/Debug Configuration 대화 상자에서 [+]→[Application]을 선택합니다.
다음을 입력하고 [OK]를 클릭합니다.
  • Name: Simple
  • Main classs: io.vertx.core.Starter
  • Program arguments: run com.example.simple.ServerVerticle
  • IntelliJ의 "Run"→"Run'Simple"을 선택하여 IntelliJ의 콘솔에서 오류가 없음을 확인합니다.
    IntelliJ의 Run→Edit Configuration....탭

    확인


    다음 명령을 실행하여 제품 목록이 반환되는지 확인합니다.
    $ curl -D - localhost:8080/products                                    ⬡ 0.10.30 [±master]
    HTTP/1.1 200 OK
    Content-Type: application/json
    Content-Length: 123
    
    [{"id":"1","name":"Egg Whisk","price":150},{"id":"2","name":"Tea Cosy","price":100},{"id":"3","name":"Spatula","price":30}]
    

    해설

    src/main/java/com/example/simple/ServerVerticlestart 방법에서 로터의 실례를 생성한 후BodyHandler의 등록, 루트의 등록을 진행한다.나는 Express를 이용한 사람들에게 있어서 흔히 볼 수 있는 코드라고 생각한다.Apex는 BodyHandler 외에도 로그 출력을 불러올 수 있는 프로세서와 템플릿 엔진을 등록하는 프로세서를 갖추고 있으며, 사용자 정의 프로세서를 설치해 등록할 수 있다.또한 경로도 Express와 같은 느낌으로 설정할 수 있으니 자세한 내용은 애플 문서을 참조하십시오.
    이번ServerVerticle이 유일한 버틸이다.기본 동작에 따라 이 Verticle에는 하나의 이벤트-loop thread만 할당됩니다.따라서 Verticle store 필드는 이 라인의 로컬 필드가 됩니다.실제로 크기 조절을 위해 ServerVerticle은 여러 개의 실례를 시작하는데 이 경우 Verticle 간에 데이터를 공유해야 하기 때문에 다른 기구 데이터베이스와 Shared Data 등을 사용해야 한다.
    일람 표시 이외의 전체 코드여기.가 설치되어 있습니다.

    이쪽도 오세요.

  • Vert.x3 입문~Hello World Verticle
  • 좋은 웹페이지 즐겨찾기