基础概念: 秒杀是一种电商促销活动,通常在极短的时间内(如几秒到几分钟)以超低价销售商品。这种活动旨在吸引大量用户关注并迅速完成交易,因此对系统的性能和稳定性有极高的要求。
优势:
类型:
应用场景:
常见问题及原因:
示例代码(前端部分):
// 秒杀按钮点击事件
document.getElementById('seckill-btn').addEventListener('click', function() {
// 发送秒杀请求
fetch('/api/seckill', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ productId: '12345' })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('秒杀成功,请尽快支付!');
} else {
alert('秒杀失败,请重试!');
}
})
.catch(error => {
console.error('Error:', error);
alert('网络错误,请稍后再试!');
});
});
示例代码(后端部分,Node.js):
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { Pool } = require('pg');
app.use(bodyParser.json());
const pool = new Pool({
user: 'your_db_user',
host: 'your_db_host',
database: 'your_db_name',
password: 'your_db_password',
port: 5432,
});
app.post('/api/seckill', async (req, res) => {
const { productId } = req.body;
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query('SELECT stock FROM products WHERE id = $1 FOR UPDATE', [productId]);
if (rows[0].stock > 0) {
await client.query('UPDATE products SET stock = stock - 1 WHERE id = $1', [productId]);
await client.query('COMMIT');
res.json({ success: true });
} else {
await client.query('ROLLBACK');
res.json({ success: false });
}
} catch (e) {
await client.query('ROLLBACK');
res.status(500).json({ success: false, error: e.message });
} finally {
client.release();
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上代码示例,可以看到前端如何发送秒杀请求,以及后端如何处理并发请求并确保库存的正确更新。
Elastic 实战工作坊
Elastic 实战工作坊
云+社区沙龙online第5期[架构演进]
数智话
企业创新在线学堂
视频云直播活动
领取专属 10元无门槛券
手把手带您无忧上云