未验证 提交 efb97ef8 编写于 作者: Z Zhiyu Yang 提交者: GitHub

Enhance/ts-339 refactor code in springbootdemo and JDBCDemo (#7866)

* fix confilct

* refactor code in springbootdemo
上级 2394bf08
......@@ -17,7 +17,7 @@
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.31</version>
<version>2.0.34</version>
</dependency>
</dependencies>
......
......@@ -7,6 +7,9 @@ public class JdbcDemo {
private static String host;
private static final String dbName = "test";
private static final String tbName = "weather";
private static final String user = "root";
private static final String password = "taosdata";
private Connection connection;
public static void main(String[] args) {
......@@ -30,10 +33,9 @@ public class JdbcDemo {
}
private void init() {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
final String url = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password;
// get connection
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty("charset", "UTF-8");
properties.setProperty("locale", "en_US.UTF-8");
......@@ -42,8 +44,7 @@ public class JdbcDemo {
connection = DriverManager.getConnection(url, properties);
if (connection != null)
System.out.println("[ OK ] Connection established.");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("[ ERROR! ] Connection establish failed.");
} catch (SQLException e) {
e.printStackTrace();
}
}
......@@ -74,7 +75,7 @@ public class JdbcDemo {
}
private void select() {
final String sql = "select * from "+ dbName + "." + tbName;
final String sql = "select * from " + dbName + "." + tbName;
executeQuery(sql);
}
......@@ -89,8 +90,6 @@ public class JdbcDemo {
}
}
/************************************************************************/
private void executeQuery(String sql) {
long start = System.currentTimeMillis();
try (Statement statement = connection.createStatement()) {
......@@ -117,7 +116,6 @@ public class JdbcDemo {
}
}
private void printSql(String sql, boolean succeed, long cost) {
System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql);
}
......@@ -132,7 +130,6 @@ public class JdbcDemo {
long end = System.currentTimeMillis();
printSql(sql, false, (end - start));
e.printStackTrace();
}
}
......@@ -141,5 +138,4 @@ public class JdbcDemo {
System.exit(0);
}
}
\ No newline at end of file
}
......@@ -4,14 +4,15 @@ import java.sql.*;
import java.util.Properties;
public class JdbcRestfulDemo {
private static final String host = "127.0.0.1";
private static final String host = "localhost";
private static final String dbname = "test";
private static final String user = "root";
private static final String password = "taosdata";
public static void main(String[] args) {
try {
// load JDBC-restful driver
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
// use port 6041 in url when use JDBC-restful
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=" + password;
Properties properties = new Properties();
properties.setProperty("charset", "UTF-8");
......@@ -21,12 +22,12 @@ public class JdbcRestfulDemo {
Connection conn = DriverManager.getConnection(url, properties);
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists restful_test");
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
stmt.execute("create table restful_test.weather(ts timestamp, temperature float) tags(location nchar(64))");
stmt.executeUpdate("insert into t1 using restful_test.weather tags('北京') values(now, 18.2)");
ResultSet rs = stmt.executeQuery("select * from restful_test.weather");
stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists " + dbname);
stmt.execute("use " + dbname);
stmt.execute("create table " + dbname + ".weather(ts timestamp, temperature float) tags(location nchar(64))");
stmt.executeUpdate("insert into t1 using " + dbname + ".weather tags('北京') values(now, 18.2)");
ResultSet rs = stmt.executeQuery("select * from " + dbname + ".weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
......@@ -38,8 +39,6 @@ public class JdbcRestfulDemo {
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
......
......@@ -34,9 +34,8 @@ public class SubscribeDemo {
System.out.println(usage);
return;
}
/*********************************************************************************************/
try {
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");
......
......@@ -60,12 +60,15 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.28</version>
<!-- <scope>system</scope>-->
<!-- <systemPath>${project.basedir}/src/main/resources/taos-jdbcdriver-2.0.28-dist.jar</systemPath>-->
<version>2.0.34</version>
</dependency>
<dependency>
......
......@@ -4,7 +4,7 @@ import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.taosdata.example.springbootdemo.dao"})
@MapperScan(basePackages = {"com.taosdata.example.springbootdemo"})
@SpringBootApplication
public class SpringbootdemoApplication {
......
......@@ -15,35 +15,21 @@ public class WeatherController {
@Autowired
private WeatherService weatherService;
/**
* create database and table
*
* @return
*/
@GetMapping("/lastOne")
public Weather lastOne() {
return weatherService.lastOne();
}
@GetMapping("/init")
public int init() {
return weatherService.init();
}
/**
* Pagination Query
*
* @param limit
* @param offset
* @return
*/
@GetMapping("/{limit}/{offset}")
public List<Weather> queryWeather(@PathVariable Long limit, @PathVariable Long offset) {
return weatherService.query(limit, offset);
}
/**
* upload single weather info
*
* @param temperature
* @param humidity
* @return
*/
@PostMapping("/{temperature}/{humidity}")
public int saveWeather(@PathVariable float temperature, @PathVariable float humidity) {
return weatherService.save(temperature, humidity);
......
......@@ -8,6 +8,8 @@ import java.util.Map;
public interface WeatherMapper {
Map<String, Object> lastOne();
void dropDB();
void createDB();
......
......@@ -9,20 +9,48 @@
<result column="humidity" jdbcType="FLOAT" property="humidity"/>
</resultMap>
<select id="lastOne" resultType="java.util.Map">
select last_row(*), location, groupid
from test.weather
</select>
<update id="dropDB">
drop database if exists test
drop
database if exists test
</update>
<update id="createDB">
create database if not exists test
create
database if not exists test
</update>
<update id="createSuperTable">
create table if not exists test.weather(ts timestamp, temperature float, humidity float) tags(location nchar(64), groupId int)
create table if not exists test.weather
(
ts
timestamp,
temperature
float,
humidity
float,
note
binary
(
64
)) tags
(
location nchar
(
64
), groupId int)
</update>
<update id="createTable" parameterType="com.taosdata.example.springbootdemo.domain.Weather">
create table if not exists test.t#{groupId} using test.weather tags(#{location}, #{groupId})
create table if not exists test.t#{groupId} using test.weather tags
(
#{location},
#{groupId}
)
</update>
<select id="select" resultMap="BaseResultMap">
......@@ -36,25 +64,29 @@
</select>
<insert id="insert" parameterType="com.taosdata.example.springbootdemo.domain.Weather">
insert into test.t#{groupId} (ts, temperature, humidity) values (#{ts}, ${temperature}, ${humidity})
insert into test.t#{groupId} (ts, temperature, humidity, note)
values (#{ts}, ${temperature}, ${humidity}, #{note})
</insert>
<select id="getSubTables" resultType="String">
select tbname from test.weather
select tbname
from test.weather
</select>
<select id="count" resultType="int">
select count(*) from test.weather
select count(*)
from test.weather
</select>
<resultMap id="avgResultSet" type="com.taosdata.example.springbootdemo.domain.Weather">
<id column="ts" jdbcType="TIMESTAMP" property="ts" />
<result column="avg(temperature)" jdbcType="FLOAT" property="temperature" />
<result column="avg(humidity)" jdbcType="FLOAT" property="humidity" />
<id column="ts" jdbcType="TIMESTAMP" property="ts"/>
<result column="avg(temperature)" jdbcType="FLOAT" property="temperature"/>
<result column="avg(humidity)" jdbcType="FLOAT" property="humidity"/>
</resultMap>
<select id="avg" resultMap="avgResultSet">
select avg(temperature), avg(humidity)from test.weather interval(1m)
select avg(temperature), avg(humidity)
from test.weather interval(1m)
</select>
</mapper>
\ No newline at end of file
......@@ -11,6 +11,7 @@ public class Weather {
private Float temperature;
private Float humidity;
private String location;
private String note;
private int groupId;
public Weather() {
......@@ -61,4 +62,12 @@ public class Weather {
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
......@@ -29,6 +29,7 @@ public class WeatherService {
Weather weather = new Weather(new Timestamp(ts + (thirtySec * i)), 30 * random.nextFloat(), random.nextInt(100));
weather.setLocation(locations[random.nextInt(locations.length)]);
weather.setGroupId(i % locations.length);
weather.setNote("note-" + i);
weatherMapper.createTable(weather);
count += weatherMapper.insert(weather);
}
......@@ -58,4 +59,21 @@ public class WeatherService {
public List<Weather> avg() {
return weatherMapper.avg();
}
public Weather lastOne() {
Map<String, Object> result = weatherMapper.lastOne();
long ts = (long) result.get("ts");
float temperature = (float) result.get("temperature");
float humidity = (float) result.get("humidity");
String note = (String) result.get("note");
int groupId = (int) result.get("groupid");
String location = (String) result.get("location");
Weather weather = new Weather(new Timestamp(ts), temperature, humidity);
weather.setNote(note);
weather.setGroupId(groupId);
weather.setLocation(location);
return weather;
}
}
package com.taosdata.example.springbootdemo.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Map;
@Aspect
@Component
public class TaosAspect {
@Around("execution(java.util.Map<String,Object> com.taosdata.example.springbootdemo.dao.*.*(..))")
public Object handleType(ProceedingJoinPoint joinPoint) {
Map<String, Object> result = null;
try {
result = (Map<String, Object>) joinPoint.proceed();
for (String key : result.keySet()) {
Object obj = result.get(key);
if (obj instanceof byte[]) {
obj = new String((byte[]) obj);
result.put(key, obj);
}
if (obj instanceof Timestamp) {
obj = ((Timestamp) obj).getTime();
result.put(key, obj);
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
}
# datasource config - JDBC-JNI
#spring.datasource.driver-class-name=com.taosdata.jdbc.TSDBDriver
#spring.datasource.url=jdbc:TAOS://127.0.0.1:6030/test?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8
#spring.datasource.url=jdbc:TAOS://localhost:6030/?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?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8
spring.datasource.url=jdbc:TAOS-RS://localhsot:6041/test?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8
spring.datasource.username=root
spring.datasource.password=taosdata
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=5
spring.datasource.druid.max-wait=30000
spring.datasource.druid.validation-query=select server_status();
spring.aop.auto=true
spring.aop.proxy-target-class=true
#mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.com.taosdata.jdbc.springbootdemo.dao=debug
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册