JDBCUtil.java 2.6 KB
package com.xxxcom.util;

import com.xxxcom.model.vo.Msg_Vo;

import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.AsyncSQLClient;
import io.vertx.ext.asyncsql.PostgreSQLClient;
import io.vertx.ext.sql.SQLConnection;

public class JDBCUtil {

	  
	private static AsyncSQLClient client;

	// 获取连接字符串
	private Future<JsonObject> getSqlStr() {
		Vertx vertx = Vertx.vertx();
		Future<JsonObject> future = Future.future();
		ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file")
				.setConfig(new JsonObject().put("path", "config/dbconfig.json"));
		ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore);
		ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
		retriever.getConfig(ar -> {
			if (ar.failed()) {
				// Failed to retrieve the configuration
			} else {
				JsonObject config = ar.result();
				future.complete(config);
			}
		});
		return future;
	}

	public AsyncSQLClient getClient(Vertx vertx) {

		if (client == null) {
			// 获取配置文件连接信息
			client = PostgreSQLClient.createShared(vertx,
					new JsonObject().put("host", "120.76.158.63").put("port", 5432).put("database", "iot")
							.put("maxPoolSize", 10).put("username", "postgres").put("charset", "UTF-8")
							.put("password", "Nmamtf_098"));

		}
		System.out.println("client:" + client);
		return client;

	}

	/**
	 * 获取数据库连接
	 * 
	 * @param vertx
	 * @return
	 */
	public Future<SQLConnection> getConnection(Vertx vertx) {
		Future<SQLConnection> future = Future.future();
		AsyncSQLClient client = getClient(vertx);
		client.getConnection(conn -> {
			if (conn.succeeded()) {
				SQLConnection connresult = conn.result();
				System.out.println("connresult:" + connresult);
				future.complete(connresult);

			} else {
				future.fail(conn.cause());
			}
		});

		System.out.println("future:" + future);

		return future;
	}

	// 查询
	public Future<Msg_Vo> query(Vertx vertx,String sql,JsonArray params){
		Future<Msg_Vo> future = Future.future();
		getConnection(vertx).setHandler(result->{
			SQLConnection conn=result.result();
			conn.queryWithParams(sql, params, query->{
				if (query.succeeded()) {
					JsonArray arr = new JsonArray();
					query.result().getRows().forEach(arr::add);
					future.complete(new Msg_Vo(0, arr.encode()));	
				} else {
					future.fail(query.cause());
				}
			});
		});
		return future;
	}
 
}