标题:针对特定情况有效使用正确的redis数据类型。
我理解redis必须提供的主要5种数据类型(以及它们如何工作),但知道在特定情况下使用哪种数据,无论我读过多少教程,都让我感到困惑!
例如,我是否会使用sadd
或hincrby
来衡量依赖于会话/用户ID的唯一统计信息。
我的目标是尽可能高效地使用redis,同时仍然提供统计/分析的所有可能总数。
示例:
var device = {
UDID: 1
};
redis.incr("total_app_visits"); // Is this wasted memory due to being able to total `unique_app_visits` and `returning_visits_total` below ?
// Alternatively we could use hincryby("unique_app_visits", device.UDID, 1);
// Which is more efficient here? Which would work better for getting the most out of?
redis.sadd("unique_app_visits", device.UDID, function(err, result) {
if (result === 0) { // If this is not a unique visit, then it means they are a returning customer.
redis.hincrby("returning_app_visits", device.UDID, 1);
redis.incr("returning_visits_total"); // Is this also wasted memory due to being able to get the total from `returning_app_visits` by iterating with `hgetall` Or is this a compuational performance cost too great?
}
});
**编辑**
使用hgetall
检索returning_app_visits
总计的示例:
redis.hgetall("returning_app_visits", function(err, result) {
var returning_visits_total = 0;
for (user in result) {
returning_visits_total = returning_visits_total + Number(result[user]);
}
console.log("returning_visits_total: " + returning_visits_total);
});
相关资源:
What are the underlying data structures used for Redis?
Redis types and their respective pros and cons