vert.x学习
Posted 超超学堂
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vert.x学习相关的知识,希望对你有一定的参考价值。
{
"host" : <主机地址>,
"port" : <端口>,
"maxPoolSize" : <最大连接数>,
"username" : <用户名>,
"password" : <密码>,
"database" : <数据库名称>,
"charset" : <编码>,
"queryTimeout" : <查询超时时间-毫秒>
}
private Future<Void> startHttpServer(){
Future<Void> future = Future.future();
System.out.println(">>>> http server start <<<<");
HttpServer httpServer = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route("/index").handler(routingContext -> indexHandler(routingContext));
router.get("/user/findAll").handler(this::queryAll);
router.get("/user/findById/:id").handler(this::selectByIdHandler);
httpServer.requestHandler(router::accept).listen(8080);
return future;
}
方法中:/user/findById/:id 使用的是restful风格的请求,和springmvc中/user/findById/{id}是一样的,
而具体id的获取是从用户的request中拿到的参数值,而request需要RoutingContext来获取,这里的request应该是vert.x包装过的HttpServerRequest,并不是HttpServerletRequest。
我们对应的selectByIdHandler代码如下:
private void selectByIdHandler(RoutingContext context) {
String id = context.request().getParam("id");
getClient().getConnection(car -> {
if (car.succeeded()){
SQLConnection sqlConnection = car.result();
sqlConnection.queryWithParams("select * from user where id = ?",new JsonArray().add(id),res -> {
sqlConnection.close();
if (res.succeeded()){
List<JsonObject> jsonObjects = res.result().getRows();
context.put("list",jsonObjects);
templateEngine.render(context,"templates","/user/user.ftl",ar -> {
if (ar.succeeded()){
context.response().putHeader("content-type","text/html");
context.response().end(ar.result());
} else {
LOGGER.error(ar.cause().getMessage());
context.fail(ar.cause());
}
});
} else {
LOGGER.error(res.cause());
context.fail(car.cause());
}
});
} else {
context.fail(car.cause());
}
});
}
HttpServerVerticle:
public class HttpServerVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerVerticle.class);
private final FreeMarkerTemplateEngine templateEngine = FreeMarkerTemplateEngine.create();
private final Integer serverPort = 9090;
@Override
public void start(Future<Void> startFuture) throws Exception {
HttpServer httpServer = vertx.createHttpServer();
Router router = Router.router(vertx);
router.get("/user/:id").handler(this::selectByIdHandler);
httpServer.requestHandler(router::accept).listen(serverPort,ar -> {
if (ar.succeeded()){
LOGGER.info(">>>> http server start at: " + serverPort + " <<<<");
startFuture.complete();
} else {
LOGGER.error(">>>> http server start failed <<<<",ar.cause());
startFuture.fail(ar.cause());
}
});
}
private void selectByIdHandler(RoutingContext context) {
LOGGER.info(">>>> select by id handler <<<<");
String id = context.request().getParam("id");
JsonObject request = new JsonObject().put("id",id);
DeliveryOptions options = new DeliveryOptions().addHeader("action","one-user");
vertx.eventBus().send("database.verticle",request,options,reply -> {
if (reply.succeeded()){
JsonObject jsonObject = (JsonObject) reply.result().body();
context.put("id",id);
LOGGER.info(">>>> handler success <<<<");
templateEngine.render(context,"templates","/user/user.ftl",ar -> {
if (ar.succeeded()){
context.response().putHeader("content_type","text/html");
context.response().end(ar.result());
} else {
context.fail(ar.cause());
}
});
} else {
LOGGER.error(">>>> handler failed <<<<");
context.fail(reply.cause());
}
});
}
}
DataBaseVerticle代码:
public class DataBaseVerticle extends AbstractVerticle {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/springboot?useSSL=false&characterEncoding=utf8";
private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
private static final String USER_NAME = "root";
private static final String PASSWORD = "123";
private static final int MAX_POOL_SIZE = 30;
private static final Logger LOGGER = LoggerFactory.getLogger(DataBaseVerticle.class);
private JDBCClient jdbcClient;
@Override
public void start(Future<Void> startFuture) throws Exception {
LOGGER.info(">>>> database verticle start <<<<");
jdbcClient = JDBCClient.createShared(vertx,new JsonObject().put("url",URL).put("driver_class",DRIVER_CLASS)
.put("user",USER_NAME).put("password",PASSWORD).put("max_pool_size",MAX_POOL_SIZE));
jdbcClient.getConnection(ar ->{
if (ar.succeeded()){
SQLConnection connection = ar.result();
connection.execute("select * from user",res -> {
if (res.succeeded()){
vertx.eventBus().consumer("database.verticle",this::queryUser);
startFuture.complete();
} else {
LOGGER.error(res.cause());
startFuture.fail(res.cause());
}
});
} else {
LOGGER.error(ar.cause());
startFuture.fail(ar.cause());
}
});
}
private void queryUser(Message<JsonObject> message) {
if (!message.headers().contains("action")){
LOGGER.error(">>>> exception <<<<");
message.fail(404,"no action");
return;
}
String action = message.headers().get("action");
switch (action){
case "one-user":
fetchOneById(message);
break;
case "all-user":
fetchAllUser(message);
break;
default:
message.fail(500,"bad action" + action);
}
}
private void fetchOneById(Message<JsonObject> message) {
String id = message.body().getString("id");
JsonArray params = new JsonArray().add(id);
jdbcClient.querySingleWithParams("select * from user where id = ?",params,fetch -> {
if (fetch.succeeded()){
} else {
}
});
}
private void fetchAllUser(Message<JsonObject> message) {
}
}
之所以代码没有写完就是因为写不下去了,现在问题就卡在event bus这里,http server启动是没用问题的,但是浏览器访问的时候会出现问题,显示下面错误信息:
也可能是我没有注册相应的handler的原因,但是这个又该怎么注册呢??头大,所以一直卡在这个地方,网上找了一些资料,但是也都是讲解event bus的,可能我还需要再去理解一下vert.x。
今天的学习也只能到这里,event bus是vert.x里面非常重要非常重要的内容,自己还需要再去好好理解一下。如果event bus这个问题可以解决,对自己的提高应该有很大帮助,还有一个就是自己可能一直在用现有的思维去学习vert.x,不知道会不会也算个误区!!
以上是关于vert.x学习的主要内容,如果未能解决你的问题,请参考以下文章