1,基于Netty的异步框架,采用事件机制,这点同android消息机制类似,在此学习简单的使用
2,例子
package com.zjw.demo.vertx.starter;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
/**
* 简单使用,
* 参考<a href="https://vertx.io/docs">...</a>
*/
public class VertxApp {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
HttpServer httpServer = vertx.createHttpServer();
/*创建应用路由*/
Router router = Router.router(vertx);
/*两种get方法方式*/
//1
router.route(HttpMethod.GET, "/test1").handler(ctx -> ctx.end("this is async handler"));
//2
router.get("/path/get1").respond(ctx -> Future.succeededFuture(new JsonObject().put("/path/get1", "hello vert.x")));
router.get("/path/get2").blockingHandler(ctx -> {
ctx.response().setChunked(true).write("this is block handler,wait 2 second");
//取消阻塞,
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
ctx.next();
}).handler(ctx -> ctx.response().end("\nnow,2 second after"));
/*path参数*/
router.get("/path/get3/:p1/:p2").handler(ctx -> {
String p1 = ctx.pathParam("p1");
String p2 = ctx.pathParam("p2");
ctx.end(p1 + "+" + p2 + "=" + (Integer.parseInt(p1) + Integer.parseInt(p2)));
});
router.route("/path/s1").method(HttpMethod.POST).method(HttpMethod.PUT).handler(ctx -> {
//这个路由可以对应post或者put请求
});
router.route("/pata/data/01").method(HttpMethod.GET).handler(ctx -> {
new MysqlConnect().init(vertx);
ctx.end("查询数据库");
});
/*设置路由,监听8888端口*/
httpServer.requestHandler(router).listen(8888, http -> {
if (http.succeeded()) {
/*监听成功*/
System.out.println("HTTP server started on port 8888");
} else {
/*监听失败*/
System.err.println("HTTP server error");
}
});
}
}
数据库相关,
package com.zjw.demo.vertx.starter;
import io.vertx.core.Vertx;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.*;
public class MysqlConnect {
public void init(Vertx vertx) {
MySQLConnectOptions connectOptions = new MySQLConnectOptions()
.setPort(3306)
.setHost("127.0.0.1")
.setDatabase("dataBaseName")
.setUser("user")
.setPassword("password");
PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
SqlClient client = MySQLPool.client(connectOptions, poolOptions);
/*
* 简单查询
* */
client.query("SELECT * FROM users WHERE 0=0 AND id = '12'")
.execute(ar -> {
if (ar.succeeded()) {
RowSet<Row> result = ar.result();
System.out.println(result);
} else {
System.err.println("Failed:" + ar.cause().getMessage());
}
});
/*
* 简单插入
* */
client
.preparedQuery("INSERT INTO users (first_name, last_name) VALUES (?, ?)")
.execute(Tuple.of("Julien", "Viet"), ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
System.out.println(rows.rowCount());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
//关闭
client.close();
}
}
3,源码分析
...