SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Building Scalable Servers
With EventMachine and Rails


                               Dave Troy
                               Chief Executive Officer



      davetroy@shortmail.com

      @davetroy

      facebook.com/davetroy
EventMachine
EventMachine

    DRY
EventMachine

    DRY
   DRAG
EventMachine

          DRY
          DRAG
(Don’t Repeat Aman Gupta)
require ‘aman_gupta’
EventMachine
scalable non-blocking i/o in ruby
About Me
Aman Gupta
San Francisco, CA
Been maintaining EventMachine for 18
months (last 4 releases)
Ruby Hero 2009
amqp, REE patches, perftools.rb, gdb.rb,
memprof
github.com/tmm1
@tmm1
What is EventMachine?
Implementation of the Reactor pattern
  similar to Python’s Twisted   also node.js, libev
Ruby VM Support
  Ruby 1.8 (MRI)
  Ruby 1.9 (YARV)                         c++ reactor
  Rubinius
  JRuby                                   java reactor
  + simple Pure Ruby version
What is I/O?
 Generally Network I/O
   mysql query responses
   http responses
   memcache results

 Most web applications are I/O bound, not CPU bound
 Basic idea behind EM: Instead of waiting on a response
 from the network, use that time to process other
 requests
What can I use EM for?
Scaling I/O heavy applications
  handle 5-10k concurrent connections with a single
  ruby process
Any type of network I/O
  http requests
  sending emails
  custom tcp proxies
  data access
    redis
    couchdb
    mysql
    postgres
    casandra
    memcached
Simple TCP Server
TCPServer#accept     require 'socket'
                     server = TCPServer.new(2202)
to accept
                     while client = server.accept
connections from       msg = client.readline
new clients            client.write "You said: #{msg}"
                       client.close
TCPSocket#read*      end

blocks, so you can
                     require 'socket'
only handle one      server = TCPServer.new(2202)
client at a time     while true
                       Thread.new(server.accept){ |client|
Common Solution:         msg = client.readline
                         client.write "You said: #{msg}"
use a thread per         client.close
client                 }
                     end
require 'socket'
 inbound                         server = TCPServer.new(2202)
               list of clients   clients = []
buffer per                       buffers = {}


     client IO.select returns    while true
                                   sockets = [server] + clients
            readable/writable      readable, writable = IO.select(sockets)


                       sockets    readable.each do |sock|
                                    begin
                                      if sock == server
                                        clients << server.accept_nonblock
                                      else
                                        client, buf = sock, buffers[sock] ||= ''
    read in available data,
                                         buf << client.read_nonblock(1024)
process if full line received            if buf =~ /^.+?r?n/
                                           client.write "You said: #{buf}"



  Non-Blocking I/O
                                           client.close

                                           buffers.delete(client)
                                           clients.delete(client)
                                         end
    Alternative to                     end
                                     rescue Errno::EAGAIN, Errno::EWOULDBLOCK
    threads: simply don’t              # socket would block, try again later
                                     end
    block                          end
                                 end
EM does Non-Blocking I/O
handles low         module EchoServer
level sockets         def post_init
for you                 @buf = ''
                      end
inbound/              def receive_data(data)
                        @buf << data
outbound                if @buf =~ /^.+?r?n/
buffers for               send_data "You said: #{@buf}"
                          close_connection_after_writing
maximal                 end
throughput            end
                    end
efficient i/o with
writev/readv        require 'eventmachine'
                    EM.run do
                      EM.start_server '0.0.0.0', 2202, EchoServer
epoll & kqueue      end
support
So, what’s a Reactor?
       while reactor_running?
         expired_timers.each{ |timer| timer.process }
         new_network_io.each{ |io| io.process }
       end

reactor is simply a single threaded while loop, called
the “reactor loop”
your code “reacts” to incoming events
if your event handler takes too long, other events
cannot fire
lesson: never block the reactor        while reactor_running?
                                         while true
   no sleep(1)                           end
   no long loops (100_000.times)         # reactor is blocked!
   no blocking I/O (mysql queries)     end
   no polling (while !condition)
Writing Asynchronous Code
synchronous ruby code uses return values
            ret = operation()
            do_something_with(ret)

evented async code uses blocks instead
operation{ |ret| do_something_with(ret) }

different from how you usually use ruby blocks. the block
is stored and invoked later (it’s asynchronous)
puts(1)                      puts(1)
1.times{ puts(2) }           operation{ puts(3) }
puts(3)                      puts(2)
Receiving Email Using ActionMailer

  port 25        postfix
  (smtp)         (spool)

                        fork
                      process


                 Action                   pgsql
                 Mailer    ActiveRecord    (db)
Receiving Email Using LMTP

  port 25       postfix
  (smtp)        (spool)

                     port 8081
                      (lmtp)


                 EM                       pgsql
               (w/Rails)   ActiveRecord    (db)
Receiving Email — Scalably via LMTP


    postfix       postfix       message
    (spool)       (spool)       systems




     EM          EM           EM          EM
   (w/Rails)   (w/Rails)    (w/Rails)   (w/Rails)
LMTP Daemon



http://tools.ietf.org/html/rfc2033
POP3 Daemon



http://tools.ietf.org/html/rfc1939
IMAP Daemon



http://tools.ietf.org/html/rfc3501
EventMachine
Geo Firehose                       LISTEN
                                    8192
(one connection - Port 80)


                                      250, 500, 1000 Connections

 twittervision.com/
                                Apache
       stream

RewriteRule ^/stream(.*)$ http://127.0.0.1:8192%{REQUEST_URI} [P,QSA,L]
replyz.com
Does Anybody Know...?

mailstrom.co
mailstrom.410labs.com
Power Tools for Your Inbox

shortmail.com
Email, simplified.
Some Other Handy Stuff...

  • start_tls: secure any TCP connection
  • Timers: Periodic, Once, Scheduled
  • epoll, kqueue, threadpool_size
  • set_effective_user             (listen on protected ports)



  • teh docs: http://eventmachine.rubyforge.org/EventMachine.html
So, Some Stuff To Remember...

  • EventMachine: awesome for I/O, events
  • Code is Data, Data is Code
  • Often Working with State Machines
  • Don’t peg the CPU. No really, don’t.
  • TEBWTDI
  • Testing can be interesting
Dave Troy
                             Chief Executive Officer



    davetroy@shortmail.com

    @davetroy

    facebook.com/davetroy




 Tomorrow @ BohConf!
http://emrubyconf.com/

Weitere ähnliche Inhalte

Was ist angesagt?

Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصول
efazati
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
Tom Croucher
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Was ist angesagt? (20)

Solving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.comSolving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.com
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصول
 
Ruby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiRuby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay Shanghai
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
vert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in Javavert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in Java
 
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachine
 

Ähnlich wie Servers with Event Machine - David Troy - RailsConf 2011

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
secunderbadtirumalgi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
tobiascrawley
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by Aryo
Agate Studio
 

Ähnlich wie Servers with Event Machine - David Troy - RailsConf 2011 (20)

Python twisted
Python twistedPython twisted
Python twisted
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Pfm technical-inside
Pfm technical-insidePfm technical-inside
Pfm technical-inside
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Npc08
Npc08Npc08
Npc08
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by Aryo
 
03 sockets
03 sockets03 sockets
03 sockets
 
JUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxJUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBox
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
Rack
RackRack
Rack
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Servers with Event Machine - David Troy - RailsConf 2011

  • 1. Building Scalable Servers With EventMachine and Rails Dave Troy Chief Executive Officer davetroy@shortmail.com @davetroy facebook.com/davetroy
  • 2.
  • 5. EventMachine DRY DRAG
  • 6. EventMachine DRY DRAG (Don’t Repeat Aman Gupta)
  • 9. About Me Aman Gupta San Francisco, CA Been maintaining EventMachine for 18 months (last 4 releases) Ruby Hero 2009 amqp, REE patches, perftools.rb, gdb.rb, memprof github.com/tmm1 @tmm1
  • 10. What is EventMachine? Implementation of the Reactor pattern similar to Python’s Twisted also node.js, libev Ruby VM Support Ruby 1.8 (MRI) Ruby 1.9 (YARV) c++ reactor Rubinius JRuby java reactor + simple Pure Ruby version
  • 11. What is I/O? Generally Network I/O mysql query responses http responses memcache results Most web applications are I/O bound, not CPU bound Basic idea behind EM: Instead of waiting on a response from the network, use that time to process other requests
  • 12. What can I use EM for? Scaling I/O heavy applications handle 5-10k concurrent connections with a single ruby process Any type of network I/O http requests sending emails custom tcp proxies data access redis couchdb mysql postgres casandra memcached
  • 13. Simple TCP Server TCPServer#accept require 'socket' server = TCPServer.new(2202) to accept while client = server.accept connections from msg = client.readline new clients client.write "You said: #{msg}" client.close TCPSocket#read* end blocks, so you can require 'socket' only handle one server = TCPServer.new(2202) client at a time while true Thread.new(server.accept){ |client| Common Solution: msg = client.readline client.write "You said: #{msg}" use a thread per client.close client } end
  • 14. require 'socket' inbound server = TCPServer.new(2202) list of clients clients = [] buffer per buffers = {} client IO.select returns while true sockets = [server] + clients readable/writable readable, writable = IO.select(sockets) sockets readable.each do |sock| begin if sock == server clients << server.accept_nonblock else client, buf = sock, buffers[sock] ||= '' read in available data, buf << client.read_nonblock(1024) process if full line received if buf =~ /^.+?r?n/ client.write "You said: #{buf}" Non-Blocking I/O client.close buffers.delete(client) clients.delete(client) end Alternative to end rescue Errno::EAGAIN, Errno::EWOULDBLOCK threads: simply don’t # socket would block, try again later end block end end
  • 15. EM does Non-Blocking I/O handles low module EchoServer level sockets def post_init for you @buf = '' end inbound/ def receive_data(data) @buf << data outbound if @buf =~ /^.+?r?n/ buffers for send_data "You said: #{@buf}" close_connection_after_writing maximal end throughput end end efficient i/o with writev/readv require 'eventmachine' EM.run do EM.start_server '0.0.0.0', 2202, EchoServer epoll & kqueue end support
  • 16. So, what’s a Reactor? while reactor_running? expired_timers.each{ |timer| timer.process } new_network_io.each{ |io| io.process } end reactor is simply a single threaded while loop, called the “reactor loop” your code “reacts” to incoming events if your event handler takes too long, other events cannot fire lesson: never block the reactor while reactor_running? while true no sleep(1) end no long loops (100_000.times) # reactor is blocked! no blocking I/O (mysql queries) end no polling (while !condition)
  • 17. Writing Asynchronous Code synchronous ruby code uses return values ret = operation() do_something_with(ret) evented async code uses blocks instead operation{ |ret| do_something_with(ret) } different from how you usually use ruby blocks. the block is stored and invoked later (it’s asynchronous) puts(1) puts(1) 1.times{ puts(2) } operation{ puts(3) } puts(3) puts(2)
  • 18. Receiving Email Using ActionMailer port 25 postfix (smtp) (spool) fork process Action pgsql Mailer ActiveRecord (db)
  • 19. Receiving Email Using LMTP port 25 postfix (smtp) (spool) port 8081 (lmtp) EM pgsql (w/Rails) ActiveRecord (db)
  • 20. Receiving Email — Scalably via LMTP postfix postfix message (spool) (spool) systems EM EM EM EM (w/Rails) (w/Rails) (w/Rails) (w/Rails)
  • 24. EventMachine Geo Firehose LISTEN 8192 (one connection - Port 80) 250, 500, 1000 Connections twittervision.com/ Apache stream RewriteRule ^/stream(.*)$ http://127.0.0.1:8192%{REQUEST_URI} [P,QSA,L]
  • 25. replyz.com Does Anybody Know...? mailstrom.co mailstrom.410labs.com Power Tools for Your Inbox shortmail.com Email, simplified.
  • 26. Some Other Handy Stuff... • start_tls: secure any TCP connection • Timers: Periodic, Once, Scheduled • epoll, kqueue, threadpool_size • set_effective_user (listen on protected ports) • teh docs: http://eventmachine.rubyforge.org/EventMachine.html
  • 27. So, Some Stuff To Remember... • EventMachine: awesome for I/O, events • Code is Data, Data is Code • Often Working with State Machines • Don’t peg the CPU. No really, don’t. • TEBWTDI • Testing can be interesting
  • 28. Dave Troy Chief Executive Officer davetroy@shortmail.com @davetroy facebook.com/davetroy Tomorrow @ BohConf! http://emrubyconf.com/

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n