物联网平台MongoDB实战|(三)性能优化与生产实践

写在前面

这是「物联网平台MongoDB实战」系列的第三篇文章,也是最后一篇。

前两篇文章我们讨论了为什么选择MongoDB,以及核心组件的设计与实现。这一篇,我们重点聊聊性能优化和生产环境中的实践经验。

说实话,性能优化这块是最让我头疼的。一开始觉得MongoDB很简单,建几个索引就完事了。但真正上线后才发现,问题远比想象中复杂:慢查询、连接池耗尽、内存占用过高......各种问题接踵而来。这篇文章记录的是我们在这些问题上摸爬滚打的经验,希望能帮你少走一些弯路。

一、连接池优化

连接池配置是MongoDB性能优化的第一步,配置不当可能导致连接等待、资源浪费等问题。

1.1 连接池参数详解

yaml 复制代码
mongodb:
  host: localhost
  port: 27017
  database: iot_platform
  # 连接池配置
  max-connections-per-host: 100
  min-connections-per-host: 10
  # 超时配置
  connection-timeout: 10000
  socket-timeout: 10000
  max-wait-time: 30000
  # 连接生命周期
  max-connection-life-time: 3600000
  max-connection-idle-time: 1800000
  # 心跳配置
  heartbeat-frequency: 10000

参数说明:

参数 说明 推荐值 调优建议
max-connections-per-host 最大连接数 100-500 根据并发量调整,公式:并发数 × 平均查询时间
min-connections-per-host 最小连接数 10-20 保持预热连接,避免冷启动
connection-timeout 连接超时 10秒 网络延迟高时可适当增加
socket-timeout 读写超时 10秒 慢查询多时可适当增加
max-wait-time 获取连接等待时间 30秒 避免无限等待
max-connection-life-time 连接最大存活时间 60分钟 防止长时间使用同一连接
max-connection-idle-time 空闲连接存活时间 30分钟 及时释放空闲连接
heartbeat-frequency 心跳频率 10秒 及时发现服务器故障

1.2 连接池大小计算

连接池大小不是越大越好,需要根据实际情况计算:

复制代码
连接池大小 = 并发请求数 × 平均查询时间(秒) + 冗余量

举个例子:

  • 系统峰值并发:200个请求
  • 平均查询时间:50ms(0.05秒)
  • 冗余量:20%

计算:200 × 0.05 × 1.2 = 12

这种情况下,连接池大小设置15-20就足够了。设置太大反而浪费资源。

1.3 连接池监控

我们实现了连接池状态的监控,方便排查问题:

java 复制代码
@Component
@Slf4j
public class MongoDBConnectionMonitor {
    
    @Autowired
    private MongoClient mongoClient;
    
    @Scheduled(fixedRate = 60000)  // 每分钟执行一次
    public void monitorConnectionPool() {
        try {
            // 获取连接池状态
            ConnectionPoolStatistics stats = 
                (ConnectionPoolStatistics) mongoClient.getClusterDescription()
                    .getServerDescriptions().get(0)
                    .getConnectionPoolStatistics();
            
            if (stats != null) {
                int activeCount = stats.getActiveConnectionCount();
                int availableCount = stats.getAvailableConnectionCount();
                int pendingCount = stats.getPendingConnectionCount();
                int maxSize = stats.getMaxSize();
                
                log.info("MongoDB连接池状态 - 活跃: {}, 空闲: {}, 等待: {}, 最大: {}", 
                        activeCount, availableCount, pendingCount, maxSize);
                
                // 告警判断
                double usageRate = (double) activeCount / maxSize;
                if (usageRate > 0.8) {
                    log.warn("MongoDB连接池使用率过高: {}%", usageRate * 100);
                }
                
                if (pendingCount > 10) {
                    log.warn("MongoDB连接池等待队列过长: {}", pendingCount);
                }
            }
        } catch (Exception e) {
            log.error("获取MongoDB连接池状态失败", e);
        }
    }
}

二、索引设计与优化

索引是MongoDB性能优化的核心,合理的索引设计可以让查询性能提升几个数量级。

2.1 索引类型选择

MongoDB支持多种索引类型,需要根据查询模式选择:

(1)单字段索引

适用于单字段查询:

javascript 复制代码
// 设备编码查询
db.device_data.createIndex({"deviceCode": 1})

// 时间戳查询
db.device_data.createIndex({"timestamp": -1})

(2)复合索引

适用于多字段组合查询:

javascript 复制代码
// 设备+时间组合查询
db.device_data.createIndex({"deviceCode": 1, "timestamp": -1})

// 设备+时间+告警状态组合查询
db.device_data.createIndex({
  "deviceCode": 1,
  "timestamp": -1,
  "alarmStatus": 1
})

复合索引的设计原则:

  • ESR原则:Equality(等值)→ Sort(排序)→ Range(范围)
  • 等值查询的字段放在前面
  • 排序字段放在中间
  • 范围查询的字段放在后面

(3)TTL索引

自动过期删除,适合日志和时序数据:

javascript 复制代码
// 30天后自动删除
db.device_logs.createIndex(
  {"createdAt": 1}, 
  {expireAfterSeconds: 2592000}
)

(4)文本索引

支持全文搜索:

javascript 复制代码
// 设备名称全文搜索
db.devices.createIndex({"deviceName": "text"})

// 搜索包含"温度"的设备
db.devices.find({$text: {$search: "温度"}})

(5)地理空间索引

支持地理位置查询:

javascript 复制代码
// 2dsphere索引
db.devices.createIndex({"location": "2dsphere"})

// 查询半径5公里内的设备
db.devices.find({
  "location": {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [116.397, 39.909]
      },
      $maxDistance: 5000
    }
  }
})

2.2 索引设计实例

以设备数据查询为例,我们设计了以下索引:

javascript 复制代码
// 1. 设备编码索引(高频单字段查询)
db.device_data.createIndex({"deviceCode": 1})

// 2. 时间戳索引(时序查询)
db.device_data.createIndex({"timestamp": -1})

// 3. 设备+时间复合索引(设备历史数据查询)
db.device_data.createIndex({"deviceCode": 1, "timestamp": -1})

// 4. 告警状态索引(告警查询)
db.device_data.createIndex({"alarmStatus": 1})

// 5. 设备+时间+告警复合索引(复杂查询)
db.device_data.createIndex({
  "deviceCode": 1,
  "timestamp": -1,
  "alarmStatus": 1
})

2.3 索引优化技巧

(1)避免过度索引

索引不是越多越好,每个索引都会占用存储空间,并降低写入性能。建议:

  • 只为实际使用的查询创建索引
  • 定期检查索引使用情况,删除无用索引
javascript 复制代码
// 查看索引使用情况
db.device_data.aggregate([{$indexStats: {}}])

// 删除无用索引
db.device_data.dropIndex("unused_index_name")

(2)使用覆盖查询

如果查询的所有字段都在索引中,MongoDB可以直接从索引返回结果,不需要查询文档:

javascript 复制代码
// 创建复合索引
db.device_data.createIndex({"deviceCode": 1, "timestamp": -1, "value": 1})

// 覆盖查询:只返回索引字段
db.device_data.find(
  {"deviceCode": "sensor_001"},
  {"_id": 0, "deviceCode": 1, "timestamp": 1, "value": 1}
)

(3)避免索引失效的情况

以下情况会导致索引失效:

  • 使用$ne、$nin操作符
  • 使用$or操作符(每个条件都要有索引)
  • 对索引字段使用函数或计算
  • 查询条件中使用正则表达式的开头是通配符
javascript 复制代码
// 索引失效示例
db.device_data.find({"deviceCode": {$ne: "sensor_001"}})  // 不走索引
db.device_data.find({$or: [{deviceCode: "a"}, {deviceName: "b"}]})  // 部分走索引
db.device_data.find({deviceCode: /^sensor/})  // 走索引
db.device_data.find({deviceCode: /sensor$/})  // 不走索引

2.4 慢查询分析

MongoDB提供了慢查询日志,可以用来分析性能问题:

javascript 复制代码
// 开启慢查询日志(查询超过100ms记录)
db.setProfilingLevel(1, 100)

// 查看慢查询
db.system.profile.find().sort({ts: -1}).limit(10)

// 分析查询执行计划
db.device_data.find({
  "deviceCode": "sensor_001",
  "timestamp": {$gte: 1699876543000}
}).explain("executionStats")

explain结果关键字段:

字段 说明
executionTimeMillis 执行时间(毫秒)
totalDocsExamined 扫描文档数
totalKeysExamined 扫描索引键数
nReturned 返回文档数
indexUsed 使用的索引

优化判断标准:

  • totalDocsExamined / nReturned 应该接近1,否则说明扫描了大量无用文档
  • executionTimeMillis 应该在可接受范围内

三、查询优化

除了索引优化,查询语句本身的写法也会影响性能。

3.1 查询优化实例

(1)使用投影减少返回数据

java 复制代码
// 只查询需要的字段
public List<Map<String, Object>> findDeviceBasicInfo(String deviceCode) {
    Map<String, Object> query = new HashMap<>();
    query.put("deviceCode", deviceCode);
    
    Map<String, Object> projection = new HashMap<>();
    projection.put("deviceCode", 1);
    projection.put("deviceName", 1);
    projection.put("alarmStatus", 1);
    projection.put("_id", 0);
    
    return MongoDBUtils.findWithProjection("device_data", query, projection);
}

(2)分页查询优化

传统的skip+limit分页在大数据量时性能很差:

java 复制代码
// 传统分页(数据量大时性能差)
public List<Map<String, Object>> findByPage(int page, int size) {
    int skip = (page - 1) * size;
    return MongoDBUtils.find("device_data", null, size, skip, null);
}

推荐使用游标分页:

java 复制代码
// 游标分页(性能更好)
public List<Map<String, Object>> findByCursor(String lastId, int size) {
    Map<String, Object> query = new HashMap<>();
    if (StringUtils.hasText(lastId)) {
        query.put("_id", new Document("$gt", new ObjectId(lastId)));
    }
    
    Map<String, Object> sort = new HashMap<>();
    sort.put("_id", 1);
    
    return MongoDBUtils.find("device_data", query, size, 0, sort);
}

(3)批量查询优化

避免N+1查询,使用$in操作符:

java 复制代码
// 错误做法:循环查询
public List<Map<String, Object>> findDevicesBad(List<String> deviceCodes) {
    List<Map<String, Object>> result = new ArrayList<>();
    for (String code : deviceCodes) {
        Map<String, Object> query = new HashMap<>();
        query.put("deviceCode", code);
        result.addAll(MongoDBUtils.find("device_data", query));
    }
    return result;
}

// 正确做法:使用$in
public List<Map<String, Object>> findDevicesGood(List<String> deviceCodes) {
    Map<String, Object> query = new HashMap<>();
    query.put("deviceCode", new Document("$in", deviceCodes));
    return MongoDBUtils.find("device_data", query);
}

3.2 聚合管道优化

MongoDB的聚合管道功能强大,但也容易写出低效的查询:

java 复制代码
// 统计每个设备的平均温度
public Map<String, Double> getAverageTemperatureByDevice() {
    List<Document> pipeline = Arrays.asList(
        // 1. 先过滤,减少后续处理的数据量
        new Document("$match", new Document("deviceType", "temperature")),
        
        // 2. 只保留需要的字段
        new Document("$project", new Document()
            .append("deviceCode", 1)
            .append("temperature", "$data.temperature")),
        
        // 3. 分组统计
        new Document("$group", new Document()
            .append("_id", "$deviceCode")
            .append("avgTemp", new Document("$avg", "$temperature"))
            .append("count", new Document("$sum", 1))),
        
        // 4. 过滤低频数据
        new Document("$match", new Document("count", new Document("$gte", 10))),
        
        // 5. 排序
        new Document("$sort", new Document("avgTemp", -1))
    );
    
    MongoCollection<Document> collection = MongoDBUtils.getCollection("device_data");
    Map<String, Double> result = new HashMap<>();
    
    try (MongoCursor<Document> cursor = collection.aggregate(pipeline).iterator()) {
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            result.put(doc.getString("_id"), doc.getDouble("avgTemp"));
        }
    }
    
    return result;
}

聚合管道优化原则:

  • $match放在前面,尽早过滤数据
  • $limit尽早使用,限制处理的数据量
  • 只$project需要的字段
  • 避免在$group中使用过多字段

四、错误处理与监控

生产环境中,完善的错误处理和监控是系统稳定运行的保障。

4.1 异常处理机制

java 复制代码
@Service
@Slf4j
public class MongoDBServiceImpl implements IMongoDBService {
    
    @Override
    public boolean insert(String collectionName, Map<String, Object> document) {
        try {
            // 参数验证
            validateParameters(collectionName, document);
            
            // 执行插入操作
            boolean result = MongoDBUtils.insertOne(collectionName, document);
            
            if (result) {
                log.info("MongoDB向集合{}插入文档成功", collectionName);
            } else {
                log.error("MongoDB向集合{}插入文档失败", collectionName);
            }
            
            return result;
            
        } catch (IllegalArgumentException e) {
            // 参数错误,记录日志并抛出
            log.error("参数验证失败: {}", e.getMessage());
            throw e;
            
        } catch (MongoWriteException e) {
            // 写入错误
            log.error("MongoDB写入错误,错误码: {}, 消息: {}", 
                     e.getError().getCode(), e.getMessage());
            return false;
            
        } catch (MongoCommandException e) {
            // 命令执行错误(如权限不足)
            log.error("MongoDB命令执行错误,错误码: {}", e.getErrorCode());
            return false;
            
        } catch (MongoTimeoutException e) {
            // 超时错误
            log.error("MongoDB操作超时: {}", e.getMessage());
            return false;
            
        } catch (MongoException e) {
            // 其他MongoDB错误
            log.error("MongoDB操作异常: {}", e.getMessage());
            return false;
            
        } catch (Exception e) {
            // 未知异常
            log.error("未知异常: {}", e.getMessage(), e);
            return false;
        }
    }
    
    private void validateParameters(String collectionName, Map<String, Object> document) {
        if (StringUtils.isEmpty(collectionName)) {
            throw new IllegalArgumentException("集合名称不能为空");
        }
        if (document == null || document.isEmpty()) {
            throw new IllegalArgumentException("文档数据不能为空");
        }
    }
}

4.2 健康检查

实现MongoDB连接健康检查,配合Spring Boot Actuator使用:

java 复制代码
@Component
public class MongoDBHealthIndicator implements HealthIndicator {
    
    @Override
    public Health health() {
        try {
            // 执行简单的ping操作
            Document result = MongoDBUtils.getDatabase().runCommand(
                new Document("ping", 1)
            );
            
            double ok = result.getDouble("ok");
            if (ok == 1.0) {
                return Health.up()
                    .withDetail("database", MongoDBUtils.getDatabaseName())
                    .withDetail("status", "连接正常")
                    .withDetail("responseTime", System.currentTimeMillis())
                    .build();
            } else {
                return Health.down()
                    .withDetail("error", "ping返回异常")
                    .withDetail("response", result.toJson())
                    .build();
            }
            
        } catch (Exception e) {
            return Health.down()
                .withDetail("error", e.getMessage())
                .withDetail("status", "连接异常")
                .build();
        }
    }
}

4.3 性能监控

通过AOP实现操作性能监控:

java 复制代码
@Aspect
@Component
@Slf4j
public class MongoDBPerformanceAspect {
    
    // 慢查询阈值(毫秒)
    private static final long SLOW_QUERY_THRESHOLD = 1000;
    
    // 统计数据
    private final AtomicLong totalOperations = new AtomicLong(0);
    private final AtomicLong slowOperations = new AtomicLong(0);
    private final ConcurrentHashMap<String, AtomicLong> operationCounts = 
        new ConcurrentHashMap<>();
    
    @Around("execution(* com.xinye.iot.data.mongodb.service.impl.MongoDBServiceImpl.*(..))")
    public Object monitorPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        
        try {
            Object result = joinPoint.proceed();
            long duration = System.currentTimeMillis() - startTime;
            
            // 记录统计信息
            totalOperations.incrementAndGet();
            operationCounts.computeIfAbsent(methodName, k -> new AtomicLong(0))
                .incrementAndGet();
            
            // 慢查询告警
            if (duration > SLOW_QUERY_THRESHOLD) {
                slowOperations.incrementAndGet();
                log.warn("MongoDB慢查询 - 方法: {}, 耗时: {}ms, 参数: {}", 
                        methodName, duration, Arrays.toString(joinPoint.getArgs()));
            } else {
                log.debug("MongoDB操作 - 方法: {}, 耗时: {}ms", methodName, duration);
            }
            
            return result;
            
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("MongoDB操作失败 - 方法: {}, 耗时: {}ms, 错误: {}", 
                     methodName, duration, e.getMessage());
            throw e;
        }
    }
    
    /**
     * 获取性能统计信息
     */
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalOperations", totalOperations.get());
        stats.put("slowOperations", slowOperations.get());
        stats.put("slowQueryRate", 
                 totalOperations.get() > 0 
                     ? (double) slowOperations.get() / totalOperations.get() 
                     : 0);
        
        Map<String, Long> opCounts = new HashMap<>();
        operationCounts.forEach((k, v) -> opCounts.put(k, v.get()));
        stats.put("operationCounts", opCounts);
        
        return stats;
    }
}

4.4 监控指标暴露

将监控指标暴露给Prometheus:

java 复制代码
@Component
public class MongoDBMetrics {
    
    private final Counter operationCounter;
    private final Counter errorCounter;
    private final Histogram durationHistogram;
    
    public MongoDBMetrics(MeterRegistry registry) {
        this.operationCounter = Counter.builder("mongodb_operations_total")
            .description("MongoDB操作总数")
            .tag("type", "operation")
            .register(registry);
        
        this.errorCounter = Counter.builder("mongodb_errors_total")
            .description("MongoDB错误总数")
            .tag("type", "error")
            .register(registry);
        
        this.durationHistogram = Histogram.builder("mongodb_operation_duration")
            .description("MongoDB操作耗时")
            .unit(DurationUnit.MILLISECONDS)
            .register(registry);
    }
    
    public void recordOperation(String operation, long duration, boolean success) {
        operationCounter.increment();
        durationHistogram.record(duration);
        
        if (!success) {
            errorCounter.increment();
        }
    }
}

五、测试策略

完善的测试是保证代码质量的关键。

5.1 单元测试

为MongoDB服务编写完整的单元测试:

java 复制代码
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
@Slf4j
class MongoDBServiceTest {
    
    @Autowired
    private IMongoDBService mongoDBService;
    
    private static final String TEST_COLLECTION = "test_collection";
    private static String testDocumentId;
    
    @Test
    @Order(1)
    @DisplayName("测试插入文档")
    void testInsert() {
        Map<String, Object> document = new HashMap<>();
        document.put("name", "测试设备");
        document.put("type", "sensor");
        document.put("value", 25.5);
        document.put("timestamp", System.currentTimeMillis());
        
        boolean result = mongoDBService.insert(TEST_COLLECTION, document);
        
        assertTrue(result, "文档插入应该成功");
        log.info("插入测试文档成功");
    }
    
    @Test
    @Order(2)
    @DisplayName("测试查询文档")
    void testFind() {
        Map<String, Object> query = new HashMap<>();
        query.put("type", "sensor");
        
        List<Map<String, Object>> results = mongoDBService.find(TEST_COLLECTION, query);
        
        assertFalse(results.isEmpty(), "应该找到匹配的文档");
        
        Map<String, Object> document = results.get(0);
        assertEquals("测试设备", document.get("name"));
        assertEquals("sensor", document.get("type"));
        
        testDocumentId = document.get("_id").toString();
        log.info("查询测试文档成功,ID: {}", testDocumentId);
    }
    
    @Test
    @Order(3)
    @DisplayName("测试更新文档")
    void testUpdate() {
        Map<String, Object> update = new HashMap<>();
        update.put("value", 30.0);
        update.put("lastModified", System.currentTimeMillis());
        
        boolean result = mongoDBService.updateById(TEST_COLLECTION, testDocumentId, update);
        
        assertTrue(result, "文档更新应该成功");
        
        // 验证更新结果
        Map<String, Object> updated = mongoDBService.findById(TEST_COLLECTION, testDocumentId);
        assertEquals(30.0, updated.get("value"));
        
        log.info("更新测试文档成功");
    }
    
    @Test
    @Order(4)
    @DisplayName("测试统计文档")
    void testCount() {
        long count = mongoDBService.count(TEST_COLLECTION);
        
        assertTrue(count > 0, "集合中应该有文档");
        
        Map<String, Object> query = new HashMap<>();
        query.put("type", "sensor");
        long sensorCount = mongoDBService.count(TEST_COLLECTION, query);
        
        assertTrue(sensorCount > 0, "应该有sensor类型的文档");
        
        log.info("统计测试成功,总数: {}, sensor类型: {}", count, sensorCount);
    }
    
    @Test
    @Order(5)
    @DisplayName("测试删除文档")
    void testDelete() {
        boolean result = mongoDBService.deleteById(TEST_COLLECTION, testDocumentId);
        
        assertTrue(result, "文档删除应该成功");
        
        // 验证删除结果
        Map<String, Object> deleted = mongoDBService.findById(TEST_COLLECTION, testDocumentId);
        assertNull(deleted, "文档应该已被删除");
        
        log.info("删除测试文档成功");
    }
    
    @Test
    @DisplayName("测试参数校验")
    void testParameterValidation() {
        // 测试空集合名称
        assertThrows(IllegalArgumentException.class, () -> {
            mongoDBService.insert(null, new HashMap<>());
        });
        
        // 测试空文档
        assertThrows(IllegalArgumentException.class, () -> {
            mongoDBService.insert(TEST_COLLECTION, null);
        });
        
        log.info("参数校验测试成功");
    }
}

5.2 集成测试

使用TestContainers进行集成测试,确保测试环境与生产环境一致:

java 复制代码
@SpringBootTest
@Testcontainers
@Slf4j
class MongoDBIntegrationTest {
    
    @Container
    static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.4")
            .withExposedPorts(27017);
    
    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("mongodb.host", mongoDBContainer::getHost);
        registry.add("mongodb.port", mongoDBContainer::getFirstMappedPort);
        registry.add("mongodb.database", () -> "test_db");
    }
    
    @Autowired
    private IMongoDBService mongoDBService;
    
    @Test
    @DisplayName("测试完整工作流程")
    void testCompleteWorkflow() {
        String collection = "integration_test";
        
        // 1. 批量插入
        List<Map<String, Object>> documents = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Map<String, Object> doc = new HashMap<>();
            doc.put("index", i);
            doc.put("batch", "test");
            documents.add(doc);
        }
        
        boolean insertResult = mongoDBService.insertMany(collection, documents);
        assertTrue(insertResult, "批量插入应该成功");
        
        // 2. 查询验证
        Map<String, Object> query = new HashMap<>();
        query.put("batch", "test");
        List<Map<String, Object>> results = mongoDBService.find(collection, query);
        assertEquals(100, results.size(), "应该查询到100条记录");
        
        // 3. 统计验证
        long count = mongoDBService.count(collection, query);
        assertEquals(100, count, "统计数量应该为100");
        
        // 4. 批量更新
        Map<String, Object> update = new HashMap<>();
        update.put("updated", true);
        long updatedCount = mongoDBService.updateMany(collection, query, update);
        assertEquals(100, updatedCount, "应该更新100条记录");
        
        // 5. 批量删除
        long deletedCount = mongoDBService.deleteMany(collection, query);
        assertEquals(100, deletedCount, "应该删除100条记录");
        
        log.info("完整工作流程测试成功");
    }
    
    @Test
    @DisplayName("测试并发操作")
    void testConcurrentOperations() throws InterruptedException {
        String collection = "concurrent_test";
        int threadCount = 10;
        int operationsPerThread = 100;
        
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        CountDownLatch latch = new CountDownLatch(threadCount);
        AtomicInteger successCount = new AtomicInteger(0);
        
        for (int i = 0; i < threadCount; i++) {
            final int threadIndex = i;
            executor.submit(() -> {
                try {
                    for (int j = 0; j < operationsPerThread; j++) {
                        Map<String, Object> doc = new HashMap<>();
                        doc.put("thread", threadIndex);
                        doc.put("index", j);
                        doc.put("timestamp", System.currentTimeMillis());
                        
                        if (mongoDBService.insert(collection, doc)) {
                            successCount.incrementAndGet();
                        }
                    }
                } finally {
                    latch.countDown();
                }
            });
        }
        
        latch.await(30, TimeUnit.SECONDS);
        executor.shutdown();
        
        int expectedTotal = threadCount * operationsPerThread;
        assertEquals(expectedTotal, successCount.get(), 
                    "所有操作应该成功");
        
        log.info("并发测试成功,总操作数: {}", successCount.get());
    }
}

六、生产环境经验

6.1 部署架构

生产环境建议使用副本集架构:

复制代码
┌─────────────────────────────────────────────────┐
│                  MongoDB副本集                    │
├─────────────────────────────────────────────────┤
│  ┌─────────┐    ┌─────────┐    ┌─────────┐     │
│  │ Primary │───▶│Secondary│───▶│Secondary│     │
│  │ (读写)   │    │ (只读)   │    │ (只读)   │     │
│  └─────────┘    └─────────┘    └─────────┘     │
│       │              │              │           │
│       └──────────────┴──────────────┘           │
│                  自动故障转移                     │
└─────────────────────────────────────────────────┘

副本集的优势:

  • 高可用:主节点故障时自动切换
  • 数据冗余:多副本保证数据安全
  • 读写分离:读操作可以分散到从节点

6.2 备份策略

java 复制代码
@Component
@Slf4j
public class MongoDBBackupService {
    
    @Scheduled(cron = "0 0 2 * * ?")  // 每天凌晨2点执行
    public void backupDatabase() {
        try {
            String timestamp = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String backupPath = "/backup/mongodb_" + timestamp;
            
            // 使用mongodump备份
            ProcessBuilder pb = new ProcessBuilder(
                "mongodump",
                "--host", mongoDBConfig.getHost(),
                "--port", String.valueOf(mongoDBConfig.getPort()),
                "--db", mongoDBConfig.getDatabase(),
                "--out", backupPath
            );
            
            Process process = pb.start();
            int exitCode = process.waitFor();
            
            if (exitCode == 0) {
                log.info("MongoDB备份成功,路径: {}", backupPath);
                // 清理旧备份(保留最近7天)
                cleanOldBackups(7);
            } else {
                log.error("MongoDB备份失败,退出码: {}", exitCode);
            }
            
        } catch (Exception e) {
            log.error("MongoDB备份异常", e);
        }
    }
    
    private void cleanOldBackups(int keepDays) {
        // 清理超过keepDays天的备份文件
        // ...
    }
}

6.3 容量规划

根据我们的经验,容量规划需要考虑以下因素:

(1)数据量估算

复制代码
单文档大小 × 每日新增文档数 × 保留天数 = 总存储需求

(2)内存规划

MongoDB使用内存映射文件,建议内存大小为:

复制代码
内存 = 工作集大小 + 索引大小 + 系统开销

(3)磁盘规划

  • 使用SSD提高I/O性能
  • 预留足够的空间用于索引和操作日志
  • 启用压缩减少存储空间

七、几点经验总结

7.1 架构设计

(1)分层要清晰

Controller、Service、Utils各司其职,不要混在一起。我们之前有个类既做数据转换又做数据库操作,后来拆开后代码清爽了很多。

(2)面向接口编程

Service层定义接口,方便测试和替换实现。

(3)配置外部化

所有配置参数都放在配置文件中,方便不同环境部署。

7.2 开发细节

(1)连接池很重要

根据并发量合理配置,我们在压测时发现这个对性能影响很大。

(2)索引必须建

特别是查询频繁的字段,比如设备编码、时间戳。之前忘记建索引,查历史数据特别慢。

(3)能批量就批量

单条插入和批量插入性能差别很大。

(4)异常处理要到位

不要简单catch了就不管,至少要记录日志。

7.3 安全考虑

(1)权限最小化

给应用创建专门的用户,只给必要的权限。

(2)敏感数据加密

密码、身份证号这些一定要加密存储。

(3)输入校验

虽然MongoDB没有SQL注入,但参数校验还是要做。

八、总结

这个系列记录了我们在物联网平台项目中使用MongoDB的经验,从选型、架构设计、核心实现到性能优化和生产实践。

回头看,MongoDB的优势主要在于:数据模型灵活,适合结构变化频繁的场景;查询功能强大,嵌套查询、聚合管道都能支持;运维相对简单,不像分库分表那么复杂。

当然也有一些需要注意的地方:事务支持相对较弱,复杂的业务逻辑需要在应用层处理;内存消耗比较大,需要合理配置;索引设计很重要,不然查询性能会很明显地下降。

总的来说,技术选型还是要根据具体业务场景来,没有银弹。我们的经验也不一定适合所有项目,大家参考一下思路,结合实际情况调整就好。

另外说几点心得:先在测试环境充分验证再上生产;建立完善的监控体系,MongoDB的监控指标很丰富;数据无价,定期备份是最后的保障;遇到问题多看官方文档和社区,很多坑别人已经踩过了。

相关推荐
ZhengEnCi24 分钟前
微信用SQLite为什么还要WCDB:聊天记录加密并发与坏库修复的工程真相
数据库·微信·sqlite
挖掘狂人1 小时前
如何保证缓存与数据库一致性
数据库·后端·程序员
codigger2 小时前
如何保证缓存与数据库一致性
数据库·缓存·程序员
游哇游哇游2 小时前
Redis 过期删除与内存淘汰源码级详解:惰性+定期删除、近似 LRU/LFU、8 种策略与内存打满排查
数据库·redis·缓存·面试·bootstrap
星落梦生2 小时前
苍穹外卖day05——Redis
数据库·redis·缓存
djjjx.13 小时前
Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
CoderYanger17 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
MSTcheng.18 小时前
【MySQL】MySQL数据库——表的操作
数据库·mysql·adb
Yeats_Liao19 小时前
物联网平台MongoDB实战|(一)为什么选择MongoDB
数据库·物联网·mongodb