Vert.x应用示例

最近更新时间:2022-04-25 16:47:09

查看PDF

1. pom依赖

<properties>
        <vertx.version>4.0.0</vertx.version>
   <project.version>2.3.0</project.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cloudevents</groupId>
            <artifactId>cloudevents-http-vertx</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cloudevents</groupId>
            <artifactId>cloudevents-json-jackson</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.0-alpha6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>2.0.0-alpha6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
        </dependency>
    </dependencies>

2. 监听端口资源配置

Http Server启动端口可以通过resources/application.properties文件配置

server.port=8080

3. 创建Vert.x Http Server服务,注册请求路由

package io.cloudevents.examples.vertx;

import io.cloudevents.examples.vertx.handle.EventInvokeHandle;
import io.cloudevents.examples.vertx.handle.HealthCheckHandle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class CloudEventServerVerticle extends AbstractVerticle {

    @Override
    public void start() {
        String serverPort = loadHttpServerPort();
        if (serverPort == null || serverPort.equals("")) {
            log.error("Usage: HTTPServer <port>");
            return;
        }
        final int port = Integer.parseInt(serverPort);

        // Create HTTP server.
        HttpServer server = vertx.createHttpServer();

        //创建router对象
        Router router = Router.router(vertx);

        //注册health check地址
        router.get("/health").handler(new HealthCheckHandle());
        //注册event-invoke地址
        router.post("/event-invoke").handler(new EventInvokeHandle());
        // 将请求交给路由处理
        server.requestHandler(router).exceptionHandler(System.out::println).listen(port, res -> {
            if (res.succeeded()) {
                System.out.println(
                        "Server listening on port: " + res.result().actualPort()
                );
            } else {
                System.err.println(res.cause().getMessage());
            }
        });
    }

    public static String loadHttpServerPort() {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = ClassLoader.getSystemResourceAsStream("application.properties");
            properties.load(inputStream);
            String port = properties.getProperty("server.port");
            log.info("Http Server Port: {}", port);
            return port;
        } catch (Exception e) {
            log.error("Load Properties From Config error", e);
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("Close InputStream error", e);
                }
            }
        }
    }

}

4. 添加Main函数,部署Vert.x服务

package io.cloudevents.examples.vertx;

import io.vertx.core.Vertx;

public class VertxHTTPServer {

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

5. 添加Handler实现类,用于处理不同的路由请求

健康检查Handler

package io.cloudevents.examples.vertx.handle;

import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HealthCheckHandle implements Handler<RoutingContext> {
    @Override
    public void handle(RoutingContext context) {
        log.info("receive health check");
        context.response().end("Hands Up");
    }
}

事件函数请求Handler

package io.cloudevents.examples.vertx.handle;

import io.cloudevents.CloudEventData;
import io.cloudevents.core.message.MessageReader;
import io.cloudevents.http.vertx.VertxMessageFactory;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

@Slf4j
public class EventInvokeHandle implements Handler<RoutingContext> {
    @Override
    public void handle(RoutingContext context) {
        VertxMessageFactory.createReader(context.request()).map(MessageReader::toEvent)
                .onSuccess(event -> {
                    // Print out the event.
                    log.info("receive event : {}", event);
                    log.info("specVersion: {}", event.getSpecVersion());
                    Optional.ofNullable(event.getData()).map(CloudEventData::toBytes).map(String::new).ifPresent(data ->
                            log.info("receive event data: {}", data));
                    Optional.ofNullable(event.getExtension("ak")).map(Object::toString).ifPresent(System.out::println);
                    // Write the same event as response in binary mode.
                    VertxMessageFactory.createWriter(context.response()).writeBinary(event);
                })
                .onFailure(System.err::println);
    }
}

6. Maven编译打包

在pom.xml文件中添加maven-assembly-plugin插件

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>
                                    io.cloudevents.examples.vertx.VertxHTTPServer
                                </mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                        <appendAssemblyId>false</appendAssemblyId>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>

</build>

使用下面命令将代码和及其依赖打包成可执行的jar包。

maven package

编译后的jar包位于项目文件内的target目录内。

7. Gradle编译打包

build.gradle配置文件如下:

plugins {
    id 'java'
    id 'com.github.johnrengelman.shadow' version '7.1.2'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}


repositories {
    mavenCentral()
}

dependencies {
    implementation 'io.cloudevents:cloudevents-http-vertx:2.3.0'
    implementation 'io.cloudevents:cloudevents-json-jackson:2.3.0'
    implementation 'org.slf4j:slf4j-api:2.0.0-alpha6'
    implementation 'org.slf4j:slf4j-simple:2.0.0-alpha6'
    implementation 'io.vertx:vertx-web:4.0.0'
    implementation 'io.vertx:vertx-core:4.0.0'
    implementation "org.projectlombok:lombok:1.18.22"
    annotationProcessor "org.projectlombok:lombok:1.18.22"
}

shadowJar {
    manifest {
        attributes 'Main-Class': 'io.cloudevents.examples.vertx.VertxHTTPServer'
    }
}

test {
    useJUnitPlatform()
}

在项目的根目录下执行下面命令打包

gradle shadow

编译后的jar包位于项目文件内的build/libs目录下。
如果显示编译失败,请根据输出的编译错误信息调整代码。

文档内容是否对您有帮助?

根本没帮助
文档较差
文档一般
文档不错
文档很好

在文档使用中是否遇到以下问题

内容不全,不深入
内容更新不及时
描述不清晰,比较混乱
系统或功能太复杂,缺乏足够的引导
内容冗长

更多建议

0/200

评价建议不能为空

提交成功!

非常感谢您的反馈,我们会继续努力做到更好!

问题反馈