我需要一些帮助来弄清楚在使用node,redis和MySQL/MongoDB时需要为每个请求插入大量数据时,最佳实践是什么。
您将如何设置队列来处理每个请求,如下所示:
- 用户在我的应用程序中请求一个 url,即/route/insert-data
- 服务器处理请求,将其添加到 Redis 队列,并将状态 200 发回给用户
- 应用程序通过某种间隔检查 redis 队列中是否有任何内容,如果有,它将选择最旧的队列,将其插入数据库,然后从 redis 中删除密钥
这里最好的方法是什么?我目前有一个快速应用程序设置。
谢谢!
我正在寻找类似的解决方案,但如果有人在寻找。 伪代码将是:
- 查找间隔秒后最接近(向上舍入(的时间戳(例如每 5 秒(
- 使用该时间戳作为 redis 的键
- 使用 Redis 追加将值追加到该键
- 使用 getdel 定期(每秒(检查最后一个可分割的 Redis 密钥(获取,然后删除,以提高性能(。
这可以提高性能,但这只是为了让您了解最简单的流程(Redis 将是 redis 客户端,假设您正在使用库:https://github.com/redis/node-redis (
function findNearestTimestamp() {
var currentTime = Math.floor(Date.now() / 1000); // Get the current time in seconds
var remainder = currentTime % 5; // Calculate the remainder
if (remainder === 0) {
return currentTime; // Current time is already divisible by 5 seconds
} else {
var nearestTimestamp = currentTime + (5 - remainder); // Calculate the nearest timestamp
return nearestTimestamp;
}
}
const sql_values = "('value1', 'value2', 'value3'),";
const redis_key = findNearestTimestamp(5);
redis.append(redis_key,sql_values)
您可以通过简单的方式定期检查密钥,例如
function findLastDivisibleTimestamp(seconds) {
var currentTime = Math.floor(Date.now() / 1000); // Get the current time in seconds
var remainder = currentTime % seconds; // Calculate the remainder
var lastDivisibleTimestamp = currentTime - remainder; // Subtract the remainder
return lastDivisibleTimestamp;
}
setTimeout(()=> {
const last_redis_key = findLastDivisibleTimestamp(5)
const stored_value = redis.getdel(last_redis_key)
const cleaned_value = stored_value ? str.slice(0,-1) : null
if (!cleaned_value) {
//run query here by appending values to sql insert such as
const query = `INSERT INTO table_name (column1, column2, column3)
VALUES ${values}`
}
}), 1 * 1000)
请注意,您将需要添加更多代码,以确保在数据库发生故障时,您可以捕获它,重试它,附加到下一个代码,转储它或其他方式。