Vert.x初探
Eclipse Vert.x是一个用于在JVM上构建主动应用程序的工具包。随着工作量的增加,主动应用程序都是可扩展的,当出现故障时也会恢复。主动应用程序具有响应性,因为它通过有效使用系统资源和保护自身免受错误的影响来控制系统。
Vert.x由一个庞大的生态系统支持,其中包含编写现代服务时所需的任何东西:一个复杂的网络堆栈、实时数据库驱动器、消息、事件流、摘要、矩阵、争议追踪等。
这个框架在国外流行度很高,支持mqtt,http,websocket等多种应用。
这里是一个MQTT客户端的例子。
Maven引入:
<vertx.version>4.5.9</vertx.version>
<dependency><groupId>io.vertx</groupId><artifactId>vertx-mqtt</artifactId><version>${vertx.version}</version> </dependency>
package com.example.demo.vertx;import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.mqtt.MqttClient;
import io.vertx.mqtt.MqttClientOptions;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class MqttClientVerticle extends AbstractVerticle {public static void main(String[] args) {Vertx vertx = Vertx.vertx();vertx.deployVerticle(MqttClientVerticle.class.getName());}@Overridepublic void start() throws Exception {MqttClientOptions options = new MqttClientOptions().setUsername("admin").setPassword("admin").setAutoKeepAlive(true);MqttClient mqttClient = MqttClient.create(vertx, options);mqttClient.connect(1883, "127.0.0.1", ar -> {if (ar.succeeded()) {System.out.println("Connected to the MQTT broker");// 订阅主题mqttClient.subscribe("/cmd/A99", 0, subAck -> {if (subAck.succeeded()) {System.out.println("Subscribed to topic");} else {System.err.println("Failed to subscribe to topic");}}).publishHandler(s -> {System.out.println("There are new message in topic: " + s.topicName());System.out.println("Content(as string) of the message: " + s.payload().toString());System.out.println("QoS: " + s.qosLevel());});// 发布消息mqttClient.publish("/dev/response", Buffer.buffer("Hello, MQTT!"), MqttQoS.AT_LEAST_ONCE, false, false, pubAck -> {if (pubAck.succeeded()) {System.out.println("Message published");} else {System.err.println("Failed to publish message");}});} else {System.err.println("Failed to connect to the MQTT broker");}});}}