IronCast 4: How to connect to your database from IronWorker – IronWorker 101 Part 4/4

In a series of four IronCasts, we will provide a high-level introduction to using IronWorker, an easy-to-use scalable task queue. In this series, we will be using an example application which is written in Rails. However, the same concept applies to every language or framework.

In this video, we will show you how to connect to your database from IronWorker.

One of the frequent questions that we get asked at Iron.io is how to get your workers to write back to the database, especially in development.

Step 1 – Creating a cloud hosted development database:
IronWorker on EC2 needs an open port to your database, and your database credentials in order to connect to your database. So no matter what language or framework, those are the two small requirements in order for your workers to connect to your DB. So the easiest way to do this is in development is by using a cloud hosted development database. It is generally harder to open a port (that a worker on EC2 can access) to the database on your local machine.

Using heroku as an example, you can create a free heroku development database:

heroku addons:add heroku-postgresql:dev

Step 2 – Passing your database credentials into the payload:

def create
  @snippet = Snippet.new(snippet_params)
  if @snippet.save
    @client ||= IronWorkerNG::Client.new(:token => ENV["TOKEN"], :project_id => ENV["PROJECT_ID"])
    @client.tasks.create("pygments",
                         "database" => Rails.configuration.database_configuration[Rails.env],
                         "request" => {"lang" => @snippet.language,
                                       "code" => @snippet.plain_code},
                         "snippet_id" => @snippet.id)
    redirect_to @snippet
  else
    render :new
  end
end

Step 3 – Connecting to your database using the credentials:

def setup_database
  puts "Database connection details:#{params['database'].inspect}"
  return unless params['database']
  # estabilsh database connection
  ActiveRecord::Base.establish_connection(params['database'])
end
And that’s it! Three simple steps and you have connected to your cloud hosted database from your IronWorker. Click here to take a more detailed look at the repository.
 
This is the end of the first series of IronCast. We have gone through various basic aspects of using an IronWorker such as writing worker files, prototyping locally and connecting to the database. Please don’t hesitate to contact us if you have any suggestions to any topics that you would like to us to cover in future IronCasts.


Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.