开发掌上洪城App,后台用到Vert.x,以前没用过,看官方文档(http://vertx.io/docs/)从零开始学习,博客记录学习所得,期望有更多交流:
代码运行后,浏览器输入:http://localhost:8080/hello 查看效果
相关包可在方法文档下载,CSDN上也有上传,含:
1、vertx-core-3.2.1.jar
2、vertx-web-3.2.1.jar
<span style="font-size:18px;">package io.vertx.example.mytest;
import java.io.IOException;
import java.util.function.Consumer;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
/**
* 类说明
* @author hscai
* @time 2016年6月12日下午4:24:40
*/
// verticle是vert.x中的组件,一个组件可有多个实例,创建verticle都要继承AbstractVerticle
public class VertxTest extends AbstractVerticle {
public static void main(String[] args) throws IOException {
String verticleID = VertxTest.class.getName();
runExample(verticleID);
}
@Override
public void start() throws Exception {
final Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
// router.get("/hello")表示所监听URL路径
router.get("/hello").handler(new Handler<RoutingContext>() {
public void handle(RoutingContext event) {
event.response().putHeader("content-type", "text/html").end("Hello World");
}
});
// 传递方法引用,监听端口
vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest event) {
router.accept(event);
}
}).listen(8080);// 监听端口号
}
public static void runExample(String verticleID) {
VertxOptions options = new VertxOptions();
Consumer<Vertx> runner = vertx -> {
vertx.deployVerticle(verticleID);
};
// Vert.x实例是vert.x api的入口点,我们调用vert.x中的核心服务时,均要先获取vert.x实例,
// 通过该实例来调用相应的服务,例如部署verticle、创建http server
Vertx vertx = Vertx.vertx(options);
runner.accept(vertx);
}
}</span>