Config Rails 3 with dalli(memcahed)

Config Rails 3 with dalli(memcahed)

To install dalli in your Rails 3 app, simply add the following to your Gemfile and run bundle install.

# Gemfile
gem "dalli", "~> 2.6.4",   :platforms => :ruby

To setup Rails to use the Dalli client for production, add the following to config/environments/production.rb:

# config/environments/production.rb
# Enable dalli (memcached) caching
config.cache_store = :dalli_store
config.action_controller.perform_caching = true

If you want to cache in any of your other environments, just add the same snippet to your environment of choice.

Dalli can also be used as rack middleware for session caching. To setup session caching with dalli, edit your config/initializers/session_store.rb to contain the following:

# config/initializers/session_store.rb
require 'action_dispatch/middleware/session/dalli_store'

Rails.application.config.session_store :dalli_store,
  :memcache_server => '127.0.0.1:11211',
  :namespace => 'sessions',
  :key => '_yourappname_session',
  :expire_after => 30.minutes

Now, whenever you use Rails’ built in caching or session storage, dalli will automatically interface with memcached.

# config/dalli.yml
# https://github.com/mperham/dalli#configuration
# parse the dalli.yml
# dalli_config = YAML.load_file(Rails.root.join('config/dalli.yml'))[Rails.env]
# memcached_hosts = dalli_config['servers']
# pass the servers to dalli setup
# config.cache_store = :dalli_store, *memcached_hosts, dalli_config["options"]
defaults: &defaults
  expires_in: 7 * 24 * 3600
  compress: true

development:
  options:
    <<: *defaults
    namespace: gxservice_development
  servers: 127.0.0.1:11211

test:
  options:
    <<: *defaults
    namespace: gxservice_test
  servers: 127.0.0.1:11211


staging:
  options:
    <<: *defaults
    namespace: gxservice_staging
  servers:
    - 127.0.0.1:11211

production:
  options:
    <<: *defaults
    namespace: gxservice_production
  servers:
    - cache01.mysite.org:11211
    - cache02.mysite.org:11211
    - cache03.mysite.org:11211

setup Rails use dalli with yaml file

# config/environments/production.rb
if defined?(Dalli)
  dalli_config = YAML.load_file(Rails.root.join('config/dalli.yml'))[Rails.env]
  memcached_hosts = dalli_config['servers']
  config.cache_store = :dalli_store, *memcached_hosts, dalli_config["options"]
end