简介
Vert.x项目起始于2011年,最开始的名字叫做 node.x,是一个仿照Node.js以Java开发的,基于EventLoop的异步非阻塞编程框架。Eclipse Vert.x是一个事件驱动的JVM上的框架,可以帮助我们构建现代、灵活、可扩展的程序。
使用Vert.x
1、新建maven项目,导入依赖
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
2、编写主函数
package com.qianyu;
import io.vertx.core.*;
import io.vertx.core.http.*;
public class Server {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
HttpServer httpServer = vertx.createHttpServer();
httpServer.requestHandler(request -> request.response().end("hello, world"));
httpServer.listen(8000);
}
}
此时一个端口为8000的http服务器已经开启
3、在IDEA中编写脚本测试
可以看到,返回字符串hello, world
GET http://localhost:8000
HTTP/1.1 200 OK
Content-Length: 12
hello, world
Response code: 200 (OK); Time: 277ms; Content length: 12 bytes
使用路由
1、导入web
模块
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>3.2.0</version>
</dependency>
2、使用路由
package com.qianyu;
import io.vertx.core.*;
import io.vertx.core.http.*;
import io.vertx.ext.web.*;
public class Server {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.get("/demo").blockingHandler(context -> {
context.response().end("hello, world");
});
router.post("/demo").blockingHandler(context -> {
context.response().end("this is post method");
});
HttpServer httpServer = vertx.createHttpServer();
httpServer.requestHandler(router::accept);
httpServer.listen(8000);
}
}
3、使用IDEA编写脚本测试
GET http://localhost:8000/demo
HTTP/1.1 200 OK
Content-Length: 12
hello, world
Response code: 200 (OK); Time: 19ms; Content length: 12 bytes
POST http://localhost:8000/demo
HTTP/1.1 200 OK
Content-Length: 19
this is post method
Response code: 200 (OK); Time: 122ms; Content length: 19 bytes