Springboot整合TDengine3.0

目录(这里写自定义目录标题)

springboot:整合TDengine

TDengine 介绍

涛思数据旗下产品开源、云原生的时序数据库(Time Series Database),已在2018年8月推出正式商业化版本。TDengine不依赖任何开源或第三方软件,拥有完全自主知识产权,具有高性能、高可靠、可伸缩、零管理、简单易学等技术特点。 提供缓存、数据订阅、流式计算等功能,最大程度减少研发和运维的复杂度。

基本介绍

类SQL查询语言来插入或查询数据
支持C/C++, Java(JDBC), Python, Go, RESTful, and Node.JS 等开发接口
通过TDengine Shell或Python/R/Matlab可做各种Ad Hoc查询分析
通过连续查询,支持基于滑动窗口的流式计算
引入超级表,让设备之间的数据聚合通过标签变得简单、灵活
内嵌消息队列,应用可订阅最新的数据
内嵌缓存机制,每台设备的最新状态或记录都可快速获得
无历史数据与实时数据之分

与整合springboot

依赖

org.springframework.boot spring-boot-starter-data-jdbc org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </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>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.17</version>
    </dependency>
</dependencies>

application.properties

spring.datasource.driver-class-name=com.taosdata.jdbc.rs.RestfulDriver
spring.datasource.url=jdbc:TAOS-RS://127.0.0.1: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

实体

package com.taosdata.example.springbootdemo.domain;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.sql.Timestamp;

public class Weather {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
    private Timestamp ts;
    private Float temperature;
    private Float humidity;
    private String location;
    private String note;
    private int groupId;

    public Weather() {
    }

    public Weather(Timestamp ts, float temperature, float humidity) {
        this.ts = ts;
        this.temperature = temperature;
        this.humidity = humidity;
    }

    public Timestamp getTs() {
        return ts;
    }

    public void setTs(Timestamp ts) {
        this.ts = ts;
    }

    public Float getTemperature() {
        return temperature;
    }

    public void setTemperature(Float temperature) {
        this.temperature = temperature;
    }

    public Float getHumidity() {
        return humidity;
    }

    public void setHumidity(Float humidity) {
        this.humidity = humidity;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}

dao层`

package com.taosdata.example.springbootdemo.dao;

import com.taosdata.example.springbootdemo.domain.Weather;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface WeatherMapper {

Map<String, Object> lastOne();

void dropDB();

void createDB();

void createSuperTable();

void createTable(Weather weather);

List<Weather> select(@Param("limit") Long limit, @Param("offset") Long offset);

int insert(Weather weather);

int count();

List<String> getSubTables();

List<Weather> avg();

}

service

package com.taosdata.example.springbootdemo.service;

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;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class WeatherService {

    @Autowired
    private WeatherMapper weatherMapper;
    private Random random = new Random(System.currentTimeMillis());
    private String[] locations = {"北京", "上海", "广州", "深圳", "天津"};

    public int init() {
        weatherMapper.dropDB();
        weatherMapper.createDB();
        weatherMapper.createSuperTable();
        long ts = System.currentTimeMillis();
        long thirtySec = 1000 * 30;
        int count = 0;
        for (int i = 0; i < 20; i++) {
            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);
        }
        return count;
    }

    public List<Weather> query(Long limit, Long offset) {
        return weatherMapper.select(limit, offset);
    }

    public int save(float temperature, float humidity) {
        Weather weather = new Weather();
        weather.setTemperature(temperature);
        weather.setHumidity(humidity);

        return weatherMapper.insert(weather);
    }

    public int count() {
        return weatherMapper.count();
    }

    public List<String> getSubTables() {
        return weatherMapper.getSubTables();
    }

    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;
    }
}

具体可以参考官方demo
官方example

<think>好的,我现在需要帮助用户找到如何在Spring Boot中连接TDengine数据库的配置示例教程。用户已经提供了一些相关的引用内容,我需要仔细分析这些引用来提取有用的信息。 首先,引用[3]提到了TDengine 3.0.7.1的多数据源使用,并强调了@Transactional注解必须在Spring托管的Bean方法上使用,否则事务代理不会生效。这说明用户可能需要在配置数据源时确保Spring能够正确管理事务,这点需要注意。 接下来,引用[4]展示了一个WeatherService.java的代码片段,其中使用了weatherMapper来创建表和插入数据。这里提到了createTable和insert方法,说明用户可能需要配置MyBatis或者类似的ORM框架来操作TDengine。同时,代码中的配置可能涉及到数据源的连接参数,如URL、用户名、密码等。 然后,引用[1]和[2]分别提到了手动连接库和SpringJdbcTemplate的示例代码。虽然这两个引用可能不是直接针对TDengine的,但可以借鉴其配置数据源和使用JdbcTemplate的方法。例如,引用[2]中的SpringJdbcTemplate示例可能帮助用户配置TDengine的数据源。 现在需要整合这些信息,构建一个Spring Boot连接TDengine的配置教程。步骤可能包括添加依赖、配置数据源、使用JdbcTemplate或MyBatis进行操作,以及处理事务管理。需要确保引用的内容正确应用到配置中,比如引用[3]中提到的事务注解的使用条件,需要在配置数据源时考虑事务管理器的配置。 另外,TDengine的JDBC驱动可能和传统数据库不同,需要确认正确的驱动类名和连接URL格式。例如,TDengine的URL可能以jdbc:TAOS://开头,驱动类为com.taosdata.jdbc.TSDBDriver。这些信息需要用户正确配置在application.properties中。 还需要注意多数据源的配置,如果用户有多个数据源,可能需要使用@Primary注解指定主数据源,并分别配置不同的DataSource和JdbcTemplate或SqlSessionFactory。但根据用户的问题,可能只需要单数据源的配置,所以可以简化步骤。 最后,测试连接是否成功,可以通过编写一个简单的Service类,执行一个查询语句,比如SELECT * FROM information_schema.ins_databases,来验证连接是否正常。同时,引用[4]中的save方法示例可以作为插入数据的参考,结合TDengine的SQL语法进行调整。 总结下来,配置步骤应包括依赖添加、配置文件设置、数据源和JdbcTemplate/MyBatis的Bean配置,以及事务管理的注意事项。需要确保所有步骤都参考了用户提供的引用内容,并正确应用其中的知识点。</think>以下是Spring Boot连接TDengine数据库的配置教程,整合了站内引用内容和技术实践: ### 一、基础配置步骤 1. **添加JDBC驱动依赖** ```xml <!-- pom.xml 添加TDengine官方驱动 --> <dependency> <groupId>com.taosdata.jdbc</groupId> <artifactId>taos-jdbcdriver</artifactId> <version>3.2.4</version> </dependency> ``` 2. **配置数据源参数** ```properties # application.properties spring.datasource.driver-class-name=com.taosdata.jdbc.TSDBDriver spring.datasource.url=jdbc:TAOS://127.0.0.1:6030/dbname?charset=UTF-8&locale=en_US.UTF-8 spring.datasource.username=root spring.datasource.password=taosdata ``` ### 二、事务管理配置 根据引用[3]的说明,需在配置类中显式声明事务管理器: ```java @Configuration public class DataSourceConfig { @Bean @Primary public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } ``` ### 三、数据库操作方式 #### 方式1:使用JdbcTemplate(引用[2]示例扩展) ```java @Repository public class TaosDao { @Autowired private JdbcTemplate jdbcTemplate; public void createDatabase() { jdbcTemplate.execute("CREATE DATABASE IF NOT EXISTS weather"); } } ``` #### 方式2:集成MyBatis(引用[4]示例优化) ```yaml # application.yml mybatis: mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true ``` Mapper接口示例: ```java public interface WeatherMapper { @Update("CREATE TABLE IF NOT EXISTS weather (ts TIMESTAMP, temperature FLOAT)") void createTable(); @Insert("INSERT INTO weather VALUES(#{ts}, #{temperature})") int insert(Weather weather); } ``` ### 四、多数据源配置(引用[3]实践) ```java @Configuration public class MultipleDataSourceConfig { // 主数据源 @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } // TDengine数据源 @Bean(name = "tdengineDataSource") @ConfigurationProperties(prefix = "spring.datasource.tdengine") public DataSource tdengineDataSource() { return DataSourceBuilder.create().build(); } } ``` ### 五、连接验证测试 ```java @Service public class ConnectionTestService { @Autowired private JdbcTemplate jdbcTemplate; public List<String> showDatabases() { return jdbcTemplate.queryForList("SHOW DATABASES", String.class); } } ``` **注意事项**(来自引用[3]): 1. 涉及事务操作时,必须通过Spring代理对象调用方法 2. 避免在同一个类的非public方法上使用@Transactional 3. TDengine 3.x版本建议使用REST连接方式提升稳定性
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值