SpringBoot與IoTDB整合,實現(xiàn)可穿戴設(shè)備健康數(shù)據(jù)斷點續(xù)傳功能
可穿戴設(shè)備能夠?qū)崟r采集用戶的健康數(shù)據(jù)(如心率、體溫、步數(shù)等),并通過無線網(wǎng)絡(luò)傳輸?shù)皆贫诉M(jìn)行存儲和分析。然而,在現(xiàn)實生活中,網(wǎng)絡(luò)不穩(wěn)定或設(shè)備故障可能導(dǎo)致數(shù)據(jù)丟失,影響健康數(shù)據(jù)分析的準(zhǔn)確性。例如:針對心率監(jiān)測手環(huán)在地鐵隧道等弱網(wǎng)環(huán)境下的數(shù)據(jù)積壓問題,我們就利用了IoTDB的Write Ahead Log機(jī)制實現(xiàn)斷點續(xù)傳。
推薦IoTDB 的理由
- 高效的數(shù)據(jù)壓縮: IoTDB內(nèi)置了多種高效的壓縮算法,可以顯著減少存儲空間占用。
- 分布式架構(gòu): IoTDB支持集群部署,可以水平擴(kuò)展以應(yīng)對大規(guī)模數(shù)據(jù)和高并發(fā)請求。
- 高可用性和容錯性: 提供主從復(fù)制機(jī)制,確保數(shù)據(jù)在節(jié)點故障時仍然可用,并且可以通過WAL(Write-Ahead Logging)機(jī)制實現(xiàn)斷點續(xù)傳,保證數(shù)據(jù)一致性。
- 開源免費: 作為Apache軟件基金會的頂級項目,IoTDB是開源且免費的,降低了項目的初期投入成本。
- 快速的數(shù)據(jù)查詢: 支持復(fù)雜的時序查詢操作,如聚合、降采樣等,滿足數(shù)據(jù)分析的需求。
代碼實操
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache IoTDB Client -->
<dependency>
<groupId>org.apache.iotdb</groupId>
<artifactId>iotdb-session</artifactId>
<version>1.0.0</version>
</dependency>application.properties
iotdb.host=localhost
iotdb.port=6667
iotdb.username=root
iotdb.password=root啟用了WAL機(jī)制
確保在IoTDB的配置文件(conf/iotdb-engine.properties)中啟用了WAL機(jī)制。
enable_wal=true
wal_dir=data/wal配置類
package com.example.iotdbspringbootdemo;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.session.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class IotdbConfig {
@Value("${iotdb.host}")
private String host; // IoTDB服務(wù)器主機(jī)地址
@Value("${iotdb.port}")
private int port; // IoTDB服務(wù)器端口號
@Value("${iotdb.username}")
private String username; // 連接IoTDB的用戶名
@Value("${iotdb.password}")
private String password; // 連接IoTDB的密碼
@Bean
public Session getSession() throws IoTDBConnectionException {
// 創(chuàng)建一個Session對象來連接IoTDB
Session session = new Session(host, port, username, password);
session.open(false); // 禁用自動獲取模式
return session;
}
}服務(wù)類
package com.example.iotdbspringbootdemo;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.tsfile.file.metadata.enums.TsDataType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
class HealthDataService {
@Autowired
private Session session;
/**
* 將健康數(shù)據(jù)插入到IoTDB中
*
* @param deviceId 設(shè)備ID
* @param measurements 測量值及其對應(yīng)的數(shù)據(jù)類型
* @param values 測量值的實際數(shù)據(jù)
* @throws StatementExecutionException SQL語句執(zhí)行異常
* @throws IOException IO異常
*/
public void insertHealthData(String deviceId, Map<String, TsDataType> measurements, Map<String, Object> values)
throws StatementExecutionException, IOException {
long time = System.currentTimeMillis(); // 獲取當(dāng)前時間戳作為記錄的時間戳
List<String> measurementList = new ArrayList<>(measurements.keySet()); // 提取測量值名稱列表
List<TsDataType> typeList = new ArrayList<>(measurements.values()); // 提取測量值類型列表
Object[] valueList = values.values().toArray(); // 提取測量值數(shù)組
try {
// 插入一條記錄到IoTDB
session.insertRecord(deviceId, time, measurementList, typeList, valueList);
} catch (StatementExecutionException | IOException e) {
// 捕獲并拋出異常
throw new RuntimeException("Failed to insert health data", e);
}
}
}Controller
package com.example.iotdbspringbootdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/health")
class HealthController {
@Autowired
private HealthDataService healthDataService;
/**
* 接收來自可穿戴設(shè)備的健康數(shù)據(jù)
*
* @param deviceId 設(shè)備ID
* @param healthData 健康數(shù)據(jù)Map,鍵為測量值名稱,值為測量值
* @return HTTP響應(yīng)實體
*/
@PostMapping("/data")
public ResponseEntity<?> receiveHealthData(@RequestParam String deviceId,
@RequestBody Map<String, Object> healthData) {
Map<String, TsDataType> measurements = new HashMap<>(); // 存儲測量值及其對應(yīng)的數(shù)據(jù)類型
// 根據(jù)傳入的健康數(shù)據(jù)確定其數(shù)據(jù)類型
for (String key : healthData.keySet()) {
if (key.equals("heartRate")) {
measurements.put(key, TsDataType.INT32); // 心率是整數(shù)類型
} elseif (key.equals("temperature")) {
measurements.put(key, TsDataType.FLOAT); // 體溫是浮點類型
} elseif (key.equals("steps")) {
measurements.put(key, TsDataType.INT32); // 步數(shù)是整數(shù)類型
}
}
try {
// 調(diào)用服務(wù)方法插入健康數(shù)據(jù)
healthDataService.insertHealthData(deviceId, measurements, healthData);
return ResponseEntity.ok("Data inserted successfully"); // 返回成功響應(yīng)
} catch (Exception e) {
// 捕獲并返回錯誤響應(yīng)
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}Application
package com.example.iotdbspringbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class IotdbSpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(IotdbSpringbootDemoApplication.class, args);
}
}測試
curl -X POST http://localhost:8080/health/data?deviceId=device_1 \
-H "Content-Type: application/json" \
-d '{"heartRate": 75, "temperature": 36.8, "steps": 1200}'Respons
{
"timestamp": "2025-06-16T09:45:30.123+00:00",
"status": 200,
"error": null,
"message": "Data inserted successfully",
"path": "/health/data"
}



















