Tuesday, June 2, 2015

Using Memcached or Amazon Elasticache

Memcached is a central cache service that can hold string value pairs.

Memcached is run as a daemon or service on a machine. This machine becomes your Memcached server.

Memcached is accessed on port 11211

To play with Memcached, you will need to:
  1. Install a Memcached Server
  2. Use a Memcached client library to access the server

Install a Memcached Server as a Windows Service

http://downloads.northscale.com/memcached-win32-1.4.4-14.zip
http://downloads.northscale.com/memcached-win64-1.4.4-14.zip

c:\memcached\memcached.exe -d install
c:\memcached\memcached.exe -d start

Access the Memcached Server

1. Create a Windows Console Application

2. Install Nuget package
Install-Package EnyimMemcached

3. Add Memcached server's configuration to app.Config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="enyim.com">
      <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
    </sectionGroup>
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <enyim.com>
    <memcached protocol="Binary">
      <servers>
        <!-- make sure you use the same ordering of nodes in every configuration you have -->
        <add address="127.0.0.1" port="11211" />
      </servers>
    </memcached>
  </enyim.com>
  
</configuration>

4. Write code to access the Memcached Server.
static void Main(string[] args)
{
using(MemcachedClient client = new MemcachedClient())
{
var key = "LastProcessed";
var val = DateTime.Now.Ticks; ;

Console.WriteLine("Storing Key: {0}, Value: {1}",
key, val);
client.Store(StoreMode.Set, key, val);

Console.WriteLine("Retrieved Value: {0}, Key: {1}", 
client.Get<long>(key), key);
}
}

Amazon Elaticache

Elasticache is Amazon's implementation of Memcached in the cloud.

Provision an Amazon Elasticache Cluster via AWS Console. Configure the cluster to allow access to it by other EC2 instances in the VPN (Network Security Group).

For the referenced security group, allow inbound traffic for:
TCP, port 11211 from anywhere
SSH, port 22, from anywhere

You will not be able to access the cluster from your local machine (only from EC2 instances in the same VPN).

Change the Memcached configuration (address and port) in app.Config to access Elasticache.