物联网平台MongoDB实战|(二)核心组件设计与实现

写在前面

这是「物联网平台MongoDB实战」系列的第二篇文章。

在上一篇文章中,我们讨论了为什么选择MongoDB作为物联网平台的数据存储方案,以及整体架构设计。这一篇,我们深入到代码层面,详细介绍一下MongoDB服务模块的核心组件是如何设计和实现的。

说实话,写这部分代码的时候踩了不少坑。一开始觉得MongoDB操作挺简单的,不就是CRUD嘛。但真正做起来才发现,要把一个服务模块做得健壮、好用,还是有很多细节需要考虑的。

一、MongoDBUtils工具类设计

MongoDBUtils是整个MongoDB服务模块的核心工具类,它封装了MongoDB客户端的创建、连接管理和基础操作。这个类的设计质量直接影响到整个模块的稳定性和性能。

1.1 连接管理

MongoDB客户端的创建和销毁是比较耗费资源的操作,所以我们需要确保全局只有一个客户端实例。这里采用的是双重检查锁定(Double-Checked Locking)模式:

java 复制代码
@Component
@Slf4j
public class MongoDBUtils {
    private static MongoClient mongoClient;
    private static MongoDatabase mongoDatabase;
    private static final Object lock = new Object();
    
    @Autowired
    private MongoDBConfig mongoDBConfig;
    
    @PostConstruct
    public void init() {
        if (mongoClient == null) {
            synchronized (lock) {
                if (mongoClient == null) {
                    initMongoClient();
                }
            }
        }
    }
}

为什么用双重检查锁定?

这个问题我一开始也没想清楚,后来查了资料才明白:

  • 第一次检查:如果实例已经存在,直接返回,避免不必要的同步开销。
  • 同步块:确保多线程环境下只有一个线程能创建实例。
  • 第二次检查:防止多个线程同时通过第一次检查后,重复创建实例。

这种设计的优势:

  • 资源节约:MongoDB客户端是线程安全的,一个应用只需要一个实例。重复创建会浪费内存和连接资源。
  • 线程安全:在多线程环境下保证初始化的正确性,不会出现多个实例。
  • 延迟初始化:只有在真正需要时才创建客户端,不会影响应用启动速度。

1.2 客户端初始化

客户端初始化是整个模块最关键的部分,配置不当可能导致连接泄漏、性能下降等问题:

java 复制代码
private void initMongoClient() {
    try {
        MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder()
            // 配置连接池
            .applyToConnectionPoolSettings(builder -> 
                builder.maxSize(mongoDBConfig.getMaxConnectionsPerHost())
                       .minSize(mongoDBConfig.getMinConnectionsPerHost())
                       .maxWaitTime(30, TimeUnit.SECONDS)  // 获取连接最大等待时间
                       .maxConnectionLifeTime(60, TimeUnit.MINUTES)  // 连接最大存活时间
                       .maxConnectionIdleTime(30, TimeUnit.MINUTES))  // 空闲连接最大存活时间
            // 配置Socket超时
            .applyToSocketSettings(builder -> 
                builder.connectTimeout(mongoDBConfig.getConnectionTimeout(), TimeUnit.MILLISECONDS)
                       .readTimeout(mongoDBConfig.getSocketTimeout(), TimeUnit.MILLISECONDS))
            // 配置服务器设置
            .applyToServerSettings(builder -> 
                builder.heartbeatFrequency(10, TimeUnit.SECONDS));  // 心跳频率
        
        // 构建连接字符串
        String connectionString = buildConnectionString();
        settingsBuilder.applyConnectionString(new ConnectionString(connectionString));
        
        mongoClient = MongoClients.create(settingsBuilder.build());
        mongoDatabase = mongoClient.getDatabase(mongoDBConfig.getDatabase());
        
        log.info("MongoDB客户端初始化成功,数据库: {}", mongoDBConfig.getDatabase());
    } catch (Exception e) {
        log.error("MongoDB客户端初始化失败", e);
        throw new RuntimeException("MongoDB初始化失败", e);
    }
}

private String buildConnectionString() {
    StringBuilder sb = new StringBuilder("mongodb://");
    
    if (StringUtils.hasText(mongoDBConfig.getUsername()) 
        && StringUtils.hasText(mongoDBConfig.getPassword())) {
        sb.append(mongoDBConfig.getUsername())
          .append(":")
          .append(mongoDBConfig.getPassword())
          .append("@");
    }
    
    sb.append(mongoDBConfig.getHost())
      .append(":")
      .append(mongoDBConfig.getPort())
      .append("/")
      .append(mongoDBConfig.getDatabase());
    
    return sb.toString();
}

配置参数详解:

参数 说明 推荐值
maxSize 连接池最大连接数 根据并发量设置,一般100-500
minSize 连接池最小连接数 保持一定预热连接,一般10-20
maxWaitTime 获取连接最大等待时间 30秒左右,避免长时间阻塞
maxConnectionLifeTime 连接最大存活时间 60分钟,防止长时间使用同一连接
maxConnectionIdleTime 空闲连接最大存活时间 30分钟,及时释放空闲连接
connectTimeout 连接超时时间 10秒,根据网络情况调整
readTimeout 读取超时时间 10秒,避免慢查询阻塞
heartbeatFrequency 心跳频率 10秒,及时发现服务器故障

踩过的坑:

刚开始的时候,我没有设置maxConnectionIdleTime,结果发现运行一段时间后,有些查询会莫名失败。后来排查发现是因为连接池中的连接长时间空闲,被服务器端关闭了,但客户端不知道,还在用这个已经失效的连接。加上这个参数后,问题就解决了。

1.3 获取集合对象

所有MongoDB操作都需要先获取集合对象,我们封装了一个统一的方法:

java 复制代码
public static MongoCollection<Document> getCollection(String collectionName) {
    if (mongoDatabase == null) {
        throw new IllegalStateException("MongoDB未初始化");
    }
    if (StringUtils.isEmpty(collectionName)) {
        throw new IllegalArgumentException("集合名称不能为空");
    }
    return mongoDatabase.getCollection(collectionName);
}

这个方法看似简单,但有几个细节需要注意:

  • 空值检查:防止在MongoDB未初始化时调用导致NPE。
  • 参数校验:集合名称不能为空,否则会抛出异常。
  • 延迟获取:不需要预先获取所有集合,用到哪个取哪个。

1.4 基础CRUD操作封装

1.4.1 插入操作
java 复制代码
/**
 * 插入单个文档
 * @param collectionName 集合名称
 * @param document 文档数据
 * @return 是否插入成功
 */
public static boolean insertOne(String collectionName, Map<String, Object> document) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document doc = new Document(document);
        collection.insertOne(doc);
        log.debug("向集合{}插入文档成功,文档ID: {}", collectionName, doc.get("_id"));
        return true;
    } catch (MongoWriteException e) {
        log.error("向集合{}插入文档失败,写入错误: {}", collectionName, e.getMessage());
        return false;
    } catch (MongoException e) {
        log.error("向集合{}插入文档失败,MongoDB异常: {}", collectionName, e.getMessage());
        return false;
    } catch (Exception e) {
        log.error("向集合{}插入文档失败: {}", collectionName, e.getMessage(), e);
        return false;
    }
}

/**
 * 批量插入文档
 * @param collectionName 集合名称
 * @param documents 文档列表
 * @return 是否插入成功
 */
public static boolean insertMany(String collectionName, List<Map<String, Object>> documents) {
    if (documents == null || documents.isEmpty()) {
        log.warn("批量插入文档列表为空");
        return false;
    }
    
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        List<Document> docs = documents.stream()
            .map(Document::new)
            .collect(Collectors.toList());
        collection.insertMany(docs);
        log.debug("向集合{}批量插入{}个文档成功", collectionName, documents.size());
        return true;
    } catch (MongoBulkWriteException e) {
        // 批量写入部分失败的情况
        log.error("向集合{}批量插入文档部分失败,成功: {}, 失败: {}", 
                 collectionName, 
                 e.getWriteResult().getInsertedCount(),
                 e.getErrors().size());
        return false;
    } catch (Exception e) {
        log.error("向集合{}批量插入文档失败: {}", collectionName, e.getMessage(), e);
        return false;
    }
}

为什么返回boolean而不是抛异常?

这是一个设计选择的问题。我们选择返回boolean是因为:

  • 调用方可以方便地判断操作是否成功,不需要try-catch。
  • 失败的原因已经记录在日志里了,调用方不需要处理具体的异常类型。
  • 对于批量操作,部分失败的情况也可以通过日志排查。

当然,如果调用方需要知道具体的失败原因,也可以改成抛出自定义异常。

批量插入的注意事项:

MongoDB的批量插入有大小限制,单个批次不能超过48MB。如果数据量很大,需要分批插入:

java 复制代码
public static boolean insertManyInBatches(String collectionName, 
                                          List<Map<String, Object>> documents, 
                                          int batchSize) {
    if (documents == null || documents.isEmpty()) {
        return false;
    }
    
    int total = documents.size();
    int successCount = 0;
    
    for (int i = 0; i < total; i += batchSize) {
        int end = Math.min(i + batchSize, total);
        List<Map<String, Object>> batch = documents.subList(i, end);
        
        if (insertMany(collectionName, batch)) {
            successCount += batch.size();
        }
    }
    
    log.info("分批插入完成,总数: {}, 成功: {}", total, successCount);
    return successCount == total;
}
1.4.2 查询操作

查询操作是最常用的,我们封装了多种查询方式:

java 复制代码
/**
 * 查询所有文档
 */
public static List<Map<String, Object>> findAll(String collectionName) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        List<Map<String, Object>> results = new ArrayList<>();
        
        try (MongoCursor<Document> cursor = collection.find().iterator()) {
            while (cursor.hasNext()) {
                results.add(new HashMap<>(cursor.next()));
            }
        }
        
        log.debug("查询集合{}所有文档,共{}条", collectionName, results.size());
        return results;
    } catch (Exception e) {
        log.error("查询集合{}失败: {}", collectionName, e.getMessage(), e);
        return Collections.emptyList();
    }
}

/**
 * 条件查询
 */
public static List<Map<String, Object>> find(String collectionName, 
                                             Map<String, Object> query) {
    return find(collectionName, query, 0, 0, null);
}

/**
 * 分页排序查询
 */
public static List<Map<String, Object>> find(String collectionName, 
                                             Map<String, Object> query,
                                             int limit, int skip, 
                                             Map<String, Object> sort) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        
        // 构建查询条件
        Bson filter = query == null ? new Document() : new Document(query);
        FindIterable<Document> findIterable = collection.find(filter);
        
        // 设置排序
        if (sort != null && !sort.isEmpty()) {
            List<Bson> sortList = sort.entrySet().stream()
                .map(e -> e.getValue() instanceof Integer && (Integer)e.getValue() > 0 
                    ? Sorts.ascending(e.getKey()) 
                    : Sorts.descending(e.getKey()))
                .collect(Collectors.toList());
            findIterable = findIterable.sort(Sorts.orderBy(sortList));
        }
        
        // 设置分页
        if (skip > 0) {
            findIterable = findIterable.skip(skip);
        }
        if (limit > 0) {
            findIterable = findIterable.limit(limit);
        }
        
        // 执行查询
        List<Map<String, Object>> results = new ArrayList<>();
        try (MongoCursor<Document> cursor = findIterable.iterator()) {
            while (cursor.hasNext()) {
                results.add(new HashMap<>(cursor.next()));
            }
        }
        
        log.debug("查询集合{}成功,条件: {}, 返回{}条记录", collectionName, query, results.size());
        return results;
    } catch (Exception e) {
        log.error("查询集合{}失败: {}", collectionName, e.getMessage(), e);
        return Collections.emptyList();
    }
}

关于游标的使用:

MongoDB查询返回的是一个游标,而不是一次性把所有数据加载到内存。这样做的好处是:

  • 内存友好:对于大数据量的查询,不会一次性占用太多内存。
  • 延迟加载:只有在真正遍历时才从数据库读取数据。

但是,游标需要显式关闭,否则会导致资源泄漏。我们使用try-with-resources语法确保游标被正确关闭。

1.4.3 更新操作
java 复制代码
/**
 * 根据ID更新文档
 */
public static boolean updateById(String collectionName, String id, 
                                 Map<String, Object> update) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        
        // 构建查询条件
        Bson filter;
        if (ObjectId.isValid(id)) {
            filter = Filters.eq("_id", new ObjectId(id));
        } else {
            filter = Filters.eq("_id", id);
        }
        
        // 构建更新操作
        Document updateDoc = new Document("$set", new Document(update));
        UpdateResult result = collection.updateOne(filter, updateDoc);
        
        log.debug("更新集合{}文档,ID: {}, 匹配: {}, 修改: {}", 
                 collectionName, id, result.getMatchedCount(), result.getModifiedCount());
        return result.getMatchedCount() > 0;
    } catch (Exception e) {
        log.error("更新集合{}文档失败,ID: {}", collectionName, id, e);
        return false;
    }
}

/**
 * 批量更新
 */
public static long updateMany(String collectionName, 
                              Map<String, Object> query,
                              Map<String, Object> update) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        Bson filter = new Document(query);
        Document updateDoc = new Document("$set", new Document(update));
        
        UpdateResult result = collection.updateMany(filter, updateDoc);
        log.debug("批量更新集合{},匹配: {}, 修改: {}", 
                 collectionName, result.getMatchedCount(), result.getModifiedCount());
        return result.getModifiedCount();
    } catch (Exception e) {
        log.error("批量更新集合{}失败: {}", collectionName, e.getMessage(), e);
        return 0;
    }
}

关于$set操作符:

更新操作中使用$set操作符,表示只更新指定的字段,不影响其他字段。如果不用$set,整个文档会被替换掉,这是新手常犯的错误。

java 复制代码
// 错误做法:整个文档被替换
collection.updateOne(filter, new Document("name", "新名称"));

// 正确做法:只更新name字段
collection.updateOne(filter, new Document("$set", new Document("name", "新名称")));
1.4.4 删除操作
java 复制代码
/**
 * 根据ID删除文档
 */
public static boolean deleteById(String collectionName, String id) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        
        Bson filter;
        if (ObjectId.isValid(id)) {
            filter = Filters.eq("_id", new ObjectId(id));
        } else {
            filter = Filters.eq("_id", id);
        }
        
        DeleteResult result = collection.deleteOne(filter);
        log.debug("删除集合{}文档,ID: {}, 删除: {}", 
                 collectionName, id, result.getDeletedCount());
        return result.getDeletedCount() > 0;
    } catch (Exception e) {
        log.error("删除集合{}文档失败,ID: {}", collectionName, id, e);
        return false;
    }
}

/**
 * 条件删除
 */
public static long deleteMany(String collectionName, Map<String, Object> query) {
    try {
        MongoCollection<Document> collection = getCollection(collectionName);
        Bson filter = new Document(query);
        
        DeleteResult result = collection.deleteMany(filter);
        log.debug("批量删除集合{},条件: {}, 删除: {}", 
                 collectionName, query, result.getDeletedCount());
        return result.getDeletedCount();
    } catch (Exception e) {
        log.error("批量删除集合{}失败: {}", collectionName, e.getMessage(), e);
        return 0;
    }
}

二、服务接口设计

工具类提供了基础的数据库操作,但在实际业务中,我们还需要更多的功能,比如参数校验、日志记录、异常处理等。这些逻辑放在服务层来实现。

2.1 接口定义

服务层接口IMongoDBService定义了完整的数据访问API:

java 复制代码
public interface IMongoDBService {
    
    // ==================== 查询操作 ====================
    
    /**
     * 查询集合中的所有文档
     */
    List<Map<String, Object>> findAll(String collectionName);
    
    /**
     * 条件查询
     */
    List<Map<String, Object>> find(String collectionName, Map<String, Object> query);
    
    /**
     * 分页排序查询
     */
    List<Map<String, Object>> find(String collectionName, Map<String, Object> query, 
                                   int limit, int skip, Map<String, Object> sort);
    
    /**
     * 根据ID查询单个文档
     */
    Map<String, Object> findById(String collectionName, String id);
    
    // ==================== 插入操作 ====================
    
    /**
     * 插入单个文档
     */
    boolean insert(String collectionName, Map<String, Object> document);
    
    /**
     * 批量插入文档
     */
    boolean insertMany(String collectionName, List<Map<String, Object>> documents);
    
    // ==================== 更新操作 ====================
    
    /**
     * 根据ID更新文档
     */
    boolean updateById(String collectionName, String id, Map<String, Object> update);
    
    /**
     * 条件更新
     */
    long updateMany(String collectionName, Map<String, Object> query, 
                    Map<String, Object> update);
    
    // ==================== 删除操作 ====================
    
    /**
     * 根据ID删除文档
     */
    boolean deleteById(String collectionName, String id);
    
    /**
     * 条件删除
     */
    long deleteMany(String collectionName, Map<String, Object> query);
    
    // ==================== 统计操作 ====================
    
    /**
     * 统计文档数量
     */
    long count(String collectionName);
    
    /**
     * 条件统计
     */
    long count(String collectionName, Map<String, Object> query);
    
    // ==================== 集合管理 ====================
    
    /**
     * 获取所有集合名称
     */
    List<String> getCollectionNames();
}

设计这个接口时的考虑:

  • 使用Map作为数据载体:这样比较灵活,不用为每种数据都定义一个类。对于物联网场景,设备数据结构变化频繁,用Map更方便。
  • 覆盖主要操作:基本的增删改查都有,还支持分页、排序、统计等常用功能。
  • 接口简洁:方法命名直观,参数清晰,后面要加新功能也比较容易扩展。

2.2 服务实现类

MongoDBServiceImpl实现了服务接口,并在工具类的基础上添加了业务逻辑处理:

java 复制代码
@Service
@Slf4j
public class MongoDBServiceImpl implements IMongoDBService {
    
    @Override
    public List<Map<String, Object>> find(String collectionName, 
                                          Map<String, Object> query,
                                          int limit, int skip, 
                                          Map<String, Object> sort) {
        // 参数验证
        if (StringUtils.isEmpty(collectionName)) {
            throw new IllegalArgumentException("集合名称不能为空");
        }
        if (query == null) {
            query = new HashMap<>();
        }
        if (sort == null) {
            sort = new HashMap<>();
        }
        if (limit < 0) {
            throw new IllegalArgumentException("limit参数不能为负数");
        }
        if (skip < 0) {
            throw new IllegalArgumentException("skip参数不能为负数");
        }
        
        log.debug("根据条件查询集合{},查询条件: {}, limit: {}, skip: {}, sort: {}", 
                 collectionName, query, limit, skip, sort);
        
        List<Map<String, Object>> result = MongoDBUtils.find(collectionName, query, limit, skip, sort);
        
        log.info("MongoDB分页排序查询集合{}成功,返回{}条记录", collectionName, result.size());
        return result;
    }
    
    @Override
    public Map<String, Object> findById(String collectionName, String id) {
        if (StringUtils.isEmpty(collectionName)) {
            throw new IllegalArgumentException("集合名称不能为空");
        }
        if (StringUtils.isEmpty(id)) {
            throw new IllegalArgumentException("文档ID不能为空");
        }
        
        try {
            Map<String, Object> query = new HashMap<>();
            // 智能ID处理:支持ObjectId和字符串ID
            if (ObjectId.isValid(id)) {
                query.put("_id", new ObjectId(id));
            } else {
                query.put("_id", id);
            }
            
            List<Map<String, Object>> results = MongoDBUtils.find(collectionName, query);
            return results.isEmpty() ? null : results.get(0);
        } catch (Exception e) {
            log.error("根据ID查询集合{}失败,ID: {}, 错误: {}", collectionName, id, e.getMessage());
            return null;
        }
    }
    
    @Override
    public boolean insert(String collectionName, Map<String, Object> document) {
        // 参数验证
        validateParameters(collectionName, document);
        
        // 执行插入操作
        boolean result = MongoDBUtils.insertOne(collectionName, document);
        
        if (result) {
            log.info("MongoDB向集合{}插入文档成功", collectionName);
        } else {
            log.error("MongoDB向集合{}插入文档失败", collectionName);
        }
        
        return result;
    }
    
    private void validateParameters(String collectionName, Map<String, Object> document) {
        if (StringUtils.isEmpty(collectionName)) {
            throw new IllegalArgumentException("集合名称不能为空");
        }
        if (document == null || document.isEmpty()) {
            throw new IllegalArgumentException("文档数据不能为空");
        }
    }
    
    @Override
    public long count(String collectionName, Map<String, Object> query) {
        if (StringUtils.isEmpty(collectionName)) {
            throw new IllegalArgumentException("集合名称不能为空");
        }
        
        try {
            return MongoDBUtils.count(collectionName, query);
        } catch (Exception e) {
            log.error("统计集合{}文档数量失败: {}", collectionName, e.getMessage());
            return 0;
        }
    }
}

服务实现类的特点:

  • 参数验证:对输入参数进行严格验证,提高系统健壮性。
  • 异常处理:合理处理各种异常情况,避免系统崩溃。
  • 日志记录:详细记录操作过程,便于问题排查。
  • 智能处理:如ID查询时自动判断ObjectId格式,调用方不用关心ID类型。

三、数据转换机制

在物联网平台中,设备数据通常具有复杂的层次结构。如何把这些Java对象转换成MongoDB文档,是一个需要认真设计的问题。

3.1 设备数据结构分析

以我们平台的传感器设备数据为例,数据结构是这样的:

java 复制代码
/**
 * 设备数据VO
 */
@Data
public class DeviceDataVo {
    /** 设备编码 */
    private String deviceCode;
    
    /** 设备名称 */
    private String deviceName;
    
    /** 告警状态:0-正常,1-告警 */
    private Integer alarmStatus;
    
    /** 数据采集时间戳 */
    private Long timestamp;
    
    /** 点位数据列表 */
    private List<DataPointVo> pointData;
}

/**
 * 数据点位VO
 */
@Data
public class DataPointVo {
    /** 点位编码 */
    private String pointCode;
    
    /** 点位名称 */
    private String pointName;
    
    /** 点位值 */
    private Object value;
    
    /** 单位 */
    private String unit;
    
    /** 状态:0-正常,1-异常 */
    private Integer status;
    
    /** 位置元素 */
    private LocationElementVo locationElement;
}

/**
 * 位置元素VO
 */
@Data
public class LocationElementVo {
    /** 元素编码 */
    private String elementCode;
    
    /** 元素名称 */
    private String elementName;
    
    /** 经度 */
    private Double longitude;
    
    /** 纬度 */
    private Double latitude;
    
    /** 描述 */
    private String description;
}

这是一个典型的三层嵌套结构:设备数据 → 点位数据 → 位置信息。

3.2 文档转换策略

将复杂的Java对象转换为MongoDB文档需要考虑以下因素:

(1)数据完整性

确保所有重要字段都被正确转换,不能丢失数据。

(2)类型兼容性

处理Java类型到BSON类型的转换。MongoDB支持的BSON类型有限,有些Java类型需要特殊处理。

(3)嵌套结构

正确处理对象的嵌套关系,保持数据的层次结构。

(4)性能优化

避免不必要的数据复制和转换,提高处理效率。

3.3 转换实现

我们采用手动转换的方式,虽然代码多一些,但可控性更强:

java 复制代码
@Component
@Slf4j
public class DeviceDataConverter {
    
    /**
     * 将设备数据VO转换为MongoDB文档
     */
    public Document convertToMongoDocument(DeviceDataVo deviceData) {
        if (deviceData == null) {
            return null;
        }
        
        Document document = new Document();
        
        // 1. 基础设备信息
        document.put("deviceCode", deviceData.getDeviceCode());
        document.put("deviceName", deviceData.getDeviceName());
        document.put("alarmStatus", deviceData.getAlarmStatus());
        document.put("timestamp", deviceData.getTimestamp());
        document.put("createTime", System.currentTimeMillis());
        
        // 2. 转换点位数据
        List<Document> pointDataDocs = convertPointDataList(deviceData.getPointData());
        document.put("pointData", pointDataDocs);
        
        return document;
    }
    
    /**
     * 转换点位数据列表
     */
    private List<Document> convertPointDataList(List<DataPointVo> pointDataList) {
        if (pointDataList == null || pointDataList.isEmpty()) {
            return Collections.emptyList();
        }
        
        List<Document> pointDataDocs = new ArrayList<>(pointDataList.size());
        
        for (DataPointVo point : pointDataList) {
            Document pointDoc = convertToPointDocument(point);
            if (pointDoc != null) {
                pointDataDocs.add(pointDoc);
            }
        }
        
        return pointDataDocs;
    }
    
    /**
     * 转换单个点位数据
     */
    private Document convertToPointDocument(DataPointVo point) {
        if (point == null) {
            return null;
        }
        
        Document pointDoc = new Document();
        pointDoc.put("pointCode", point.getPointCode());
        pointDoc.put("pointName", point.getPointName());
        pointDoc.put("value", point.getValue());
        pointDoc.put("unit", point.getUnit());
        pointDoc.put("status", point.getStatus());
        
        // 转换位置元素
        if (point.getLocationElement() != null) {
            Document locationDoc = convertToLocationDocument(point.getLocationElement());
            pointDoc.put("locationElement", locationDoc);
        }
        
        return pointDoc;
    }
    
    /**
     * 转换位置元素
     */
    private Document convertToLocationDocument(LocationElementVo locationElement) {
        if (locationElement == null) {
            return null;
        }
        
        Document locationDoc = new Document();
        locationDoc.put("elementCode", locationElement.getElementCode());
        locationDoc.put("elementName", locationElement.getElementName());
        locationDoc.put("longitude", locationElement.getLongitude());
        locationDoc.put("latitude", locationElement.getLatitude());
        locationDoc.put("description", locationElement.getDescription());
        
        return locationDoc;
    }
}

为什么不用JSON序列化?

刚开始我尝试直接用Jackson把对象序列化成JSON,再解析成Document。但发现有几个问题:

  • 类型丢失:Date类型序列化后变成时间戳字符串,查询时需要额外处理。
  • null值处理:JSON序列化会保留null值,但MongoDB对null值比较敏感。
  • 特殊类型:BigDecimal、ObjectId等特殊类型需要自定义序列化器。

改成手动转换后,虽然代码多了一些,但是可控性更强,也更容易处理边界情况。

3.4 批量处理优化

对于大量数据的处理,我们采用定时任务+批量操作的方式来提高性能:

java 复制代码
@Component
@Slf4j
public class DeviceDataEventListener {
    
    @Autowired
    private MongoDBService mongoDBService;
    
    @Autowired
    private DeviceDataConverter deviceDataConverter;
    
    /**
     * 每10分钟执行一次,批量保存设备数据
     */
    @Scheduled(fixedRate = 600000)
    public void saveDeviceDataToMongoDB() {
        try {
            log.info("开始收集设备数据并保存到MongoDB");
            
            // 1. 从Redis获取处理后的数据
            List<DeviceDataVo> deviceDataList = collectDeviceDataFromRedis();
            
            if (deviceDataList.isEmpty()) {
                log.info("没有设备数据需要保存");
                return;
            }
            
            // 2. 转换并批量插入
            int successCount = 0;
            int failCount = 0;
            
            for (DeviceDataVo deviceData : deviceDataList) {
                try {
                    Document document = deviceDataConverter.convertToMongoDocument(deviceData);
                    boolean success = MongoDBUtils.insertOne("device_data", document.toMap());
                    
                    if (success) {
                        successCount++;
                        log.debug("设备{}数据保存成功", deviceData.getDeviceCode());
                    } else {
                        failCount++;
                        log.warn("设备{}数据保存失败", deviceData.getDeviceCode());
                    }
                } catch (Exception e) {
                    failCount++;
                    log.error("设备{}数据转换或保存失败: {}", 
                             deviceData.getDeviceCode(), e.getMessage());
                }
            }
            
            log.info("设备数据保存完成,总数: {}, 成功: {}, 失败: {}", 
                    deviceDataList.size(), successCount, failCount);
            
        } catch (Exception e) {
            log.error("保存设备数据到MongoDB失败", e);
        }
    }
    
    /**
     * 从Redis收集设备数据
     */
    private List<DeviceDataVo> collectDeviceDataFromRedis() {
        // 实现从Redis获取数据的逻辑
        // ...
        return Collections.emptyList();
    }
}

批量处理的优化点:

  • 定时执行:避免实时写入对数据库造成压力,可以控制写入频率。
  • 逐条处理:单条失败不影响其他数据,保证数据一致性。
  • 统计日志:记录成功和失败的数量,便于监控和排查问题。

四、踩过的坑

4.1 ObjectId的处理

MongoDB默认使用ObjectId作为文档的_id,这是一个12字节的唯一标识。但在实际业务中,我们可能使用字符串类型的ID。

java 复制代码
// 错误做法:直接用字符串查询ObjectId类型的_id
query.put("_id", "507f1f77bcf86cd799439011");  // 查不到数据

// 正确做法:先判断是否是有效的ObjectId格式
if (ObjectId.isValid(id)) {
    query.put("_id", new ObjectId(id));
} else {
    query.put("_id", id);
}

4.2 null值的处理

MongoDB对null值比较敏感,查询时需要注意:

java 复制代码
// 这两种查询是不同的
db.collection.find({field: null})      // 查询field值为null或field不存在的文档
db.collection.find({field: {$type: 10}})  // 只查询field值为null的文档

我们的做法是在转换时就把null值过滤掉:

java 复制代码
private void putIfNotNull(Document doc, String key, Object value) {
    if (value != null) {
        doc.put(key, value);
    }
}

4.3 连接泄漏问题

之前遇到过连接泄漏的问题,排查后发现是游标没有正确关闭。使用try-with-resources语法可以避免这个问题:

java 复制代码
// 正确做法
try (MongoCursor<Document> cursor = collection.find().iterator()) {
    while (cursor.hasNext()) {
        // 处理数据
    }
}  // 自动关闭游标

五、小结

这篇文章聊了核心组件的设计和实现,包括MongoDBUtils工具类的连接管理、CRUD操作封装,服务层的接口设计和参数校验、异常处理最佳实践,以及数据转换和批量处理的策略。这些都是踩过坑之后的经验总结。

说起来,写代码的过程中有几个感受:一是连接池配置要合理,连接泄漏的问题排查起来挺费劲的;二是索引一定要建,特别是高频查询字段;三是能批量就批量,单条和批量性能差距挺大;四是异常处理和日志要到位,排查问题时就知道多重要了。

下一篇文章我们聊聊性能优化和监控告警,这些对生产环境稳定运行很关键。

相关推荐
csdn_aspnet1 小时前
使用 Docker 运行 Microsoft SQL 数据库服务器
数据库·microsoft·docker·sqlserver
SA-D1 小时前
MySQL 性能分析与库存一致性:从 Buffer Pool、B+ 树到执行计划
数据库·mysql
3095566662 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
Yeats_Liao2 小时前
物联网平台MongoDB实战|(三)性能优化与生产实践
数据库·mongodb·性能优化
ZhengEnCi2 小时前
微信用SQLite为什么还要WCDB:聊天记录加密并发与坏库修复的工程真相
数据库·微信·sqlite
挖掘狂人3 小时前
如何保证缓存与数据库一致性
数据库·后端·程序员
codigger3 小时前
如何保证缓存与数据库一致性
数据库·缓存·程序员
游哇游哇游4 小时前
Redis 过期删除与内存淘汰源码级详解:惰性+定期删除、近似 LRU/LFU、8 种策略与内存打满排查
数据库·redis·缓存·面试·bootstrap
星落梦生4 小时前
苍穹外卖day05——Redis
数据库·redis·缓存