
以下是一个基于Java+MySQL的物联网平台基础实现方案,涵盖设备注册与心跳检测功能的核心模块:
数据库设计
创建MySQL表结构存储设备信息与心跳记录:
-- 设备信息表
CREATE TABLE `iot_device` (
`device_id` varchar(64) PRIMARY KEY,
`device_name` varchar(128),
`secret_key` varchar(256) COMMENT '设备密钥',
`product_key` varchar(64) COMMENT '产品标识',
`status` tinyint DEFAULT 1 COMMENT '1-在线 0-离线',
`last_active_time` datetime COMMENT '最后活跃时间',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP
);
-- 心跳记录表
CREATE TABLE `iot_heartbeat` (
`id` bigint AUTO_INCREMENT PRIMARY KEY,
`device_id` varchar(64),
`timestamp` bigint COMMENT '心跳时间戳',
`ip_address` varchar(64),
`extra_info` text COMMENT '附加信息',
FOREIGN KEY (`device_id`) REFERENCES `iot_device` (`device_id`)
);
设备注册实现
设备注册核心逻辑处理类:
public class DeviceRegistryService {
private static final int DEVICE_ID_LENGTH = 16;
public Device registerDevice(DeviceRegisterDTO dto) {
Device device = new Device();
device.setDeviceId(generateDeviceId());
device.setDeviceName(dto.getDeviceName());
device.setProductKey(dto.getProductKey());
device.setSecretKey(generateSecretKey());
// JDBC插入操作示例
String sql = "INSERT INTO iot_device (device_id, device_name, secret_key, product_key) VALUES (?,?,?,?)";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, device.getDeviceId());
stmt.setString(2, device.getDeviceName());
stmt.setString(3, device.getSecretKey());
stmt.setString(4, device.getProductKey());
stmt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("设备注册失败", e);
}
return device;
}
private String generateDeviceId() {
return UUID.randomUUID().toString().replace("-","").substring(0,DEVICE_ID_LENGTH);
}
private String generateSecretKey() {
return DigestUtils.sha256Hex(UUID.randomUUID().toString());
}
}
心跳检测实现
心跳处理服务类包含状态更新逻辑:
public class HeartbeatService {
// 超时阈值(单位:秒)
private static final long HEARTBEAT_TIMEOUT = 300;
public void processHeartbeat(HeartbeatDTO heartbeat) {
// 验证设备合法性
validateDevice(heartbeat.getDeviceId(), heartbeat.getSignature());
// 记录心跳
recordHeartbeat(heartbeat);
// 更新设备状态
updateDeviceStatus(heartbeat.getDeviceId());
}
private void recordHeartbeat(HeartbeatDTO heartbeat) {
String sql = "INSERT INTO iot_heartbeat (device_id, timestamp, ip_address) VALUES (?,?,?)";
// JDBC插入操作...
}
private void updateDeviceStatus(String deviceId) {
String updateSql = "UPDATE iot_device SET status=1, last_active_time=NOW() WHERE device_id=?";
// JDBC更新操作...
}
// 定时任务检查离线设备
@Scheduled(fixedRate = 60000)
public void checkDeviceTimeout() {
String sql = "UPDATE iot_device SET status=0 WHERE last_active_time < DATE_SUB(NOW(), INTERVAL ? SECOND)";
// JDBC批量更新...
}
}
RESTful API设计
Spring Boot控制器示例:
@RestController
@RequestMapping("/api/device")
public class DeviceController {
@PostMapping("/register")
public ResponseResult<Device> register(@RequestBody DeviceRegisterDTO dto) {
return ResponseResult.success(deviceRegistryService.registerDevice(dto));
}
@PostMapping("/heartbeat")
public ResponseResult<Void> heartbeat(@RequestBody HeartbeatDTO dto) {
heartbeatService.processHeartbeat(dto);
return ResponseResult.success();
}
@GetMapping("/status/{deviceId}")
public ResponseResult<DeviceStatus> getStatus(@PathVariable String deviceId) {
// 查询设备状态实现...
}
}
安全验证
设备请求签名验证方法:
public class DeviceAuthHelper {
public static boolean verifySignature(String deviceId, String secretKey, String content, String signature) {
String expectSign = DigestUtils.sha256Hex(content + secretKey);
return expectSign.equals(signature);
}
}
性能优化建议
使用连接池管理数据库连接,推荐HikariCP配置:
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
考虑使用Redis缓存高频访问的设备信息和状态,减少数据库压力。可通过Spring Cache实现:
@Cacheable(value = "device", key = "#deviceId")
public Device getDevice(String deviceId) {
// 数据库查询实现...
}
此实现方案包含基础功能模块,可根据实际需求扩展设备管理、消息通信等物联网平台常见功能。
434

被折叠的 条评论
为什么被折叠?



