使用Locust对MongoDB进行负载测试

1.安装环境

bash 复制代码
pip install pymongo locust

2.设置测试环境

开启MongoDB服务

打开Navicat,新建MongoDB连接

新建test数据库和sample集合

3.编写脚本

load_mongo.py

python 复制代码
# coding=utf-8
from locust import User, task, between, events
from pymongo import MongoClient
import random
import string
import logging

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("MongoDB Load Test")

# MongoDB连接配置
MONGO_URI = "mongodb://admin:admin@localhost:27017/?authSource=admin"
DATABASE_NAME = "test"
COLLECTION_NAME = "sample"


# 自定义MongoDB客户端
class MongoDBClient:
    def __init__(self):
        try:
            self.client = MongoClient(MONGO_URI)
            self.db = self.client[DATABASE_NAME]
            self.collection = self.db[COLLECTION_NAME]
            logger.info("MongoDB client initialized successfully.")
        except Exception as e:
            logger.error(f"Failed to connect to MongoDB: {e}")
            self.client = None

    def insert_document(self, document):
        if self.collection is not None:
            self.collection.insert_one(document)
            logger.info("Document inserted successfully.")
        else:
            logger.error("MongoDB collection is not available.")

    def close_connection(self):
        if self.client is not None:
            self.client.close()
            logger.info("MongoDB client connection closed.")


# Locust用户类
class MongoDBUser(User):
    wait_time = between(1, 2)
    mongo_client = None

    @staticmethod
    def initialize_mongo_client():
        if MongoDBUser.mongo_client is None:
            logger.info("Initializing MongoDB client...")
            MongoDBUser.mongo_client = MongoDBClient()

    @staticmethod
    def cleanup_mongo_client():
        if MongoDBUser.mongo_client:
            MongoDBUser.mongo_client.close_connection()
            MongoDBUser.mongo_client = None
            logger.info("MongoDB client cleaned up.")

    # 监听测试开始
    @staticmethod
    @events.test_start.add_listener
    def on_test_start(environment, **kwargs):
        MongoDBUser.initialize_mongo_client()

    # 监听测试结束
    @staticmethod
    @events.test_stop.add_listener
    def on_test_stop(environment, **kwargs):
        MongoDBUser.cleanup_mongo_client()

    @task(2)
    def insert_data(self):
        """模拟插入数据的任务"""
        if MongoDBUser.mongo_client is None:
            logger.error("MongoDB client is not initialized.")
            return
        document = {
            "name": ''.join(random.choices(string.ascii_letters, k=10)),
            "age": random.randint(18, 65),
            "address": ''.join(random.choices(string.ascii_letters + string.digits, k=20)),
        }
        MongoDBUser.mongo_client.insert_document(document)
        logger.info(f"Inserted document: {document}")

4.运行测试

打开终端执行命令

bash 复制代码
locust -f load_mongo.py --headless -u 5 -r 1 -t 5s

测试结果

打开Navicat查看sample表可以看到数据增多

相关推荐
jiayou6421 小时前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区3 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
AI全栈实验室3 天前
MongoDB迁移金仓踩了5个坑,最后一个差点回滚
mongodb
随逸1773 天前
《从零搭建NestJS项目》
数据库·typescript
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
tryCbest4 天前
数据库SQL学习
数据库·sql