Once again, we'll use a couple of EC2 instances running Ubuntu 12.04: one for the Node.js web server and one for the memcached server. MongoDB will still be served from MongoLab.
Start your instances and let's configure our memcached server first. Since it requires port 11211 to be open, we have to add a couple of rules for 11211/UDP and 11211/TCP in the security group attached to the instance.
Then, let's install memcached:
ubuntu@ip-10-234-177-74:~$ sudo apt-get install memcached
We also need to edit /etc/memcached.conf in order to set the '-l' parameter to the correct IP address (running ifconfig eth0 will confirm the right one to use). In my case, it is 10.234.177.74.
Then, we need to restart memcached:
Then, we need to restart memcached:
ubuntu@ip-10-234-177-74:~$ sudo service memcached restart
Now, let's go to the Node.js instance and check that we can access the memcached server:
ubuntu@ip-10-48-161-115:~$ echo stats|nc 10.234.177.74 11211
If you see a lot of stats like I do, you're good to go. If not, double-check the steps above (rules, config file, restart).
Now, let's install the memcached client for Node.js with npm, the Node.js package manager. There are several clients out there, mc looks pretty good and well-maintained :)
ubuntu@ip-10-48-161-115:~$ npm install mc
That's it. Now, let's write some code, yeah! Here's the idea:
- call the web server with a MongoDB ObjectId, e.g. http://ec2-54-216-3-139.eu-west-1.compute.amazonaws.com:8080/?id=51e3ce08915082db3df32bf7
- query the memcached server
- if we hit, job done!
- if we miss, query the MongoDB server and update the cache