SpringBoot與IoTDB整合,實現可穿戴設備健康數據斷點續傳功能
作者:Java知識日歷
可穿戴設備能夠實時采集用戶的健康數據(如心率、體溫、步數等),并通過無線網絡傳輸到云端進行存儲和分析。然而,在現實生活中,網絡不穩定或設備故障可能導致數據丟失,影響健康數據分析的準確性。
可穿戴設備能夠實時采集用戶的健康數據(如心率、體溫、步數等),并通過無線網絡傳輸到云端進行存儲和分析。然而,在現實生活中,網絡不穩定或設備故障可能導致數據丟失,影響健康數據分析的準確性。例如:針對心率監測手環在地鐵隧道等弱網環境下的數據積壓問題,我們就利用了IoTDB的Write Ahead Log機制實現斷點續傳。
推薦IoTDB 的理由
- 高效的數據壓縮: IoTDB內置了多種高效的壓縮算法,可以顯著減少存儲空間占用。
- 分布式架構: IoTDB支持集群部署,可以水平擴展以應對大規模數據和高并發請求。
- 高可用性和容錯性: 提供主從復制機制,確保數據在節點故障時仍然可用,并且可以通過WAL(Write-Ahead Logging)機制實現斷點續傳,保證數據一致性。
- 開源免費: 作為Apache軟件基金會的頂級項目,IoTDB是開源且免費的,降低了項目的初期投入成本。
- 快速的數據查詢: 支持復雜的時序查詢操作,如聚合、降采樣等,滿足數據分析的需求。
代碼實操
<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機制
確保在IoTDB的配置文件(conf/iotdb-engine.properties
)中啟用了WAL機制。
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服務器主機地址
@Value("${iotdb.port}")
private int port; // IoTDB服務器端口號
@Value("${iotdb.username}")
private String username; // 連接IoTDB的用戶名
@Value("${iotdb.password}")
private String password; // 連接IoTDB的密碼
@Bean
public Session getSession() throws IoTDBConnectionException {
// 創建一個Session對象來連接IoTDB
Session session = new Session(host, port, username, password);
session.open(false); // 禁用自動獲取模式
return session;
}
}
服務類
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;
/**
* 將健康數據插入到IoTDB中
*
* @param deviceId 設備ID
* @param measurements 測量值及其對應的數據類型
* @param values 測量值的實際數據
* @throws StatementExecutionException SQL語句執行異常
* @throws IOException IO異常
*/
public void insertHealthData(String deviceId, Map<String, TsDataType> measurements, Map<String, Object> values)
throws StatementExecutionException, IOException {
long time = System.currentTimeMillis(); // 獲取當前時間戳作為記錄的時間戳
List<String> measurementList = new ArrayList<>(measurements.keySet()); // 提取測量值名稱列表
List<TsDataType> typeList = new ArrayList<>(measurements.values()); // 提取測量值類型列表
Object[] valueList = values.values().toArray(); // 提取測量值數組
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;
/**
* 接收來自可穿戴設備的健康數據
*
* @param deviceId 設備ID
* @param healthData 健康數據Map,鍵為測量值名稱,值為測量值
* @return HTTP響應實體
*/
@PostMapping("/data")
public ResponseEntity<?> receiveHealthData(@RequestParam String deviceId,
@RequestBody Map<String, Object> healthData) {
Map<String, TsDataType> measurements = new HashMap<>(); // 存儲測量值及其對應的數據類型
// 根據傳入的健康數據確定其數據類型
for (String key : healthData.keySet()) {
if (key.equals("heartRate")) {
measurements.put(key, TsDataType.INT32); // 心率是整數類型
} elseif (key.equals("temperature")) {
measurements.put(key, TsDataType.FLOAT); // 體溫是浮點類型
} elseif (key.equals("steps")) {
measurements.put(key, TsDataType.INT32); // 步數是整數類型
}
}
try {
// 調用服務方法插入健康數據
healthDataService.insertHealthData(deviceId, measurements, healthData);
return ResponseEntity.ok("Data inserted successfully"); // 返回成功響應
} catch (Exception e) {
// 捕獲并返回錯誤響應
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"
}
責任編輯:武曉燕
來源:
Java知識日歷