Friday, July 08, 2011

Sinatra: memcached as session store

A simple route for using memcached as session store. Assuming that Memcache server is running already.

require 'rubygems'
require 'sinatra'

use Rack::Session::Memcache, :memcache_server => 'localhost:11211', :expire_after => 3600, :namespace => "sinatra.chandankumar.com"

get "/" do
"value = " << session[:value].inspect
# Actual code to do something useful
end

# Route to set session variable
# for example to set session key :value invoke URL /set?value=ActualValue
get "/set" do
session[:value] = params[:value].inspect
# Code to do something
end

This would enable you to spawn multiple instances of (same) Sinatra app while sharing session store to achieve non sticky session. Helps scaling the front end.

To install Memcache service one could use Couchbase. Couchbase server is memcache compatible and it is comes with a nice admin interface to manage instances. More info about couchbase http://www.couchbase.com/couchbase-server/overview

0 comments:

Post a Comment