Implementing Resque/Redis on Rails 3

Hi coders! I have a new experience here with Rails 3 and I want to share it.

I have task to create a code running on background with Rails 3 and I found that I need to use Resque/Redis to make it happen. Okay, first you need to download Redis from its origin site at http://redis.io/download. Just follow the instruction there and you will be fine.

This is the main part of this post. But actually, I also followed some instruction from a blog. You can visit it directly to http://tommy.chheng.com/index.php/2010/10/how-to-run-background-processes-using-resqueredis-in-a-ruby-on-rails-app/. Honestly, it was a bliss. These are my steps on doing it:

  1. Add resque to Gemfile
    gem "resque"
  2. Run bundle install
  3. Create redis.yml in config folder :
    defaults: &defaults
      host: localhost
      port: 6379
    
    development:
      <<: *defaultstest:
      <<: *defaults 
    
    staging:
      <<: *defaults
    
    production:
      <<: *defaults

    You have to put “space” character for the configuration of every environment, or else you’ll get some errors.

  4. Create resque.rb in config/initializers :
    Dir[File.join(Rails.root, 'app', 'jobs', '*.rb')].each { |file| require file }
    config = YAML::load(File.open("#{Rails.root}/config/redis.yml"))[Rails.env]
    Resque.redis = Redis.new(:host => config['host'], :port => config['port'])
  5. Add resque.rake to lib/tasks :
    require 'resque/tasks'
    task "resque:setup" => :environment
  6. Start redis server by running ./src/redis-server from root folder of redis, that you’ve downloaded and configured
  7. Start resque by running COUNT=5 QUEUE=* rake resque:workers command
  8. Start resque web UI by running resque-web command
  9. Add your job code to resque. In my case, I added a secure copy task to another server. So what I did was creating a file called send_file.rb in models folder. The content of the file is :
    require 'net/scp'
    
    class SendFile
      @queue = :file_send #this class variable will be used as queue name in resque, so you can fill in different name
      def self.perform() # I didn't need any parameter, so I leave it blank
        Net::SCP.start('hostname.com', 'username', :password => 'password') do |scp|
          scp.upload!('local/directory', 'destination/path', {:recursive => true})
        end
      end
    end

    In my controller, I call that class by running this code
    Resque.enqueue(SendFile)

That’s it! I tried it and I succeeded. When your job is running, you can see it in resque web UI. So, why don’t you try it?
Enjoy!

Leave a comment