Simple realtime web counter
This example show how we can combine 2-3 "things" and make useful key names.
Suppose we want to put sign on every page on our website that say:
"This page was visited 45 times today, with 5 different browsers!"
To do so, we combine date using PHP function "date('Ymd')" and md5 sum of current URL. For the browser we do a set with md5 sums of the http_user_agents.
Because we are counting anyway, we will add visits history, in $userkey_glob. We do not use it here, but we keep it for information anyway.
To keep it simple, this example DO NOT deal with unique visitors, just with page views.
All combined should look like this:
$r = new Redis(); $r->connect("127.0.0.1", "6379"); $URL = $_SERVER["SCRIPT_URI"]; $UA = $_SERVER["HTTP_USER_AGENT"]; $d = date("Ymd"); $userkey_ua = "stats:" . $d . ":ua:" . md5($URL); $userkey_url = "stats:" . $d . ":url:" . md5($URL); $userkey_glob = "stats:" . $d; $r->sadd($userkey_ua, md5($UA)); $r->incr($userkey_url); $r->incr($userkey_glob); // Optionally set expire 25 hours from now one, // to be sure will be available until tomorrow. $r->expire($userkey_ua, 3600 * 25); $r->expire($userkey_url, 3600 * 25); // we want $userkey_glob to expire in 32 days $r->expire($userkey_glob, 3600 * 24 * 32); ... // Somewhere at the end of the page... echo sprintf( "This page was visited %d times today, with %d different browsers!", $r->get($userkey_url), $r->scard($userkey_ua) );
- "Rotating" news - can be used in case you want to track last 30-40-N website visitors.
Redis connection note
The example uses generic connection to the Redis server. To make the example work with our service you will need to use code similar to this one:
// change these parameter according to the information in your instance list $host = '188.8.131.52'; $port = 1234; $password = 'somehashcode'; $db = 0; $r = new Redis(); $r->connect($host, $port); $r->auth($password); $r->select($db);
blog comments powered by Disqus
Because we want this page to be useful for memcached users, we tagged with memcached all examples that may be "recreated" for memcached server.
How to use Redis for cache MySQL queries in a way similar to memcached
How to use Redis to prevent web-scraping parsing and web-spam
How to do 'Rotating' news list
How pool random element from news list
How Redis can help us with Accounting / Vote / Like / Recommend / +1 clicks
How to implement fast hi-score table
How to scale Redis on several servers using sharding
How to implement distributed work pool and to scale some work across many computers
How to collect and store information for page visitors
How to make set members to expire
How Redis can help us with user level locks
Creating distributed message queue
Building reverse index using sets
Using Redis to speed up MySQL inserts
Using Redis for caching MySQL or Cassandra data inserts
How to produce 'There are 123 visitors on this page' sign