审计记录

src/main/java/com/xxxcom/util/JDBCUtil.java 2.6 KB
胡敏 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
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;
	}
 
}