Skip to content

Instantly share code, notes, and snippets.

@itapita
Forked from Yiftach/memcachedcloud-heroku.md
Last active December 25, 2015 11:59
Show Gist options
  • Save itapita/6973084 to your computer and use it in GitHub Desktop.
Save itapita/6973084 to your computer and use it in GitHub Desktop.

Memcached Cloud is a fully-managed service for running your Memcached in a reliable and fail-safe manner. Your dataset is constantly replicated, so if a node fails, an auto-switchover mechanism guarantees data is served without interruption. Memcached Cloud provides various data persistence options as well as remote backups for disaster recovery purposes. You can quickly and easily get your apps up and running with Memcached Cloud through its add-on for Heroku, just tell us how much memory you need and get started instantly with your first Memcached bucket.

A Memcached bucket is created in seconds and from that moment on, all operations are fully-automated. The service completely frees developers from dealing with nodes, clusters, server lists, scaling and failure recovery, while guaranteeing absolutely no data loss.

Getting Started

Begin by installing the add-on:

:::term
$ heroku addons:add memcachedcloud:25

A list of all plans available can be found here.

Once Memcached Cloud has been added, you will notice a three new config vars in your heroku environment containing the servers, username and password of your first Memcached Cloud bucket: MEMCACHEDCLOUD_SERVERS, MEMCACHEDCLOUD_USERNAME, MEMCACHEDCLOUD_PASSWORD .

Use the following heroku command to view them:

:::term
$ heroku config

Next, set up your app to start using the Memcached Cloud add-on. The following sections decribe how to that with several languages and frameworks that are supported by Heroku.

Using Memcached with Ruby

Dalli is a high performance, pure Ruby client for accessing Memcached servers that uses binary protocol.

Configuring Memcached on Rails

To use Dalli with Rails 3.x, update your gems with:

:::ruby
gem 'dalli'  

And then install the gem via Bundler:

:::ruby
bundle install

Lastly, add the following line in your config/environments/production.rb:

	:::ruby	
	config.cache_store = :dalli_store, ENV[MEMCACHEDCLOUD_SERVERS].split(','), { :username => ENV[MEMCACHEDCLOUD_USERNAME], :password => ENV[MEMCACHEDCLOUD_PASSWORD] }

Configuring Memcached on Sinatra

Add this code snippet to your configure block:

:::ruby
configure do
    . . .
	require 'dalli'
	
	$cache = Dalli::Client.new(ENV[MEMCACHEDCLOUD_SERVERS].split(','), :username => ENV[MEMCACHEDCLOUD_USERNAME], :password => ENV[MEMCACHEDCLOUD_PASSWORD])
    . . .
end

Using Memcached on Unicorn

No special setup is required when using Memcached Cloud with a Unicorn server. Users running Rails apps on Unicorn should follow the instructions in the Configuring Memcached from Rails section and users running Sinatra apps on Unicorn should follow the instructions in the Configuring Memcached on Sinatra section.

Testing from Ruby

:::ruby
$cache.set("foo", "bar")
# => true
$cache.get("foo")
# => "bar"

Using Memcached with Java

spymemcached is a simple, asynchronous, single-threaded Memcached client written in Java. You can download the latest build from: https://code.google.com/p/spymemcached/downloads/list. If you are using Maven, start by adding the following repository:

:::java
<repositories>
    <repository>
      <id>spy</id>
      <name>Spy Repository</name>
      <layout>default</layout>
      <url>http://files.couchbase.com/maven2/</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
</repositories>

Next, specify the actual artifact as follows:

:::java
<dependency>
  <groupId>spy</groupId>
  <artifactId>spymemcached</artifactId>
  <version>2.8.9</version>
  <scope>provided</scope>
</dependency>

Configure the connection to your Memcached Cloud service by using the VCAP_SERVICES environment variable as shown in the following code snippet:

:::java
try {			
	AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" },
		new PlainCallbackHandler(System.getenv("MEMCACHEDCLOUD_USERNAME"), System.getenv("MEMCACHEDCLOUD_PASSWORD")));
					
	MemcachedClient mc = new MemcachedClient(
	          new ConnectionFactoryBuilder()
		          .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
		          .setAuthDescriptor(ad).build(),
		  AddrUtil.getAddresses(System.getenv("MEMCACHEDCLOUD_SERVERS")));
		
} catch (IOException ex) {
	// the Memcached client could not be initialized. 
} 

Testing from Java

:::java
mc.set("foo", 0, "bar");
Object value = mc.get("foo");

Using Memcached with Python

bmemcached is a pure, thread safe, python module to access memcached via binary protocol.

Use pip to install it:

:::term
pip install python-binary-memcached

Configure the connection to your Memcached Cloud service using the MEMCACHEDCLOUDconfig vars and the following code snippet:

:::python
import os
import urlparse
import bmemcached
import json

mc = bmemcached.Client(os.environ.get('MEMCACHEDCLOUD_URL').split(','), os.environ.get('MEMCACHEDCLOUD_USERNAME'), os.environ.get('MEMCACHEDCLOUD_PASSWORD'))

Testing from Python

:::python
mc.set('foo', 'bar')
print client.get('foo')

Using Memcached with Django

Memcached Cloud can be used as a Django cache backend with django-bmemcached.

To do so, install django-bmemcached:

:::term
pip install django-bmemcached

Next, configure your CACHES in the settings.py file:

:::python
import os
import urlparse
import json

CACHES = {
	'default': {
		'BACKEND': 'django_bmemcached.memcached.BMemcached',
		'LOCATION': os.environ.get('MEMCACHEDCLOUD_URL').split(','),
		'OPTIONS': {
        			'username': os.environ.get('MEMCACHEDCLOUD_USERNAME'),
        			'password': os.environ.get('MEMCACHEDCLOUD_PASSWORD')
	        }
  	}
}

Testing from Django

:::python
from django.core.cache import cache
cache.set("foo", "bar")
print cache.get("foo")

Using Memcached with PHP

PHPMemcacheSASL is a simple PHP class with SASL support.

Include the class in your project and configure a connection to your Memcached Cloud service using the MEMCACHEDCLOUDconfig vars and the following code snippet:

<?php
include('MemcacheSASL.php');

$mc = new MemcacheSASL;
list($host, $port) = explode(':', $_ENV['MEMCACHEDCLOUD_SERVERS']);
$mc->addServer($host, $port);
$mc->setSaslAuthData($_ENV['MEMCACHEDCLOUD_USERNAME'], $_ENV['MEMCACHEDCLOUD_PASSWORD']);

Testing from PHP

$mc->add("foo", "bar");
echo $mc->get("foo");

Memcached Cloud Dashboard

Our dashboard displays all of the performance and usage metrics for your Memcached Cloud service on a single screen, as shown in the following screenshot:

Dashboard

To access your Memcached Cloud dashboard run:

:::term
heroku addons:open memcachedcloud

You can then find your dashboard under the MY BUCKETS menu.

Alternatively, open the Memcached Cloud add-on from your application's dashboard at http://heroku.com.

Adding Memcached Buckets to Your Plan

Memcached Cloud allows you to add multiple Memcached buckets to your plan, each running in a dedicated process and in a non-blocking manner (i.e. without interfering with your other buckets). You can create as many buckets as you need.

Your first Memcached bucket is provisioned automatically upon launching the Memcached Cloud add-on. Its servers and credentials are maintained in the MEMCACHEDCLOUDconfig vars. To add buckets, simply access your Memcached Cloud console and click the Add Bucket button in the MY BUCKETS > Manage page.

Your new Memcached bucket's server and credentials will be displayed in the Memcached Cloud console.

Migrating Between Plans

Plan migration is easy and instant. It requires no code change and has no effect on your existing datasets. You can use the 'heroku addons:upgrade' command to migrate to a new plan. For example, use the following to migrate to the 5GB plan:

:::term
$ heroku addons:upgrade memcachedcloud:5000

Removing the Add-on

The Memcached Cloud add-on can be removed using the following command:

:::term
$ heroku addons:remove memcachedcloud

Warning: removing the add-on will result in the deletion of all data managed by it - this step cannot be reversed!

Support

All Memcached Cloud support and runtime issues should be submitted via the Heroku Support channels. Any non-support related issues or product feedback is welcome via email at support@garantiadata.com.

Additional Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment