Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一步一步教你如何创建第一个Vert.x Web应用 #10

Closed
codefollower opened this issue Feb 2, 2016 · 3 comments
Closed

一步一步教你如何创建第一个Vert.x Web应用 #10

codefollower opened this issue Feb 2, 2016 · 3 comments

Comments

@codefollower
Copy link
Owner

Vert.x是一个支持多语言的运行在JVM之上的开发平台,可以用于构建各种应用,包括web应用,这篇文章教你如何使用Maven和Vert.x创建第一个web应用。

0. 需要JDK 8

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

1. 安装Maven

如果已经安装了,可以跳过这一步

下载Maven: http://archive.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.zip
下文我都以Windows 7为例,如果使用Linux,需要修改一下相应的目录名,
把apache-maven-3.3.9-bin.zip解压到D:\apache-maven-3.3.9目录(也可以选择其他目录),
然后把D:\apache-maven-3.3.9\bin加入Path环境变量,
打开一个命令行窗口,输入mvn -version,能看到类似下面的信息:
Apache Maven 3.3.9

2. 创建一个空的Maven项目

mvn archetype:generate -DgroupId=my.test -DartifactId=vertx_app -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

如果在D:\目录下运行上面的命令,会生成一个D:\vertx_app目录,
打开D:\vertx_app\pom.xml文件,用下面的内容替换掉:
(用Vert.x开发最简单的Web应用只需要依赖vertx-web,测试Vert.x应用需要用到vertx-unit)

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>my.test</groupId>
  <artifactId>vertx_app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>vertx_app</name>
  <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-unit</artifactId>
            <version>3.2.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>io.vertx.core.Starter</Main-Class>
                                        <Main-Verticle>my.test.HelloWorldVerticle</Main-Verticle>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                            <artifactSet />
                            <outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3. Hello World

文件位置: vertx_app\src\main\java\my\test\HelloWorldVerticle.java

package my.test;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;

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

        // 处理http://localhost:8080/
        Route route = router.route("/");
        route.handler(routingContext -> {
            routingContext.response().end("Hello World!");
        });

        // 处理http://localhost:8080/date
        route = router.route("/date");
        route.handler(routingContext -> {
            HttpServerResponse response = routingContext.response();
            response.putHeader("content-type", "text/plain");
            response.end("date: " + new java.util.Date());
        });

        server.requestHandler(router::accept).listen(8080);
    }
}

4. 测试类

文件位置:vertx_app\src\test\java\my\HelloWorldVerticleTest.java

package my.test;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(VertxUnitRunner.class)
public class HelloWorldVerticleTest {

    private Vertx vertx;

    @Before
    public void setUp(TestContext context) {
        vertx = Vertx.vertx();
        vertx.deployVerticle(HelloWorldVerticle.class.getName(), context.asyncAssertSuccess());
    }

    @After
    public void tearDown(TestContext context) {
        vertx.close(context.asyncAssertSuccess());
    }

    @Test
    public void testHelloWorldVerticle(TestContext context) {
        final Async async = context.async();

        vertx.createHttpClient().getNow(8080, "localhost", "/", response -> {
            response.handler(body -> {
                context.assertTrue(body.toString().contains("Hello"));
                async.complete();
            });
        });

        vertx.createHttpClient().getNow(8080, "localhost", "/date", response -> {
            response.handler(body -> {
                context.assertTrue(body.toString().contains("date"));
                async.complete();
            });
        });
    }
}

5. 使用Maven测试

mvn test

6. 使用Maven打包

mvn clean package -Dmaven.test.skip=true

7. 运行

java -jar target/vertx_app-1.0-SNAPSHOT-fat.jar
如果要停止请按ctrl + c

8. 在浏览器中查看结果

http://localhost:8080/
http://localhost:8080/date

9. 参考文档:

Vert.x-Web Manual
Introduction to Vert.x

@heng4fun
Copy link

支持, 希望有更深入分析的文章

@liukeqing
Copy link

cool...

@huhaifan
Copy link

huhaifan commented Aug 7, 2017

初学vert.x,关于vert.x有些困惑,看很多地方简介都是对比Node.js,那么vert.x对于Node.js有什么优点呢? 和现在比较流行的springboot+rpc+mq的微服务相比又有什么优劣势呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants