Page View Counter like on StackOverFlow

后端 未结 7 1137
一向
一向 2020-12-04 20:19

What is the best way to implement the page view counter like the ones they have here on the site where each question has a \"Views\" counter?

Factoring in Performanc

相关标签:
7条回答
  • 2020-12-04 20:56

    An efficient way may be : Store your counters in the Application object, you may persist it to file/DB periodically and on application close.

    0 讨论(0)
  • 2020-12-04 20:59

    The counter i optimized works like this:

    UPDATE page_views SET counter = counter + 1 WHERE page_id = x
    if (affected_rows == 0 ) {
       INSERT INTO page_views (page_id, counter) VALUES (x, 1)
    }
    

    This way you run 2 query for the first view, the other views require only 1 query.

    0 讨论(0)
  • 2020-12-04 21:07

    For me the best way is to have a field in the question table and update it when the question is accessed

    UPDATE Questions SET views = views + 1 WHERE QuestionID = x
    

    Application Object: IMO is not scalable because the may end with lots of memory consumption as more questions are accessed.
    Page_views table: no need to, you have to do a costly join after

    0 讨论(0)
  • 2020-12-04 21:09

    You can implement an IHttpHandler to do that.

    0 讨论(0)
  • 2020-12-04 21:12

    Instead of making a database call everytime the database is hit, I would increment a counter using a cache object and depending on how many visits you get to your site every day you have send the page hits to the database every 100th hit to the site. This is waay faster then updating the database on every single hit.

    Or another solution is analyzing the IIS log file and updating hits every 30min through a windows service. This is what I have implemented and it work wonders.

    0 讨论(0)
  • 2020-12-04 21:18

    I've made two observations on the stackoverflow views counter:

    • There's a link element in the header that handles triggering the count update. For this question, the markup looks like this:
      <link href="/questions/246919/increment-view-count" type="text/css" rel="stylesheet" />
      I imagine you could hit that url to update the viewcount without ever actually viewing the page, but I haven't tried it.

    • I had a uservoice ticket, where the response from Jeff indicated that views are not incremented from the same ip twice in a row.

    0 讨论(0)
提交回复
热议问题