vertx 学习 jdbc 数据库连接

依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>vertx-parent</artifactId>
        <groupId>com.zlb.vert.x</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zlb.vert.x</groupId>
    <artifactId>vertx-jdbc-demo</artifactId>
    
    <properties>
        <vertx.version>3.4.2</vertx.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-jdbc-client</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
        </dependency>
    </dependencies>
</project>

vertical 编写

package com.zlb.vertx.verticle;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

import java.util.List;

public class MyVerticle extends AbstractVerticle {

    @Override
    public void init(Vertx vertx, Context context) {
        super.init(vertx, context);
        initJDBCDateSource();
    }

    private JDBCClient jdbcClient;

    /**
     * 初始化数据源
     */
    private void initJDBCDateSource() {
        System.out.println("连接测试:::--------");
        jdbcClient = JDBCClient.createShared(vertx, config());
        jdbcClient.getConnection(conn -> {
            if (conn.failed()) {
                System.out.println("数据库初始化连接是失败");
                System.err.println(conn.cause().getMessage());
                return;
            }
            // 获取连接
            final SQLConnection connection = conn.result();
            //执行 [创建一张test表]
            connection.execute("create table IF NOT  EXISTS test(id int primary key, name varchar(255))", res -> {
                //如果建表失败
                if (res.failed()) {
                    //抛出异常[可自定义]
                    throw new RuntimeException(res.cause());
                }
                // 插入一条数据
                connection.execute("insert into test values(1, 'Hello')", insert -> {
                    // 查询数据
                    connection.query("select * from test", rs -> {
                        //打印结果
                        System.out.println("数据库初始化成功");
                        for (JsonArray line : rs.result().getResults()) {
                            System.out.println(line.encode());
                        }
                        // 最后关闭连接
                        connection.close(done -> {
                            //如果连接释放失败
                            if (done.failed()) {
                                //抛出异常
                                throw new RuntimeException(done.cause());
                            }
                        });
                    });
                });
            });
        });
    }

    @Override
    public JsonObject config() {
        super.config();
        return new JsonObject()
                .put("url", "jdbc:mysql://localhost:3306/vertx-test")
                .put("driver_class", "com.mysql.jdbc.Driver")
                .put("user", "root")
                .put("password", "root")
                .put("max_pool_size", 10);
    }

    private static final String API_GET = "/test/:id";
    private static final String HTTP_HOST = "127.0.0.1";
    private static final int HTTP_PORT = 8080;

    @Override
    public void start(Future<Void> startFuture) throws Exception {
        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());
        router.get(API_GET).handler(this::handleGet);
        //创建一个服务
        vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(HTTP_PORT, HTTP_HOST, result -> {
                    if (result.succeeded())
                        startFuture.complete();
                    else
                        startFuture.fail(result.cause());
                });
    }

    private void handleGet(RoutingContext routingContext) {
        String id = routingContext.request().getParam("id");
        final HttpServerResponse response = getHttpServerResponse(routingContext);
        final SQLClient connection = jdbcClient.getConnection(res -> {
            if (res.failed()) {
                response.setStatusCode(400);
                response.end("服务器忙,请联系管理员!!!!");
                throw new RuntimeException(res.cause().getMessage());
            }
            final SQLConnection sqlConnection = res.result();
            sqlConnection.query("select * from test where id = " + id, result -> {
                if (result.failed()) {
                    throw new RuntimeException("查询失败" + id);
                }
                final List<JsonObject> rows = result.result().getRows();
                response.setStatusCode(200);
                response.end(rows.toString());
            });
        });
    }

    public HttpServerResponse getHttpServerResponse(RoutingContext rtx) {
        HttpServerResponse response = rtx.response();
        response.setChunked(true);
        response.putHeader("content-type", "application/json;charset=UTF-8");
        return response;
    }
}

入口编写:

package com.zlb.vertx;

import com.zlb.vertx.verticle.MyVerticle;
import io.vertx.core.Vertx;

public class AppServer {
    public static void main(String[] args) {
        final Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(MyVerticle.class.getName());
    }
}

运行main 方法 [数据库初始化成功]:

postman 测试:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值