年轻人的第一个Vert.x程序

创建目录结构:

helloworld
  src
    main
      java

helloworld目录下创建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>vertx.example</groupId>
    <artifactId>helloworld</artifactId>
    <version>3.9.5-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>3.9.5</version>
        </dependency>
    </dependencies>

</project>

helloword/src/main/java目录下创建java文件MyFirstVerticle.java


import io.vertx.core.AbstractVerticle;

public class MyFirstVerticle extends AbstractVerticle {

    @Override
    public void start() {
        System.out.println("Hello World!");
    }

}

用IDEA打开helloworld目录, 点击右上角创建一个application运行配置。
属性配置如下:

name: VertxLauncher
Main Class: io.vertx.core.Launcher
Program arguments: run MyFirstVerticle
working directory: $ModuleFileDir$

然后运行, 会看到以下输出:


Hello World!
十二月 29, 2020 6:42:57 下午 io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
信息: Succeeded in deploying verticle

但是你会发现程序并没有退出, 而是一直在运行

因为你不是直接写一个main方法运行的, 而是用Vert.xLauncher运行的(关于Launcher以后有机会再说), 那么怎样才可以让程序退出呢?
答案就是在start方法中增加一句this.vertx.close();

    @Override
    public void start() {
        System.out.println("Hello World!");
        this.vertx.close();
    }

其实直接写个main方法运行helloworld也很简单, 但是为什么不这样做呢? 因为Vert.x有自己的一套运行环境, 我们从一开始就用它的运行环境来执行我们的代码对我们后面的学习有好处。

最后提供一下, 用main方法运行这个helloworld的代码吧^_^

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;

public class MyFirstVerticle extends AbstractVerticle {

    @Override
    public void start() {
        System.out.println("Hello World!");
        this.vertx.close();
    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(MyFirstVerticle.class.getName());
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容