tommy
tommy

Reputation: 11

Writing proper Eventmachine code for Ruby?

I'm trying to understand Eventmachine.

I have a server:

module EchoServer
  def post_init
    puts "connected"
  end

  def receive_data(data)
   puts "Receiving data: #{data}"

   GenericModel.create!(:text => data)
  end

  def unbind
    puts "disconnected"
  end
end

EM.run do
  EM.start_server '127.0.0.1', 1234, EchoServer
end

And a client:

class Echo < EventMachine::Connection
  def post_init
    send_data 'Hello'
  end

  def receive_data(data)
    p data
    close_connection
  end

  def connection_completed
    puts "connection completed"
  end

  def unbind
    EventMachine.stop
  end
end

EventMachine.run {
  EventMachine.connect '127.0.0.1', 1234, Echo
}

Here's what I'm wondering: Database access tends to be slower so how should I rewrite that GenericModel.create! line of code to avoid slowing down my reactor loop?

Upvotes: 1

Views: 693

Answers (2)

Roman
Roman

Reputation: 13058

Either you use a connection adapter which is non-blocking and em-based (like em-mysql), or do that task in another thread.

Upvotes: 1

seph
seph

Reputation: 6076

Have a look at this SO question. It's Rails based but the demo app is a very clear explanation of the benefits of hitting a database using Eventmachine.

Upvotes: 0

Related Questions