开发者

An efficient way to store view counts for objects?

开发者 https://www.devze.com 2023-02-01 22:19 出处:网络
I maintain an application where users are able to store images, and then share them. The system is powered by MongoDB at the back end. Most of the image depiction pages are cached as flat HTML files,

I maintain an application where users are able to store images, and then share them. The system is powered by MongoDB at the back end. Most of the image depiction pages are cached as flat HTML files, but I can run some code just before loading the file.

I've decided to implement a view count for the system. I am wondering what is the best storage place for that. It should be like Memcached but it should save the viewcounts every hour or so, so even if our server has to be restarted we won't lose the view counts.

What is the best solution for that (preferably with a PHP extension 开发者_如何学编程as a client)?


You might look into Redis. Sort of a cross between NoSQL and memcached. You can have Redis save to disk though. Is memcached a dinosaur in comparison to Redis?


It sounds like the view count is for each cached flat HTML file? Why not store them in some code at the start of the file. It can be taken out when the file is viewed...


I once solved this problem by storing the view count in memcached and then updating the database at random intervals based on the number of views. The probability of storing to the database was 1/sqrt(number of views). This had nice properties. If the number of views was small, like 4, then the probability of writing to the database was 1/2. If the number of views on an object was high, say 1,000,000, then the probability goes to 1/1000. It seemed to work well.


Do thing simple ... if you does not require a real time report/statistic, you should just parse the daily apache log and store the number of matches into database or even in a flat file format.

Benefits?

  1. it does not harm your existing application
  2. it does not require additional memcache or so
  3. just need to parse the daily log apache (once a day)
  4. recoverable

Of course, this does not stop you from set-up a cronjob to periodically read/update database (for fresher view count)

0

精彩评论

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

关注公众号