开发者

Calling redis 'get' inside a loop to display forum post view data

I'm rebuilding a forum/board in rails. One of the requirements is that view information be recorded for a subject.

In the current system, a database call is made every time the page is loaded updating the view count for that post.

I would like to avoid that and am looking at implementing redis to record that information using a technique similar to this post - jQuery Redis hit counter to track view of cached Rails pages

So I would make a request to a controller that would record the view - via javascript - and then a cron job would move the redis usage data to the database (removing it from redis).

My quandary is that the current system offers real-time usage information so that will b开发者_StackOverflow中文版e the expectation moving forward. Using Heroku - as I plan - the most frequent cron jobs would run hourly, which I don't think will be acceptable.

My thought was that I could store the usage information in redis and then while I'm looping through the subjects, I would combine the usage value stored in redis with the value that had been saved in the database from the cron job.

Is this a dumb idea? I'm new to redis so I don't really know what is possible. Is it a huge no-no to do a redis call in a loop like I'm suggesting?


If you really need the old application to mantain real-time statistics, and want to use Redis, then you would have to change legacy code to access it.

Here's a starting point for your code.

At every hit, you can check thread's counter in Redis. If the counter key doesn't exist, this activates load.

So this would be a way to keep the stats updated (using php, phpredis client):

try {
    $redis = new \Redis();
    $thread_id = getFromPostGet("thread_id"); //suppose so
    $key = 'ViewCounterKey:' . $thread_id; //each thread has a counter key

    $redis->multi(); //begin transaction
    if (!$redis->exists($key)) {
        $counter = getFromDB("count(*) where thread_id = $thread_id"); //suppose so
        $redis->set($key, $counter);
    }
    $redis->incr($key); //every hit incrs the counter
    $redis->exec(); //end transaction
}
catch (\RedisException $e) {
    echo "Server down";
}

So this solution can be put together with cron jobs, which would persist the view count, and the latency of 1h between each cron would not matter, because you're always looking into memory (Redis, not DB).

Hope that makes sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜