public
Last active

Rails on Redis - is all about high performance

  • Download Gist
redis_usage.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts.all_cached # Retrive only at once by every 5 minutes
expires_in 5.minutes, :private => false, :public => true
end
end
 
# app/models/post.rb
Class Post
def self.all_cached
Rails.cache.fetch(:posts) do
self.all
end
end
end
 
# config/initializer/session_store.rb
ActionController::Base.session_store = Rack::Session::Redis
 
# config/environment.rb
require 'rack/cache'
require "redis-store"
Rails::Initializer.run do |config|
...
config.middleware.use Rack::Cache,
:verbose => true,
:metastore => "redis://localhost:6379/0",
:entitystore => "redis://localhost:6379/1"
 
if $0 == 'script/server'
# Check for redis-store
begin
# check if redis-store is running; if it is, use that instead of the default memory cache
Timeout.timeout(0.5) { TCPSocket.open("localhost", 6379) { } }
config.cache_store = :redis_store
$stderr.puts "\033[0;32mUsing redis-store on localhost:6379\033[0;34m"
rescue StandardError
$stderr.puts "\033[0;34mredis-store not running, you should run of \033[0;31m$ redis-server\033[0;29m"
raise
end
 
# Check for sphinx
begin
# check if memcached is running; if it is, use that instead of the default memory cache
Timeout.timeout(0.5) { TCPSocket.open("localhost", 9312) { } }
$stderr.puts "\033[0;32mUsing sphinx on localhost:9312\033[0;29m"
rescue StandardError
$stderr.puts "\033[0;34msphinx not running, you should run of \033[0;31m$ rake ts:start\033[0;29m"
raise
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.