When Java meets Ruby     Creative Commons BY-SA 3.0Thursday, December 8, 11
@abstractj          Java há 12 anos, Ruby n00b          TorqueBox Contributor          DynJS Contributor          Caelum &...
DISCLAIMERThursday, December 8, 11
Java                   927 JSRS!               nooooooooooooooo!Thursday, December 8, 11
import java.util.Calendar;                           public class Beer {                             private Long beerId; ...
ENTERPRISEThursday, December 8, 11
JAXR                         Java-FX     JAXP                           JSTL                         StAX JME             ...
Thursday, December 8, 11
Mas escala né?!Thursday, December 8, 11
Scala            Clojure                                   Jython                                    JVM                  ...
Ruby     Mais expressiva que Java      class Beer        attr_accessor :beer_id, :description, :created_at      endThursda...
DRY       “It is tempting, if the only tool you have is a       hammer, to treat everything as if it were a       nail.” -...
JRuby                           Java + RubyThursday, December 8, 11
JRuby    require java    pdf = com.itextpdf.text.Document.new    para = com.itextpdf.text.Paragraph.new Brought to you by ...
“You get true multithreading that                can use all your computer’s cores                from one process, plus a...
Server SideThursday, December 8, 11
Ruby App                             Sinatra      Rails                                   Rack                            ...
Ruby App                             Sinatra      Rails                                   Rack                            ...
Ruby App                                      Sinatra      Rails                                            Rack          ...
Ruby App                                      Sinatra      Rails                                            Rack          ...
JBoss     TomcatThursday, December 8, 11
JBoss     HornetQThursday, December 8, 11
JBoss     QuartzThursday, December 8, 11
JBoss     ClusteringThursday, December 8, 11
AS 7     Redução do footprint de memória     Class loader modular     Queda no tempo de startup     EE6 compliantThursday,...
TorqueBox                           “The power of JBoss with the                             expressiveness of Ruby”      ...
TorqueBoxThursday, December 8, 11
Instalação                            TorqueBox do zeroThursday, December 8, 11
Pré-requisitos      ➜ java -version      java version "1.6.0_07"      Java(TM) SE Runtime Environment (build 1.6.0_07-b06-...
➜ jruby -S gem install torquebox torquebox-capistrano-supportThursday, December 8, 11
➜ wget http://repository-torquebox.forge.cloudbees.com/     release/org/torquebox/torquebox-dist/2.0.0.beta1/torquebox-   ...
Rails     rails new beer -m $TORQUEBOX_HOME/share/rails/template.rbThursday, December 8, 11
Estrutura     Diretórios do TorqueBoxThursday, December 8, 11
Rake tasks      rake torquebox:deploy      rake torquebox:undeploy      rake torquebox:runThursday, December 8, 11
Deployment                           Make knobs, not WAR!Thursday, December 8, 11
beer-knob.yml     application:      root: /Users/Bruno/javaonebrasil/beer      environment: developmentThursday, December ...
Thursday, December 8, 11
AplicaçãoThursday, December 8, 11
source "http://torquebox.org/2x/builds/584/gem-                           repo"                           source http://ru...
Web                           Rack, Sinatra, RailsThursday, December 8, 11
Caching     class BeersController < ApplicationController        caches_action :most_popular, :expires_in => 30.seconds   ...
Thursday, December 8, 11
Clustering     ➜ torquebox run --clusteredThursday, December 8, 11
Internals     class TorqueBoxCommand < Thor      TASK_ORDER = %w(deploy undeploy start cli env help)      map "run" => "st...
Cache distribuído!Thursday, December 8, 11
mod_cluster                           httpd-based load balancerThursday, December 8, 11
Infinispan                             CachingThursday, December 8, 11
Invalidation                            Cache     Cache                           Server1   Server2Thursday, December 8, 11
Invalidation                                     Notificação                            Cache                  Cache       ...
../config/application.rb     module Beer      class Application < Rails::Application       config.cache_store = :torque_box_...
Replicated                                             Cache                                            Server2           ...
../config/application.rb     module Beer      class Application < Rails::Application       config.cache_store = :torque_box_...
Scheduling                           Agendamento de JobsThursday, December 8, 11
Internals      public class RubyJobProxy implements Job {          @Override          public void execute(JobExecutionCont...
Internals      public class RubyJobProxy implements Job {          @Override          public void execute(JobExecutionCont...
../app/jobs     class JobDemo         def initialize          #Codigo de inicializacao         end      def run       # O ...
../config/torquebox.yml     jobs:      sync_agenda:       job: JobDemo       cron: 0 0 12 * * ?     endThursday, December 8...
Mensageria     Java Messaging Service + HornetQThursday, December 8, 11
O Ministério da Saúde adverte:                      NOSQL COMO MENSAGERIA                                PODE             ...
Greenfield                                 REST + NoSQL                                 Request/Responsext                 ...
Real World                                  Nobody Cares!                                   Request/Responsext            ...
../config/torquebox.yml     /topics/beerTopic     /queues/queueBeer:Thursday, December 8, 11
Tasks     class EmailerTask < TorqueBox::Messaging::Task      def send_welcome(payload)       to = "#{payload[:name]} <#{p...
Tasks     class UserController < ApplicationController      def register       user = User.new(params[:user])       Emaile...
Processors     include TorqueBox::Messaging     class PrintHandler < MessageProcessor       def on_message(body)         p...
Queues     include TorqueBox     req = Messaging::Queue.new /queues/questions     res = Messaging::Queue.new /queues/answe...
FutureThursday, December 8, 11
Future     class EmailerTask      def send_welcome(payload)       to = "#{payload[:name]} <#{payload[:address]}>"       # ...
Future     class EmailerTask         include TorqueBox::Messaging::Backgroundable         always_background :send_welcome ...
Future       future = @emailTask.send_welcome(:send_welcome)       future.started?       future.complete?       future.err...
ServicesThursday, December 8, 11
Services     class BeerService      def initialize       @queue = Messaging::Queue.new(“beer”)      end      def start    ...
Singleton Services                                     Clustered                           Server1                  Server...
Singleton Services                                     Clustered                           Server1                  Server...
Services     ➜ torquebox run --clustered     ../config/torquebox.yml     services:      BeerService:       singleton: true ...
CDI                           Injeção de dependênciasThursday, December 8, 11
Pra quê?Thursday, December 8, 11
Java     package br.com.javaonebrasil;     public class Beer {       //gets e sets       public void say(String message) {...
Ruby     class BeerController < ApplicationController          include TorqueBox::Injectors          def create           ...
JNDI   class MyService    include TorqueBox::Injectors    def initialize opts={}     @factory = inject("java:comp/env/jdbc...
Destinations      class MyService       include TorqueBox::Injectors       def initialize opts={}        @inbound = inject...
Transactions          Queue               Database   Infinispan                   Rails Application       Topic        XA D...
XA (2PC)      HornetQ ✔      Infinispan ✔       TorqueBox + ActiveRecord ✔Thursday, December 8, 11
Outras features     Autenticação + WebsocketsThursday, December 8, 11
BackStageThursday, December 8, 11
Stomp Box                           TorqueBox deployment supportThursday, December 8, 11
Thursday, December 8, 11
What’s next?Thursday, December 8, 11
Polyglot     Immutant                           Queue   Queue   TorqueBoxThursday, December 8, 11
Getting started                       Installing TorqueBox 2.0                      http://vimeo.com/33299335Thursday, Dec...
Comunidade           irc.freenode.net #torquebox           http://torquebox.org           http://github.com/torquebox     ...
Obrigado!                                            @abstractj                                   http://github.com/abstra...
Upcoming SlideShare
Loading in …5
×

TorqueBox - When Java meets Ruby

2,203 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,203
On SlideShare
0
From Embeds
0
Number of Embeds
28
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

TorqueBox - When Java meets Ruby

  1. 1. When Java meets Ruby Creative Commons BY-SA 3.0Thursday, December 8, 11
  2. 2. @abstractj Java há 12 anos, Ruby n00b TorqueBox Contributor DynJS Contributor Caelum & ConcreteSThursday, December 8, 11
  3. 3. DISCLAIMERThursday, December 8, 11
  4. 4. Java 927 JSRS! nooooooooooooooo!Thursday, December 8, 11
  5. 5. import java.util.Calendar; public class Beer { private Long beerId; private String description; private Calendar createdAt; public Long getBeerId() { return beerId; } public void setBeerId(Long beerId) {Expressiva? } this.beerId = beerId; public String getDescription() { return description; } public void setDescription(String description) this.description = description; } public Calendar getCreatedAt() { return createdAt; } public void setCreatedAt(Calendar createdAt) this.createdAt = createdAt; }Thursday, December 8, 11 }
  6. 6. ENTERPRISEThursday, December 8, 11
  7. 7. JAXR Java-FX JAXP JSTL StAX JME JDOM JVM JAX-RPC EJB AWT JMX Swing EAR Struts JAAS JCP JavaBean NPE Spring JAX-WS ENTERPRISE RMI JSE JNI JNDI NIO SOA JSP JSF JAXB WAR JDO JAX-RS JPQL JAF POJO EJBQL JRE JEEThursday, December 8, 11
  8. 8. Thursday, December 8, 11
  9. 9. Mas escala né?!Thursday, December 8, 11
  10. 10. Scala Clojure Jython JVM DynJS Rhino GroovyThursday, December 8, 11
  11. 11. Ruby Mais expressiva que Java class Beer attr_accessor :beer_id, :description, :created_at endThursday, December 8, 11
  12. 12. DRY “It is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.” - Abraham MaslowThursday, December 8, 11
  13. 13. JRuby Java + RubyThursday, December 8, 11
  14. 14. JRuby require java pdf = com.itextpdf.text.Document.new para = com.itextpdf.text.Paragraph.new Brought to you by JRuby file = java.io.FileOutputStream.new pdf_demo.pdf com.itextpdf.text.pdf.PdfWriter.get_instance pdf, file pdf.open pdf.add para pdf.closeThursday, December 8, 11
  15. 15. “You get true multithreading that can use all your computer’s cores from one process, plus a virtual machine that’s been tuned for a decade and a half.” Using JRuby - Bringing Ruby to JavaThursday, December 8, 11
  16. 16. Server SideThursday, December 8, 11
  17. 17. Ruby App Sinatra Rails Rack Passenger/Thin Apache/NginxThursday, December 8, 11
  18. 18. Ruby App Sinatra Rails Rack Passenger/Thin Jobs Apache/Nginx crondThursday, December 8, 11
  19. 19. Ruby App Sinatra Rails Rack Tasks Passenger/Thin Jobs Resque/ DelayedJob Apache/Nginx crondThursday, December 8, 11
  20. 20. Ruby App Sinatra Rails Rack Tasks Passenger/Thin Jobs Resque/ DelayedJob Apache/Nginx crond Daemons god/monitThursday, December 8, 11
  21. 21. JBoss TomcatThursday, December 8, 11
  22. 22. JBoss HornetQThursday, December 8, 11
  23. 23. JBoss QuartzThursday, December 8, 11
  24. 24. JBoss ClusteringThursday, December 8, 11
  25. 25. AS 7 Redução do footprint de memória Class loader modular Queda no tempo de startup EE6 compliantThursday, December 8, 11
  26. 26. TorqueBox “The power of JBoss with the expressiveness of Ruby” Jim Crossley - MagicRuby ConferenceThursday, December 8, 11
  27. 27. TorqueBoxThursday, December 8, 11
  28. 28. Instalação TorqueBox do zeroThursday, December 8, 11
  29. 29. Pré-requisitos ➜ java -version java version "1.6.0_07" Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode)Thursday, December 8, 11
  30. 30. ➜ jruby -S gem install torquebox torquebox-capistrano-supportThursday, December 8, 11
  31. 31. ➜ wget http://repository-torquebox.forge.cloudbees.com/ release/org/torquebox/torquebox-dist/2.0.0.beta1/torquebox- dist-2.0.0.beta1-bin.zip ➜ unzip torquebox-dist-2.0.0.beta1-bin.zip ➜ export TORQUEBOX_HOME=$PWD/torquebox- dist-2.0.0.beta1 ➜ export JBOSS_HOME=$TORQUEBOX_HOME/jboss ➜ export JRUBY_HOME=$TORQUEBOX_HOME/jruby ➜ export PATH=$JRUBY_HOME/bin:$PATHThursday, December 8, 11
  32. 32. Rails rails new beer -m $TORQUEBOX_HOME/share/rails/template.rbThursday, December 8, 11
  33. 33. Estrutura Diretórios do TorqueBoxThursday, December 8, 11
  34. 34. Rake tasks rake torquebox:deploy rake torquebox:undeploy rake torquebox:runThursday, December 8, 11
  35. 35. Deployment Make knobs, not WAR!Thursday, December 8, 11
  36. 36. beer-knob.yml application: root: /Users/Bruno/javaonebrasil/beer environment: developmentThursday, December 8, 11
  37. 37. Thursday, December 8, 11
  38. 38. AplicaçãoThursday, December 8, 11
  39. 39. source "http://torquebox.org/2x/builds/584/gem- repo" source http://rubygems.org gem rails, 3.1.1 Gemfile gem activerecord-jdbcsqlite3-adapter gem jruby-openssl gem json gem jquery-rails gem "torquebox-rake-support", "2.x.incremental. 584" gem "torquebox", "2.x.incremental.584"Thursday, December 8, 11
  40. 40. Web Rack, Sinatra, RailsThursday, December 8, 11
  41. 41. Caching class BeersController < ApplicationController caches_action :most_popular, :expires_in => 30.seconds def most_popular @popular_beers = Beer.most_popular(:limit => 25) end endThursday, December 8, 11
  42. 42. Thursday, December 8, 11
  43. 43. Clustering ➜ torquebox run --clusteredThursday, December 8, 11
  44. 44. Internals class TorqueBoxCommand < Thor TASK_ORDER = %w(deploy undeploy start cli env help) map "run" => "start" desc "run", "Run TorqueBox" method_option :clustered, :type => :boolean, :desc => "Run TorqueBox in clustered mode" def start setup_environment TorqueBox::DeployUtils.run_server(:clustered => options.clustered, :max_threads => options[max-threads], :bind_address => options[bind-address]) end endThursday, December 8, 11
  45. 45. Cache distribuído!Thursday, December 8, 11
  46. 46. mod_cluster httpd-based load balancerThursday, December 8, 11
  47. 47. Infinispan CachingThursday, December 8, 11
  48. 48. Invalidation Cache Cache Server1 Server2Thursday, December 8, 11
  49. 49. Invalidation Notificação Cache Cache Server1 Server2 NEW Cache DesatualizadoThursday, December 8, 11
  50. 50. ../config/application.rb module Beer class Application < Rails::Application config.cache_store = :torque_box_store end endThursday, December 8, 11
  51. 51. Replicated Cache Server2 Cache Server1 Sync Cache Sync Server2 Cache Server2Thursday, December 8, 11
  52. 52. ../config/application.rb module Beer class Application < Rails::Application config.cache_store = :torque_box_store, {:mode => replicated, :sync =>false} end endThursday, December 8, 11
  53. 53. Scheduling Agendamento de JobsThursday, December 8, 11
  54. 54. Internals public class RubyJobProxy implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { Ruby ruby = null; try { ruby = this.runtimePool.borrowRuntime( resolver.getComponentName() ); JobComponent job = (JobComponent)resolver.resolve( ruby ); job.run(); } catch (Exception e) { throw new JobExecutionException( e ); } finally { if (ruby != null) { this.runtimePool.returnRuntime( ruby ); } } }Thursday, December 8, 11
  55. 55. Internals public class RubyJobProxy implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { Ruby ruby = null; try { ruby = this.runtimePool.borrowRuntime( resolver.getComponentName() ); JobComponent job = (JobComponent)resolver.resolve( ruby ); job.run(); } catch (Exception e) { throw new JobExecutionException( e ); } finally { if (ruby != null) { this.runtimePool.returnRuntime( ruby ); } } }Thursday, December 8, 11
  56. 56. ../app/jobs class JobDemo def initialize #Codigo de inicializacao end def run # O que você quer executar end endThursday, December 8, 11
  57. 57. ../config/torquebox.yml jobs: sync_agenda: job: JobDemo cron: 0 0 12 * * ? endThursday, December 8, 11
  58. 58. Mensageria Java Messaging Service + HornetQThursday, December 8, 11
  59. 59. O Ministério da Saúde adverte: NOSQL COMO MENSAGERIA PODE TRAZER DANOS A SUA SAÚDE E A DE SEUS FAMILIARESThursday, December 8, 11
  60. 60. Greenfield REST + NoSQL Request/Responsext NoSQL RAILS APP pub/sub SINATRA APPThursday, December 8, 11
  61. 61. Real World Nobody Cares! Request/Responsext NoSQL RAILS APP pub/sub MAINFRAMEThursday, December 8, 11
  62. 62. ../config/torquebox.yml /topics/beerTopic /queues/queueBeer:Thursday, December 8, 11
  63. 63. Tasks class EmailerTask < TorqueBox::Messaging::Task def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # send welcome email to the user end endThursday, December 8, 11
  64. 64. Tasks class UserController < ApplicationController def register user = User.new(params[:user]) EmailerTask.async(:send_welcome, :address => user.email, :name => user.name) end endThursday, December 8, 11
  65. 65. Processors include TorqueBox::Messaging class PrintHandler < MessageProcessor   def on_message(body)     puts "Processing #{body} of #{message}"   end   def configure(opts)     @color = opts[color]   end endThursday, December 8, 11
  66. 66. Queues include TorqueBox req = Messaging::Queue.new /queues/questions res = Messaging::Queue.new /queues/answers   Thread.new do   req.publish "What time is it?"   puts res.receive( :timeout => 1000 ) endThursday, December 8, 11
  67. 67. FutureThursday, December 8, 11
  68. 68. Future class EmailerTask def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # long running task end endThursday, December 8, 11
  69. 69. Future class EmailerTask include TorqueBox::Messaging::Backgroundable always_background :send_welcome def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # long running task end endThursday, December 8, 11
  70. 70. Future future = @emailTask.send_welcome(:send_welcome) future.started? future.complete? future.error? future.result future.result(10000)Thursday, December 8, 11
  71. 71. ServicesThursday, December 8, 11
  72. 72. Services class BeerService def initialize @queue = Messaging::Queue.new(“beer”) end def start @queue.publish “Testing” end def stop # O que fazer quando o serviço receber um stop end endThursday, December 8, 11
  73. 73. Singleton Services Clustered Server1 Server2 BeerService BeerServiceThursday, December 8, 11
  74. 74. Singleton Services Clustered Server1 Server2 BeerService BeerServiceThursday, December 8, 11
  75. 75. Services ➜ torquebox run --clustered ../config/torquebox.yml services: BeerService: singleton: true endThursday, December 8, 11
  76. 76. CDI Injeção de dependênciasThursday, December 8, 11
  77. 77. Pra quê?Thursday, December 8, 11
  78. 78. Java package br.com.javaonebrasil; public class Beer { //gets e sets public void say(String message) { // Execução do método } } Deploy do jar na aplicação app/ models/ views/ controllers/ lib/beer.jarThursday, December 8, 11
  79. 79. Ruby class BeerController < ApplicationController include TorqueBox::Injectors def create beer = inject(br.com.javaonebrasil.Beer ) beer.say “Ruby is for Java” end endThursday, December 8, 11
  80. 80. JNDI class MyService include TorqueBox::Injectors def initialize opts={} @factory = inject("java:comp/env/jdbc/myDB") end endThursday, December 8, 11
  81. 81. Destinations class MyService include TorqueBox::Injectors def initialize opts={} @inbound = inject("/topic/beerpub") @outbound = inject("/queue/beer") end endThursday, December 8, 11
  82. 82. Transactions Queue Database Infinispan Rails Application Topic XA Distributed, multi resource transactionThursday, December 8, 11
  83. 83. XA (2PC) HornetQ ✔ Infinispan ✔ TorqueBox + ActiveRecord ✔Thursday, December 8, 11
  84. 84. Outras features Autenticação + WebsocketsThursday, December 8, 11
  85. 85. BackStageThursday, December 8, 11
  86. 86. Stomp Box TorqueBox deployment supportThursday, December 8, 11
  87. 87. Thursday, December 8, 11
  88. 88. What’s next?Thursday, December 8, 11
  89. 89. Polyglot Immutant Queue Queue TorqueBoxThursday, December 8, 11
  90. 90. Getting started Installing TorqueBox 2.0 http://vimeo.com/33299335Thursday, December 8, 11
  91. 91. Comunidade irc.freenode.net #torquebox http://torquebox.org http://github.com/torquebox twitter: @torqueboxThursday, December 8, 11
  92. 92. Obrigado! @abstractj http://github.com/abstractj Creative Commons BY-SA 3.0Thursday, December 8, 11

×