秒杀是一种电商促销活动,通常指在极短时间内以极低价格出售商品。由于参与人数众多,系统需要处理高并发请求,这对数据库的性能提出了极高的要求。
以下是一个简单的示例,展示如何在 MongoDB 中使用事务来防止超卖现象:
const { MongoClient } = require('mongodb');
async function run() {
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('products');
const session = client.startSession();
session.startTransaction();
try {
const product = await collection.findOne({ _id: 'product_id', stock: { $gt: 0 } }, { session });
if (!product) {
throw new Error('Out of stock');
}
await collection.updateOne({ _id: 'product_id' }, { $inc: { stock: -1 } }, { session });
await session.commitTransaction();
console.log('Purchase successful');
} catch (error) {
await session.abortTransaction();
console.error('Transaction aborted:', error);
}
} finally {
await client.close();
}
}
run().catch(console.dir);MongoDB 在处理秒杀活动时具有显著优势,但也需要针对高并发场景进行优化和防护措施。通过合理使用事务、消息队列和索引优化,可以有效应对秒杀活动中可能遇到的各种挑战。