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