未验证 提交 1d72ed87 编写于 作者: H huili 提交者: GitHub

Merge pull request #5062 from taosdata/hotfix/TD-2541

Hotfix/td 2541
......@@ -9,6 +9,14 @@
<version>SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.18</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
......@@ -48,12 +56,4 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.15</version>
</dependency>
</dependencies>
</project>
......@@ -11,12 +11,12 @@ Download the tdengine package on our website: ``https://www.taosdata.com/cn/all-
## Run jdbcDemo using mvn plugin
run command:
```
mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JdbcDemo"
mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JDBCDemo"
```
and run with your customed args
```
mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JdbcDemo" -Dexec.args="-host [HOSTNAME]"
mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JDBCDemo" -Dexec.args="-host [HOSTNAME]"
```
## Compile the Demo Code and Run It
......
......@@ -5,7 +5,6 @@ import java.util.Properties;
public class JDBCDemo {
private static String host;
private static String driverType = "jni";
private static final String dbName = "test";
private static final String tbName = "weather";
private Connection connection;
......@@ -14,17 +13,10 @@ public class JDBCDemo {
for (int i = 0; i < args.length; i++) {
if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1)
host = args[++i];
if ("-driverType".equalsIgnoreCase(args[i]) && i < args.length - 1) {
driverType = args[++i];
if (!"jni".equalsIgnoreCase(driverType) && !"restful".equalsIgnoreCase(driverType))
printHelp();
}
}
if (host == null) {
printHelp();
}
JDBCDemo demo = new JDBCDemo();
demo.init();
demo.createDatabase();
......@@ -38,15 +30,10 @@ public class JDBCDemo {
}
private void init() {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
// get connection
try {
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
if (driverType.equals("restful")) {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
} else {
Class.forName("com.taosdata.jdbc.TSDBDriver");
}
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty("charset", "UTF-8");
properties.setProperty("locale", "en_US.UTF-8");
......@@ -70,11 +57,39 @@ public class JDBCDemo {
exuete(sql);
}
private void dropTable() {
final String sql = "drop table if exists " + dbName + "." + tbName + "";
exuete(sql);
}
private void createTable() {
final String sql = "create table if not exists " + dbName + "." + tbName + " (ts timestamp, temperature float, humidity int)";
exuete(sql);
}
private void insert() {
final String sql = "insert into test.weather (ts, temperature, humidity) values(now, 20.5, 34)";
exuete(sql);
}
private void select() {
final String sql = "select * from test.weather";
executeQuery(sql);
}
private void close() {
try {
if (connection != null) {
this.connection.close();
System.out.println("connection closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/************************************************************************/
private void executeQuery(String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
......@@ -99,15 +114,6 @@ public class JDBCDemo {
}
}
private void insert() {
final String sql = "insert into test.weather (ts, temperature, humidity) values(now, 20.5, 34)";
exuete(sql);
}
private void createTable() {
final String sql = "create table if not exists " + dbName + "." + tbName + " (ts timestamp, temperature float, humidity int)";
exuete(sql);
}
private void printSql(String sql, boolean succeed, long cost) {
System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql);
......@@ -125,24 +131,8 @@ public class JDBCDemo {
}
}
private void close() {
try {
if (connection != null) {
this.connection.close();
System.out.println("connection closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void dropTable() {
final String sql = "drop table if exists " + dbName + "." + tbName + "";
exuete(sql);
}
private static void printHelp() {
System.out.println("Usage: java -jar JdbcDemo.jar -host <hostname> -driverType <jni|restful>");
System.out.println("Usage: java -jar JDBCDemo.jar -host <hostname>");
System.exit(0);
}
......
......@@ -14,9 +14,9 @@ public class JdbcRestfulDemo {
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
Properties properties = new Properties();
// properties.setProperty("charset", "UTF-8");
// properties.setProperty("locale", "en_US.UTF-8");
// properties.setProperty("timezone", "UTC-8");
properties.setProperty("charset", "UTF-8");
properties.setProperty("locale", "en_US.UTF-8");
properties.setProperty("timezone", "UTC-8");
Connection conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement();
......
......@@ -6,75 +6,70 @@ import com.taosdata.jdbc.TSDBResultSet;
import com.taosdata.jdbc.TSDBSubscribe;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class SubscribeDemo {
private static final String usage = "java -jar SubscribeDemo.jar -host <hostname> -database <database name> -topic <topic> -sql <sql>";
public static TSDBConnection getConnection(String host, String database) throws Exception {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
String cs = String.format("jdbc:TAOS://%s:0/%s", host, database);
return (TSDBConnection) DriverManager.getConnection(cs, properties);
}
public static void main(String[] args) throws Exception {
String usage = "java -Djava.ext.dirs=../ TestTSDBSubscribe [-host host] <-db database> <-topic topic> <-sql sql>";
if (args.length < 2) {
System.err.println(usage);
return;
}
String host = "localhost", database = "", topic = "", sql = "";
public static void main(String[] args) {
// parse args from command line
String host = "", database = "", topic = "", sql = "";
for (int i = 0; i < args.length; i++) {
if ("-db".equalsIgnoreCase(args[i]) && i < args.length - 1) {
if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) {
host = args[++i];
}
if ("-database".equalsIgnoreCase(args[i]) && i < args.length - 1) {
database = args[++i];
}
if ("-topic".equalsIgnoreCase(args[i]) && i < args.length - 1) {
topic = args[++i];
}
if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) {
host = args[++i];
}
if ("-sql".equalsIgnoreCase(args[i]) && i < args.length - 1) {
sql = args[++i];
}
}
if (database.isEmpty() || topic.isEmpty() || sql.isEmpty()) {
System.err.println(usage);
if (host.isEmpty() || database.isEmpty() || topic.isEmpty() || sql.isEmpty()) {
System.out.println(usage);
return;
}
TSDBConnection connection = null;
TSDBSubscribe sub = null;
/*********************************************************************************************/
try {
connection = getConnection(host, database);
sub = ((TSDBConnection) connection).subscribe(topic, sql, false);
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
final String url = "jdbc:TAOS://" + host + ":6030/" + database + "?user=root&password=taosdata";
// get TSDBConnection
TSDBConnection connection = (TSDBConnection) DriverManager.getConnection(url, properties);
// create TSDBSubscribe
TSDBSubscribe sub = connection.subscribe(topic, sql, false);
int total = 0;
while (true) {
TSDBResultSet rs = sub.consume();
int count = 0;
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t");
}
System.out.println();
count++;
}
total += count;
System.out.printf("%d rows consumed, total %d\n", count, total);
Thread.sleep(900);
// System.out.printf("%d rows consumed, total %d\n", count, total);
if (total >= 10)
break;
TimeUnit.SECONDS.sleep(1);
}
sub.close(false);
connection.close();
} catch (Exception e) {
System.out.println("host: " + host + ", database: " + database + ", topic: " + topic + ", sql: " + sql);
e.printStackTrace();
} finally {
if (null != sub) {
sub.close(true);
}
if (null != connection) {
connection.close();
}
}
}
}
}
\ No newline at end of file
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.taosdata.example.calcite</groupId>
<artifactId>calciteDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
<!-- calcite -->
<dependency>
<groupId>org.apache.calcite</groupId>
<artifactId>calcite-core</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.calcite.avatica</groupId>
<artifactId>avatica-core</artifactId>
<version>1.17.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- tdengine -->
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.8</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.taosdata.example.calcite;
import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.*;
import java.util.Properties;
public class CalciteDemo {
private static String url_taos = "jdbc:TAOS://192.168.236.135:6030/test";
private static String url_mysql = "jdbc:mysql://master:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
public static void main(String[] args) throws SqlParseException, ClassNotFoundException, SQLException {
Class.forName("org.apache.calcite.jdbc.Driver");
Properties info = new Properties();
info.setProperty("caseSensitive", "false");
Connection connection = DriverManager.getConnection("jdbc:calcite:", info);
CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = calciteConnection.getRootSchema();
//这里hdb是在tdengine中创建的数据库名
Schema schema = mysqlTest(rootSchema);
// Schema schema = tdengineTest(rootSchema);
//创建新的schema自动映射到原来的hdb数据库
rootSchema.add("test", schema);
Statement stmt = calciteConnection.createStatement();
//查询schema test中的表,表名是tdengine中的表
ResultSet rs = stmt.executeQuery("select * from test.t");
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
System.out.println(metaData.getColumnLabel(i) + " : " + rs.getString(i));
}
}
}
private static Schema tdengineTest(SchemaPlus rootSchema) throws ClassNotFoundException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(url_taos);
dataSource.setUsername("root");
dataSource.setPassword("taosdata");
return JdbcSchema.create(rootSchema, "test", dataSource, "hdb", null);
}
private static Schema mysqlTest(SchemaPlus rootSchema) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(url_mysql);
dataSource.setUsername("root");
dataSource.setPassword("123456");
//Schema schema = JdbcSchema.create(rootSchema, "test", dataSource, "hdb", null);
return JdbcSchema.create(rootSchema, "test", dataSource, "test", null);
}
}
log4j.rootLogger=info,stdout
#console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH:mm:ss a}]:%p %l%m%n
\ No newline at end of file
这个example中,我们适配了java常见的连接池:
* c3p0
* dbcp
* HikariCP(默认)
* druid
* HikariCP
* dbcp
* c3p0
### 说明
ConnectionPoolDemo的程序逻辑:
1. 创建到host的connection连接池
2. 创建名称为pool_test的database,创建表超级weather,创建tableSize个子表
3. 不断向所有子表进行插入
3. 总共插入totalNumber条数据
### 如何运行这个例子:
```shell script
# mvn exec:java -Dexec.mainClass="com.taosdata.demo.ConnectionPoolDemo" -Dexec.args="-host localhost"
mvn clean package assembly:single
java -jar target/connectionPools-1.0-SNAPSHOT-jar-with-dependencies.jar -host 127.0.0.1
```
使用mvn运行ConnectionPoolDemo的main方法,可以指定参数
```shell script
Usage:
mvn exec:java -Dexec.mainClass="com.taosdata.demo.ConnectionPoolDemo" -Dexec.args="<args>"
java -jar target/connectionPools-1.0-SNAPSHOT-jar-with-dependencies.jar
-host : hostname
-poolType <c3p0| dbcp| druid| hikari>
-poolSize <poolSize>
......@@ -26,8 +28,5 @@ mvn exec:java -Dexec.mainClass="com.taosdata.demo.ConnectionPoolDemo" -Dexec.arg
-sleep : 每次插入任务提交后的
```
### 如何停止程序:
ConnectionPoolDemo不会自己停止,会一直执行插入,需要手动Ctrl+C运行。
### 日志
使用log4j,将日志和错误分别输出到了debug.log和error.log中
\ No newline at end of file
......@@ -12,7 +12,7 @@
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.17</version>
<version>2.0.18</version>
</dependency>
<!-- druid -->
......@@ -50,6 +50,35 @@
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.taosdata.example.ConnectionPoolDemo</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.taosdata.demo;
package com.taosdata.example;
import com.taosdata.demo.common.InsertTask;
import com.taosdata.demo.pool.C3p0Builder;
import com.taosdata.demo.pool.DbcpBuilder;
import com.taosdata.demo.pool.DruidPoolBuilder;
import com.taosdata.demo.pool.HikariCpBuilder;
import com.taosdata.example.common.InsertTask;
import com.taosdata.example.pool.C3p0Builder;
import com.taosdata.example.pool.DbcpBuilder;
import com.taosdata.example.pool.DruidPoolBuilder;
import com.taosdata.example.pool.HikariCpBuilder;
import org.apache.log4j.Logger;
import javax.sql.DataSource;
......@@ -20,44 +20,43 @@ public class ConnectionPoolDemo {
private static Logger logger = Logger.getLogger(DruidPoolBuilder.class);
private static final String dbName = "pool_test";
private static int batchSize = 10;
private static int sleep = 1000;
private static int poolSize = 50;
private static int tableSize = 1000;
private static int threadCount = 50;
private static String poolType = "hikari";
private static long totalSize = 1_000_000l;
private static long tableSize = 1;
private static long batchSize = 1;
private static int poolSize = 50;
private static int threadCount = 50;
private static int sleep = 0;
public static void main(String[] args) throws InterruptedException {
public static void main(String[] args) {
String host = null;
for (int i = 0; i < args.length; i++) {
if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) {
host = args[++i];
}
if ("-batchSize".equalsIgnoreCase(args[i]) && i < args.length - 1) {
batchSize = Integer.parseInt(args[++i]);
}
if ("-sleep".equalsIgnoreCase(args[i]) && i < args.length - 1) {
sleep = Integer.parseInt(args[++i]);
if ("-poolType".equalsIgnoreCase(args[i]) && i < args.length - 1) {
poolType = args[++i];
}
if ("-poolSize".equalsIgnoreCase(args[i]) && i < args.length - 1) {
poolSize = Integer.parseInt(args[++i]);
if ("-recordNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) {
totalSize = Long.parseLong(args[++i]);
}
if ("-tableSize".equalsIgnoreCase(args[i]) && i < args.length - 1) {
tableSize = Integer.parseInt(args[++i]);
if ("-tableNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) {
tableSize = Long.parseLong(args[++i]);
}
if ("-poolType".equalsIgnoreCase(args[i]) && i < args.length - 1) {
poolType = args[++i];
if ("-batchNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) {
batchSize = Long.parseLong(args[++i]);
}
}
if (host == null) {
System.out.println("Usage: java -jar XXX.jar " +
"-host <hostname> " +
"-batchSize <batchSize> " +
"-sleep <sleep> " +
"-poolSize <poolSize> " +
"-tableSize <tableSize>" +
"-poolType <c3p0| dbcp| druid| hikari>");
System.out.println("Usage: java -jar XXX.jar -host <hostname> " +
"-poolType <c3p0| dbcp| druid| hikari>" +
"-recordNumber <number> " +
"-tableNumber <number> " +
"-batchNumber <number> " +
"-sleep <number> "
);
return;
}
......@@ -79,30 +78,35 @@ public class ConnectionPoolDemo {
}
logger.info(">>>>>>>>>>>>>> connection pool Type: " + poolType);
init(dataSource);
try {
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
String sql = "insert into " + dbName + ".t_1 values('2020-01-01 00:00:00.000',12.12,111)";
int affectRows = statement.executeUpdate(sql);
System.out.println("affectRows >>> " + affectRows);
affectRows = statement.executeUpdate(sql);
System.out.println("affectRows >>> " + affectRows);
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
// try {
// Connection connection = dataSource.getConnection();
// Statement statement = connection.createStatement();
// String sql = "insert into " + dbName + ".t_1 values('2020-01-01 00:00:00.000',12.12,111)";
// int affectRows = statement.executeUpdate(sql);
// System.out.println("affectRows >>> " + affectRows);
// affectRows = statement.executeUpdate(sql);
// System.out.println("affectRows >>> " + affectRows);
// statement.close();
// connection.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (long i = 0; i < totalSize / tableSize / batchSize; i++) {
executor.execute(new InsertTask(dataSource, dbName, tableSize, batchSize));
// sleep few seconds
try {
if (sleep > 0)
TimeUnit.MILLISECONDS.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
// ExecutorService executor = Executors.newFixedThreadPool(threadCount);
// while (true) {
// executor.execute(new InsertTask(dataSource, dbName, tableSize, batchSize));
// if (sleep > 0)
// TimeUnit.MILLISECONDS.sleep(sleep);
// }
}
private static void init(DataSource dataSource) {
......
package com.taosdata.demo.common;
package com.taosdata.example.common;
import org.apache.log4j.Logger;
......@@ -13,11 +13,11 @@ public class InsertTask implements Runnable {
private static final Logger logger = Logger.getLogger(InsertTask.class);
private final DataSource ds;
private final int batchSize;
private final String dbName;
private final int tableSize;
private final long tableSize;
private final long batchSize;
public InsertTask(DataSource ds, String dbName, int tableSize, int batchSize) {
public InsertTask(DataSource ds, String dbName, long tableSize, long batchSize) {
this.ds = ds;
this.dbName = dbName;
this.tableSize = tableSize;
......@@ -26,52 +26,21 @@ public class InsertTask implements Runnable {
@Override
public void run() {
Connection conn = null;
Statement stmt = null;
int affectedRows = 0;
long start = System.currentTimeMillis();
try {
conn = ds.getConnection();
stmt = conn.createStatement();
try (Connection conn = ds.getConnection(); Statement stmt = conn.createStatement()) {
for (int tb_index = 1; tb_index <= tableSize; tb_index++) {
StringBuilder sb = new StringBuilder();
sb.append("insert into ");
sb.append(dbName);
sb.append(".t_");
sb.append(tb_index);
sb.append("(ts, temperature, humidity) values ");
sb.append("insert into ").append(dbName).append(".t_").append(tb_index).append("(ts, temperature, humidity) values ");
for (int i = 0; i < batchSize; i++) {
sb.append("(");
sb.append(start + i);
sb.append(", ");
sb.append(random.nextFloat() * 30);
sb.append(", ");
sb.append(random.nextInt(70));
sb.append(") ");
sb.append("(").append(start + i).append(", ").append(random.nextFloat() * 30).append(", ").append(random.nextInt(70)).append(") ");
}
logger.info("SQL >>> " + sb.toString());
affectedRows += stmt.executeUpdate(sb.toString());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
logger.info(">>> affectedRows:" + affectedRows + " TimeCost:" + (System.currentTimeMillis() - start) + " ms");
}
logger.info(">>> affectedRows:" + affectedRows + " TimeCost:" + (System.currentTimeMillis() - start) + " ms");
}
}
package com.taosdata.demo.pool;
package com.taosdata.example.pool;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
......
package com.taosdata.demo.pool;
package com.taosdata.example.pool;
import com.alibaba.druid.pool.DruidDataSource;
......@@ -11,19 +11,17 @@ public class DruidPoolBuilder {
DruidDataSource dataSource = new DruidDataSource();
// jdbc properties
dataSource.setUrl(url);
dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
dataSource.setUrl(url);
dataSource.setUsername("root");
dataSource.setPassword("taosdata");
// pool configurations
dataSource.setInitialSize(poolSize);//初始连接数,默认0
dataSource.setMinIdle(poolSize);//最小闲置数
dataSource.setMaxActive(poolSize);//最大连接数,默认8
dataSource.setMaxWait(30000);//获取连接的最大等待时间,单位毫秒
dataSource.setInitialSize(poolSize);
dataSource.setMinIdle(poolSize);
dataSource.setMaxActive(poolSize);
dataSource.setMaxWait(30000);
dataSource.setValidationQuery("select server_status()");
return dataSource;
}
}
package com.taosdata.demo.pool;
package com.taosdata.example.pool;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
......@@ -15,9 +15,10 @@ public class HikariCpBuilder {
config.setUsername("root");
config.setPassword("taosdata");
// pool configurations
config.setMinimumIdle(3); //minimum number of idle connection
config.setMaximumPoolSize(10); //maximum number of connection in the pool
config.setMinimumIdle(poolSize); //minimum number of idle connection
config.setMaximumPoolSize(poolSize); //maximum number of connection in the pool
config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool
config.setMaxLifetime(0); // maximum life time for each connection
config.setIdleTimeout(0); // max idle time for recycle idle connection
config.setConnectionTestQuery("select server_status()"); //validation query
......
......@@ -47,15 +47,9 @@
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.14</version>
<version>2.0.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
......
spring:
datasource:
driver-class-name: com.taosdata.jdbc.TSDBDriver
url: jdbc:TAOS://localhost:6030/mp_test
url: jdbc:TAOS://localhost:6030/mp_test?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8
user: root
password: taosdata
charset: UTF-8
locale: en_US.UTF-8
timezone: UTC-8
druid:
initial-size: 5
min-idle: 5
max-active: 5
mybatis-plus:
configuration:
map-underscore-to-camel-case: false
......
......@@ -8,7 +8,7 @@
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.taosdata.jdbc</groupId>
<groupId>com.taosdata.example</groupId>
<artifactId>springbootdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootdemo</name>
......@@ -63,7 +63,7 @@
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.4</version>
<version>2.0.18</version>
</dependency>
<dependency>
......@@ -71,8 +71,6 @@
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
</dependencies>
<build>
......
......@@ -47,7 +47,7 @@ logging.level.com.taosdata.jdbc.springbootdemo.dao=debug
* 插入单条记录
```xml
<!-- weatherMapper.xml -->
<insert id="insert" parameterType="com.taosdata.jdbc.springbootdemo.domain.Weather" >
<insert id="insert" parameterType="Weather" >
insert into test.weather (ts, temperature, humidity) values (now, #{temperature,jdbcType=INTEGER}, #{humidity,jdbcType=FLOAT})
</insert>
```
......@@ -67,9 +67,9 @@ logging.level.com.taosdata.jdbc.springbootdemo.dao=debug
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taosdata.jdbc.springbootdemo.dao.WeatherMapper">
<mapper namespace="WeatherMapper">
<resultMap id="BaseResultMap" type="com.taosdata.jdbc.springbootdemo.domain.Weather">
<resultMap id="BaseResultMap" type="Weather">
<id column="ts" jdbcType="TIMESTAMP" property="ts" />
<result column="temperature" jdbcType="INTEGER" property="temperature" />
<result column="humidity" jdbcType="FLOAT" property="humidity" />
......
package com.taosdata.jdbc.springbootdemo;
package com.taosdata.example.springbootdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.taosdata.jdbc.springbootdemo.dao"})
@MapperScan(basePackages = {"com.taosdata.example.springbootdemo.dao"})
@SpringBootApplication
public class cd {
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
package com.taosdata.jdbc.springbootdemo.controller;
package com.taosdata.example.springbootdemo.controller;
import com.taosdata.jdbc.springbootdemo.domain.Weather;
import com.taosdata.jdbc.springbootdemo.service.WeatherService;
import com.taosdata.example.springbootdemo.domain.Weather;
import com.taosdata.example.springbootdemo.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -45,7 +45,6 @@ public class WeatherController {
*/
@PostMapping("/{temperature}/{humidity}")
public int saveWeather(@PathVariable int temperature, @PathVariable float humidity) {
return weatherService.save(temperature, humidity);
}
......@@ -57,7 +56,6 @@ public class WeatherController {
*/
@PostMapping("/batch")
public int batchSaveWeather(@RequestBody List<Weather> weatherList) {
return weatherService.save(weatherList);
}
......
package com.taosdata.jdbc.springbootdemo.dao;
package com.taosdata.example.springbootdemo.dao;
import com.taosdata.jdbc.springbootdemo.domain.Weather;
import com.taosdata.example.springbootdemo.domain.Weather;
import org.apache.ibatis.annotations.Param;
import java.util.List;
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taosdata.jdbc.springbootdemo.dao.WeatherMapper">
<mapper namespace="com.taosdata.example.springbootdemo.dao.WeatherMapper">
<resultMap id="BaseResultMap" type="com.taosdata.jdbc.springbootdemo.domain.Weather">
<resultMap id="BaseResultMap" type="com.taosdata.example.springbootdemo.domain.Weather">
<id column="ts" jdbcType="TIMESTAMP" property="ts" />
<result column="temperature" jdbcType="INTEGER" property="temperature" />
<result column="humidity" jdbcType="FLOAT" property="humidity" />
......@@ -34,7 +34,7 @@
</if>
</select>
<insert id="insert" parameterType="com.taosdata.jdbc.springbootdemo.domain.Weather" >
<insert id="insert" parameterType="com.taosdata.example.springbootdemo.domain.Weather" >
insert into test.weather (ts, temperature, humidity) values (now, #{temperature,jdbcType=INTEGER}, #{humidity,jdbcType=FLOAT})
</insert>
......
package com.taosdata.jdbc.springbootdemo.domain;
package com.taosdata.example.springbootdemo.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
......
package com.taosdata.jdbc.springbootdemo.service;
package com.taosdata.example.springbootdemo.service;
import com.taosdata.jdbc.springbootdemo.dao.WeatherMapper;
import com.taosdata.jdbc.springbootdemo.domain.Weather;
import com.taosdata.example.springbootdemo.dao.WeatherMapper;
import com.taosdata.example.springbootdemo.domain.Weather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......
package com.taosdata.jdbc.springbootdemo.controller;
import com.taosdata.jdbc.springbootdemo.domain.Rainfall;
import com.taosdata.jdbc.springbootdemo.service.RainStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/rainstation")
public class RainStationController {
@Autowired
private RainStationService service;
@GetMapping("/init")
public boolean init() {
service.init();
service.createTable();
return true;
}
@PostMapping("/insert")
public int insert(@RequestBody Rainfall rainfall){
return service.insert(rainfall);
}
}
package com.taosdata.jdbc.springbootdemo.dao;
import java.util.Map;
public interface DatabaseMapper {
int createDatabase(String dbname);
int dropDatabase(String dbname);
int creatDatabaseWithParameters(Map<String,String> map);
int useDatabase(String dbname);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taosdata.jdbc.springbootdemo.dao.DatabaseMapper">
<update id="createDatabase" parameterType="java.lang.String">
create database if not exists ${dbname}
</update>
<update id="dropDatabase" parameterType="java.lang.String">
DROP database if exists ${dbname}
</update>
<update id="creatDatabaseWithParameters" parameterType="map">
CREATE database if not EXISTS ${dbname}
<if test="keep != null">
KEEP ${keep}
</if>
<if test="days != null">
DAYS ${days}
</if>
<if test="replica != null">
REPLICA ${replica}
</if>
<if test="cache != null">
cache ${cache}
</if>
<if test="blocks != null">
blocks ${blocks}
</if>
<if test="minrows != null">
minrows ${minrows}
</if>
<if test="maxrows != null">
maxrows ${maxrows}
</if>
</update>
<update id="useDatabase" parameterType="java.lang.String">
use ${dbname}
</update>
</mapper>
\ No newline at end of file
package com.taosdata.jdbc.springbootdemo.dao;
import java.util.Map;
public interface RainfallMapper {
int save(Map<String, Object> map);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taosdata.jdbc.springbootdemo.dao.RainfallMapper">
<insert id="save" parameterType="map">
INSERT INTO ${table} using ${dbname}.${stable} tags(#{values.station_code}, #{values.station_name}) (ts, name, code, rainfall) values (#{values.ts}, #{values.name}, #{values.code}, #{values.rainfall})
</insert>
</mapper>
\ No newline at end of file
package com.taosdata.jdbc.springbootdemo.dao;
import com.taosdata.jdbc.springbootdemo.domain.TableMetadata;
public interface TableMapper {
boolean createSTable(TableMetadata tableMetadata);
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taosdata.jdbc.springbootdemo.dao.TableMapper">
<update id="createSTable" parameterType="com.taosdata.jdbc.springbootdemo.domain.TableMetadata">
create table if not exists ${dbname}.${tablename}
<foreach collection="fields" item="field" index="index" open="(" close=")" separator=",">
${field.name} ${field.type}
</foreach>
TAGS
<foreach collection="tags" item="tag" index="index" open="(" close=")" separator=",">
${tag.name} ${tag.type}
</foreach>
</update>
<update id="dropTable" parameterType="java.lang.String">
drop ${tablename}
</update>
</mapper>
\ No newline at end of file
package com.taosdata.jdbc.springbootdemo.domain;
public class FieldMetadata {
private String name;
private String type;
public FieldMetadata(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package com.taosdata.jdbc.springbootdemo.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.sql.Timestamp;
public class Rainfall {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS",timezone = "GMT+8")
private Timestamp ts;
private String name;
private String code;
private float rainfall;
private String station_code;
private String station_name;
public Timestamp getTs() {
return ts;
}
public void setTs(Timestamp ts) {
this.ts = ts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public float getRainfall() {
return rainfall;
}
public void setRainfall(float rainfall) {
this.rainfall = rainfall;
}
public String getStation_code() {
return station_code;
}
public void setStation_code(String station_code) {
this.station_code = station_code;
}
public String getStation_name() {
return station_name;
}
public void setStation_name(String station_name) {
this.station_name = station_name;
}
}
package com.taosdata.jdbc.springbootdemo.domain;
import java.util.List;
public class TableMetadata {
private String dbname;
private String tablename;
private List<FieldMetadata> fields;
private List<TagMetadata> tags;
public String getDbname() {
return dbname;
}
public void setDbname(String dbname) {
this.dbname = dbname;
}
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public List<FieldMetadata> getFields() {
return fields;
}
public void setFields(List<FieldMetadata> fields) {
this.fields = fields;
}
public List<TagMetadata> getTags() {
return tags;
}
public void setTags(List<TagMetadata> tags) {
this.tags = tags;
}
}
package com.taosdata.jdbc.springbootdemo.domain;
public class TagMetadata {
private String name;
private String type;
public TagMetadata(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package com.taosdata.jdbc.springbootdemo.service;
import com.taosdata.jdbc.springbootdemo.dao.DatabaseMapper;
import com.taosdata.jdbc.springbootdemo.dao.RainfallMapper;
import com.taosdata.jdbc.springbootdemo.dao.TableMapper;
import com.taosdata.jdbc.springbootdemo.domain.FieldMetadata;
import com.taosdata.jdbc.springbootdemo.domain.Rainfall;
import com.taosdata.jdbc.springbootdemo.domain.TableMetadata;
import com.taosdata.jdbc.springbootdemo.domain.TagMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class RainStationService {
@Autowired
private DatabaseMapper databaseMapper;
@Autowired
private TableMapper tableMapper;
@Autowired
private RainfallMapper rainfallMapper;
public boolean init() {
databaseMapper.dropDatabase("rainstation");
Map<String, String> map = new HashMap<>();
map.put("dbname", "rainstation");
map.put("keep", "36500");
map.put("days", "30");
map.put("blocks", "4");
databaseMapper.creatDatabaseWithParameters(map);
databaseMapper.useDatabase("rainstation");
return true;
}
public boolean createTable() {
TableMetadata tableMetadata = new TableMetadata();
tableMetadata.setDbname("rainstation");
tableMetadata.setTablename("monitoring");
List<FieldMetadata> fields = new ArrayList<>();
fields.add(new FieldMetadata("ts", "timestamp"));
fields.add(new FieldMetadata("name", "NCHAR(10)"));
fields.add(new FieldMetadata("code", " BINARY(8)"));
fields.add(new FieldMetadata("rainfall", "float"));
tableMetadata.setFields(fields);
List<TagMetadata> tags = new ArrayList<>();
tags.add(new TagMetadata("station_code", "BINARY(8)"));
tags.add(new TagMetadata("station_name", "NCHAR(10)"));
tableMetadata.setTags(tags);
tableMapper.createSTable(tableMetadata);
return true;
}
public int insert(Rainfall rainfall) {
Map<String, Object> map = new HashMap<>();
map.put("dbname", "rainstation");
map.put("table", "S_53646");
map.put("stable", "monitoring");
map.put("values", rainfall);
return rainfallMapper.save(map);
}
}
\ No newline at end of file
# datasource config
# datasource config - JDBC-JNI
spring.datasource.driver-class-name=com.taosdata.jdbc.TSDBDriver
spring.datasource.url=jdbc:TAOS://localhost:6030/log
spring.datasource.url=jdbc:TAOS://127.0.0.1:6030/test?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8
spring.datasource.username=root
spring.datasource.password=taosdata
# datasource config - JDBC-RESTful
#spring.datasource.driver-class-name=com.taosdata.jdbc.rs.RestfulDriver
#spring.datasource.url=jdbc:TAOS-RS://master:6041/test?user=root&password=taosdata
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=5
# max wait time for get connection, ms
spring.datasource.druid.max-wait=60000
spring.datasource.druid.max-wait=30000
spring.datasource.druid.validation-query=select server_status();
spring.datasource.druid.validation-query-timeout=5000
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=600000
spring.datasource.druid.max-evictable-idle-time-millis=900000
#mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
......
package com.taosdata.jdbc.springbootdemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootdemoApplicationTests {
@Test
void contextLoads() {
}
}
......@@ -67,7 +67,7 @@
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.17</version>
<version>2.0.18</version>
<!-- <scope>system</scope>-->
<!-- <systemPath>${project.basedir}/src/main/resources/lib/taos-jdbcdriver-2.0.15-dist.jar</systemPath>-->
</dependency>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册