Vert.x使用Mysql异步驱动
先来点线程理论:
传统的jdbc驱动都是同步的,因此会造成线程阻塞
根据Java的线程模型设计,用户态线程与内核态线程是1:1,用户态线程阻塞会造成内核态线程阻塞
cpu在调度线程的时候,一个cpu核心只能同时做一件事情,当线程阻塞越多,cpu的有效计算效率跟着下降,造成大量的线程上下文切换
在高并发的时候,异步的优势就十分明显了。话说现在去面试,不管百人以下的小厂或者千人以上的大厂,都会来一句百万并发、亿级流量。
注意:异步驱动并不能提高MySQL数据库的性能,只是令程序的线程不阻塞,减少线程的开销,提高程序的性能。
Talk is cheap. Show me the code.
关于vertx请参考小弟之前的文章 ,
1.pom文件增加依赖
<dependency><groupId>io.vertx</groupId><artifactId>vertx-mysql-client</artifactId><version>4.0.0</version></dependency>
2.编写DBUtil.java数据库工具类
package com.hm.util;import io.vertx.core.Vertx;import io.vertx.mysqlclient.MySQLConnectOptions;import io.vertx.mysqlclient.MySQLPool;import io.vertx.sqlclient.PoolOptions;public class DBUtil {private Vertx vertx;public DBUtil(Vertx vertx) {this.vertx=vertx;}public MySQLPool getConnection(){MySQLConnectOptions connectOptions = new MySQLConnectOptions().setPort(3306).setHost("127.0.0.1").setDatabase("stu").setUser("root").setPassword("***");// Pool optionsPoolOptions poolOptions = new PoolOptions().setMaxSize(5);// Create the pooled clienMySQLPool client = MySQLPool.pool(vertx,connectOptions, poolOptions);return client;}}
链式编程就是爽...
3.新建IndexHandler.java(类似springboot的controller)
package com.hm.handler;import com.hm.util.DBUtil;import io.vertx.core.Handler;import io.vertx.core.Vertx;import io.vertx.ext.web.RoutingContext;import io.vertx.mysqlclient.MySQLPool;import io.vertx.sqlclient.Row;import io.vertx.sqlclient.RowSet;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class IndexHandler implements Handler<RoutingContext> {private Vertx vertx;public IndexHandler(Vertx vertx) {this.vertx=vertx;}@Overridepublic void handle(RoutingContext event) {DBUtil dbUtil = new DBUtil(vertx);List<Map<String,Object>> rList=new ArrayList<>();MySQLPool client = dbUtil.getConnection();client.query("SELECT * FROM girl_friends").execute(ar -> {if (ar.succeeded()) {RowSet<Row> result = ar.result();System.out.println("Got " + result.size() + " rows ");String[] list={"id","NAME","AGE"};for (Row row : result) {Map<String,Object> map=new HashMap<>();for (String str : list) {map.put(str,row.getValue(str));}rList.add(map);}} else {System.out.println("Failure: " + ar.cause().getMessage());}// Now close the poolclient.close();event.response().end(rList.toString());});}}
4.程序入口main方法
package com.hm;import com.hm.handler.IndexHandler;import io.vertx.core.Vertx;import io.vertx.core.http.HttpServer;import io.vertx.ext.web.Router;public class App {public static void main(String[] args) {Vertx vertx = Vertx.vertx();HttpServer server = vertx.createHttpServer();Router router = Router.router(vertx);//主路由//一级路由router.route("/index").handler(new IndexHandler(vertx));server.requestHandler(router).listen(8089);}}
