SlideShare uma empresa Scribd logo
1 de 85
Baixar para ler offline
Além da fronteira entre Java & Ruby

        Creative  Commons  BY-­SA  3.0




Friday, November 4, 2011
@abstractj
          Java há 12 anos, Ruby n00b
          TorqueBox Contributor
          DynJS Contributor
          Caelum & ConcreteS


Friday, November 4, 2011
DISCLAIMER



Friday, November 4, 2011
Java

                   927 JSRS!
               nooooooooooooooo!

Friday, November 4, 2011
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;
                             }
Friday, November 4, 2011
                           }
ENTERPRISE



Friday, November 4, 2011
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
     JEE

Friday, November 4, 2011
Friday, November 4, 2011
Mas escala né?!



Friday, November 4, 2011
Scala            Clojure
                                   Jython


                                    JVM
                                    DynJS
                   Rhino                    Groovy




Friday, November 4, 2011
Ruby
     Mais expressiva que Java

      class Beer
        attr_accessor :beer_id, :description, :created_at
      end




Friday, November 4, 2011
DRY


Friday, November 4, 2011
JRuby
                           Java + Ruby




Friday, November 4, 2011
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.close




Friday, November 4, 2011
“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 Java




Friday, November 4, 2011
Server Side



Friday, November 4, 2011
Ruby App
                             Sinatra      Rails
                                   Rack
                             Passenger/Thin


                             Apache/Nginx




Friday, November 4, 2011
Ruby App
                             Sinatra      Rails
                                   Rack
                             Passenger/Thin       Jobs


                             Apache/Nginx         crond




Friday, November 4, 2011
Ruby App
                                      Sinatra      Rails
                                            Rack
                           Tasks      Passenger/Thin       Jobs
                        Resque/
                       DelayedJob     Apache/Nginx         crond




Friday, November 4, 2011
Ruby App
                                      Sinatra      Rails
                                            Rack
                           Tasks      Passenger/Thin       Jobs
                        Resque/
                       DelayedJob     Apache/Nginx         crond


                                         Daemons


                                       god/monit



Friday, November 4, 2011
JBoss
     Tomcat




Friday, November 4, 2011
JBoss
     HornetQ




Friday, November 4, 2011
JBoss
     Quartz




Friday, November 4, 2011
JBoss
     Clustering




Friday, November 4, 2011
TorqueBox
                           “The power of JBoss with the
                             expressiveness of Ruby”
                                       Jim Crossley - MagicRuby Conference




Friday, November 4, 2011
TorqueBox




Friday, November 4, 2011
Instalação
                            TorqueBox do zero




Friday, November 4, 2011
➜ jruby -S gem install torquebox torquebox-capistrano-support




Friday, November 4, 2011
➜ wget http://torquebox.org/builds/LATEST/torquebox-dist-
     bin.zip
     ➜ unzip torquebox-dist-bin.zip

     ➜ export TORQUEBOX_HOME=$PWD/torquebox-2.x
     ➜ export JBOSS_HOME=$TORQUEBOX_HOME/jboss
     ➜ export JRUBY_HOME=$TORQUEBOX_HOME/jruby

     ➜ export PATH=$JRUBY_HOME/bin:$PATH




Friday, November 4, 2011
Rails
     rails new beer -m $TORQUEBOX_HOME/share/rails/template.rb




Friday, November 4, 2011
Estrutura
     Diretórios do TorqueBox




Friday, November 4, 2011
Rake tasks
      rake torquebox:deploy
      rake torquebox:undeploy
      rake torquebox:run




Friday, November 4, 2011
Deployment
                           Make knobs, not WAR!




Friday, November 4, 2011
beer-knob.yml
     application:
      root: /Users/Bruno/rubyconfbr/beer
      environment: development




Friday, November 4, 2011
Friday, November 4, 2011
Aplicação



Friday, November 4, 2011
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"




Friday, November 4, 2011
Web
                           Rack, Sinatra, Rails




Friday, November 4, 2011
Caching
     class BeersController < ApplicationController

        caches_action :most_popular, :expires_in => 30.seconds

        def most_popular
         @popular_beers = Beer.most_popular(:limit => 25)
        end

     end




Friday, November 4, 2011
Friday, November 4, 2011
Clustering
     ➜ torquebox run --clustered




Friday, November 4, 2011
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
     end




Friday, November 4, 2011
Cache distribuído!



Friday, November 4, 2011
mod_cluster



Friday, November 4, 2011
Infinispan
                             Caching




Friday, November 4, 2011
Invalidation
                            Cache     Cache
                           Server1   Server2




Friday, November 4, 2011
Invalidation
                                     Notificação
                            Cache                  Cache
                           Server1                Server2


                           NEW                   Cache
                                              Desatualizado




Friday, November 4, 2011
../config/application.rb
     module Beer

      class Application < Rails::Application
       config.cache_store = :torque_box_store
      end
     end




Friday, November 4, 2011
Replicated
                                             Cache
                                            Server2
                            Cache
                           Server1   Sync
                                             Cache
                                     Sync   Server2



                                             Cache
                                            Server2




Friday, November 4, 2011
../config/application.rb
     module Beer

      class Application < Rails::Application
       config.cache_store = :torque_box_store, {:mode =>
     replicated, :sync =>false}
      end
     end




Friday, November 4, 2011
Scheduling
                           Agendamento de Jobs




Friday, November 4, 2011
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 );
                watchDog(context);
                job.run();
             } catch (Exception e) {
                throw new JobExecutionException( e );
             } finally {
                if (ruby != null) {
                    this.runtimePool.returnRuntime( ruby );
                }
             }
           }




Friday, November 4, 2011
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 );
                watchDog(context);
                job.run();
             } catch (Exception e) {
                throw new JobExecutionException( e );
             } finally {
                if (ruby != null) {
                    this.runtimePool.returnRuntime( ruby );
                }
             }
           }




Friday, November 4, 2011
../app/jobs
     class JobDemo

         def initialize
          #Codigo de inicializacao
         end

      def run
       # O que você quer executar
      end
     end


Friday, November 4, 2011
../config/torquebox.yml
     jobs:
      sync_agenda:
       job: JobDemo
       cron: '0 0 12 * * ?'
     end




Friday, November 4, 2011
Mensageria
     Java Messaging Service + HornetQ




Friday, November 4, 2011
O Ministério da Saúde adverte:

                      NOSQL COMO MENSAGERIA
                                PODE
                     TRAZER DANOS A SUA SAÚDE
                       E A DE SEUS FAMILIARES




Friday, November 4, 2011
Greenfield
                                  REST + NoSQL

                                  Request/Responsext


                                      NoSQL

                     RAILS APP        pub/sub          SINATRA APP




Friday, November 4, 2011
Real World
                                   Nobody Cares!
                                    Request/Responsext


                                        NoSQL

                       RAILS APP        pub/sub          MAINFRAME




Friday, November 4, 2011
../config/torquebox.yml
     /topics/beerTopic
     /queues/queueBeer:




Friday, November 4, 2011
Tasks
     class EmailerTask < TorqueBox::Messaging::Task
      def send_welcome(payload)
       to = "#{payload[:name]} <#{payload[:address]}>"
       # send welcome email to the user
      end
     end




Friday, November 4, 2011
Tasks
     class UserController < ApplicationController
      def register
       user = User.new(params[:user])

       EmailerTask.async(:send_welcome, :address =>
     user.email, :name => user.name)
      end
     end




Friday, November 4, 2011
Processors
     include TorqueBox::Messaging

     class PrintHandler < MessageProcessor
       def on_message(body)
         puts "Processing #{body} of #{message}"
       end
       def configure(opts)
         @color = opts['color']
       end
     end




Friday, November 4, 2011
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 )
     end




Friday, November 4, 2011
Future




Friday, November 4, 2011
Future
     class EmailerTask

      def send_welcome(payload)
       to = "#{payload[:name]} <#{payload[:address]}>"
       # long running task
      end
     end




Friday, November 4, 2011
Future
     class EmailerTask

         include TorqueBox::Messaging::Backgroundable
         always_background :send_welcome

      def send_welcome(payload)
       to = "#{payload[:name]} <#{payload[:address]}>"
       # long running task
      end
     end




Friday, November 4, 2011
Future
       future = @emailTask.send_welcome(:send_welcome)

       future.started?

       future.complete?

       future.error?

       future.result
       future.result(10000)




Friday, November 4, 2011
Services



Friday, November 4, 2011
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
     end




Friday, November 4, 2011
Singleton Services
                                     Clustered
                           Server1                  Server2




            BeerService                          BeerService




Friday, November 4, 2011
Singleton Services
                                     Clustered
                           Server1                  Server2




            BeerService                          BeerService




Friday, November 4, 2011
Services
     ➜ torquebox run --clustered



     ../config/torquebox.yml
     services:
      BeerService:
       singleton: true
     end




Friday, November 4, 2011
CDI
                           Injeção de dependências




Friday, November 4, 2011
Pra quê?



Friday, November 4, 2011
Java
     package br.com.rubyconf;

     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.jar




Friday, November 4, 2011
Ruby
     class BeerController < ApplicationController

          include TorqueBox::Injectors

          def create
           beer = inject(br.com.rubyconf.Beer )
           beer.say “Ruby is for Java”
          end

     end




Friday, November 4, 2011
JNDI
    class MyService
     include TorqueBox::Injectors

     def initialize opts={}
      @factory = inject("java:comp/env/jdbc/myDB")
     end
    end




Friday, November 4, 2011
Destinations
      class MyService
       include TorqueBox::Injectors

       def initialize opts={}
        @inbound = inject("/topic/beerpub")
        @outbound = inject("/queue/beer")
       end
      end




Friday, November 4, 2011
Outras features
     Autenticação + Websockets + XA (2PC)




Friday, November 4, 2011
BackStage




Friday, November 4, 2011
Stomp Box
                           TorqueBox deployment support




Friday, November 4, 2011
Friday, November 4, 2011
Comunidade
           irc.freenode.net #torquebox
           http://torquebox.org
           http://github.com/torquebox
           twitter: @torquebox

Friday, November 4, 2011
Obrigado!
                                                  @abstractj
                                         http://github.com/abstractj



        Creative  Commons  BY-­SA  3.0




Friday, November 4, 2011

Mais conteúdo relacionado

Mais procurados

TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyistsbobmcwhirter
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBHiro Asari
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
JUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxJUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxmarekgoldmann
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
Torquebox @ Raleigh.rb - April 2011
Torquebox @ Raleigh.rb - April 2011Torquebox @ Raleigh.rb - April 2011
Torquebox @ Raleigh.rb - April 2011tobiascrawley
 
JUDCon 2010 Boston : BoxGrinder
JUDCon 2010 Boston : BoxGrinderJUDCon 2010 Boston : BoxGrinder
JUDCon 2010 Boston : BoxGrindermarekgoldmann
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
ZK_Arch_notes_20081121
ZK_Arch_notes_20081121ZK_Arch_notes_20081121
ZK_Arch_notes_20081121WANGCHOU LU
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projectsjazzman1980
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Spring into rails
Spring into railsSpring into rails
Spring into railsHiro Asari
 
When Two Worlds Collide: Java and Ruby in the Enterprise
When Two Worlds Collide: Java and Ruby in the EnterpriseWhen Two Worlds Collide: Java and Ruby in the Enterprise
When Two Worlds Collide: Java and Ruby in the Enterprisebenbrowning
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Invokedynamic in 45 Minutes
Invokedynamic in 45 MinutesInvokedynamic in 45 Minutes
Invokedynamic in 45 MinutesCharles Nutter
 

Mais procurados (19)

TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyists
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRB
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
JUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxJUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBox
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Torquebox @ Raleigh.rb - April 2011
Torquebox @ Raleigh.rb - April 2011Torquebox @ Raleigh.rb - April 2011
Torquebox @ Raleigh.rb - April 2011
 
JRuby and You
JRuby and YouJRuby and You
JRuby and You
 
JUDCon 2010 Boston : BoxGrinder
JUDCon 2010 Boston : BoxGrinderJUDCon 2010 Boston : BoxGrinder
JUDCon 2010 Boston : BoxGrinder
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
ZK_Arch_notes_20081121
ZK_Arch_notes_20081121ZK_Arch_notes_20081121
ZK_Arch_notes_20081121
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projects
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Spring into rails
Spring into railsSpring into rails
Spring into rails
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
When Two Worlds Collide: Java and Ruby in the Enterprise
When Two Worlds Collide: Java and Ruby in the EnterpriseWhen Two Worlds Collide: Java and Ruby in the Enterprise
When Two Worlds Collide: Java and Ruby in the Enterprise
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
First Day With J Ruby
First Day With J RubyFirst Day With J Ruby
First Day With J Ruby
 
Invokedynamic in 45 Minutes
Invokedynamic in 45 MinutesInvokedynamic in 45 Minutes
Invokedynamic in 45 Minutes
 

Semelhante a TorqueBox - Ultrapassando a fronteira entre Java e Ruby

Conquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSConquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSCaridy Patino
 
Javascript - How to avoid the bad parts
Javascript - How to avoid the bad partsJavascript - How to avoid the bad parts
Javascript - How to avoid the bad partsMikko Ohtamaa
 
Ruby hollywood
Ruby hollywoodRuby hollywood
Ruby hollywoodehuard
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby.toster
 
Mapnik2 Performance, September 2011
Mapnik2 Performance, September 2011Mapnik2 Performance, September 2011
Mapnik2 Performance, September 2011Development Seed
 
Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyBlazing Cloud
 
The Fast, The Slow and the Lazy
The Fast, The Slow and the LazyThe Fast, The Slow and the Lazy
The Fast, The Slow and the LazyMaurício Linhares
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineDavid Keener
 
Philly Spring UG Roo Overview
Philly Spring UG Roo OverviewPhilly Spring UG Roo Overview
Philly Spring UG Roo Overviewkrimple
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureSander Mak (@Sander_Mak)
 
A Look at the Future of HTML5
A Look at the Future of HTML5A Look at the Future of HTML5
A Look at the Future of HTML5Tim Wright
 

Semelhante a TorqueBox - Ultrapassando a fronteira entre Java e Ruby (20)

Caridy patino - node-js
Caridy patino - node-jsCaridy patino - node-js
Caridy patino - node-js
 
Conquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSConquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JS
 
CommonJS Frameworks
CommonJS FrameworksCommonJS Frameworks
CommonJS Frameworks
 
Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
Javascript - How to avoid the bad parts
Javascript - How to avoid the bad partsJavascript - How to avoid the bad parts
Javascript - How to avoid the bad parts
 
Ruby紹介
Ruby紹介Ruby紹介
Ruby紹介
 
Ruby hollywood
Ruby hollywoodRuby hollywood
Ruby hollywood
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
 
Mapnik2 Performance, September 2011
Mapnik2 Performance, September 2011Mapnik2 Performance, September 2011
Mapnik2 Performance, September 2011
 
JRuby in The Enterprise
JRuby in The EnterpriseJRuby in The Enterprise
JRuby in The Enterprise
 
Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_many
 
The Fast, The Slow and the Lazy
The Fast, The Slow and the LazyThe Fast, The Slow and the Lazy
The Fast, The Slow and the Lazy
 
Pocket Knife JS
Pocket Knife JSPocket Knife JS
Pocket Knife JS
 
Better Career with Java
Better Career with JavaBetter Career with Java
Better Career with Java
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
Philly Spring UG Roo Overview
Philly Spring UG Roo OverviewPhilly Spring UG Roo Overview
Philly Spring UG Roo Overview
 
3b jf h-readingdatafromconsole
3b jf h-readingdatafromconsole3b jf h-readingdatafromconsole
3b jf h-readingdatafromconsole
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the future
 
A Look at the Future of HTML5
A Look at the Future of HTML5A Look at the Future of HTML5
A Look at the Future of HTML5
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[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.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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 Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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.pptxEarley Information Science
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

TorqueBox - Ultrapassando a fronteira entre Java e Ruby

  • 1. Além da fronteira entre Java & Ruby Creative  Commons  BY-­SA  3.0 Friday, November 4, 2011
  • 2. @abstractj Java há 12 anos, Ruby n00b TorqueBox Contributor DynJS Contributor Caelum & ConcreteS Friday, November 4, 2011
  • 4. Java 927 JSRS! nooooooooooooooo! Friday, November 4, 2011
  • 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; } Friday, November 4, 2011 }
  • 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 JEE Friday, November 4, 2011
  • 9. Mas escala né?! Friday, November 4, 2011
  • 10. Scala Clojure Jython JVM DynJS Rhino Groovy Friday, November 4, 2011
  • 11. Ruby Mais expressiva que Java class Beer attr_accessor :beer_id, :description, :created_at end Friday, November 4, 2011
  • 13. JRuby Java + Ruby Friday, November 4, 2011
  • 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.close Friday, November 4, 2011
  • 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 Java Friday, November 4, 2011
  • 17. Ruby App Sinatra Rails Rack Passenger/Thin Apache/Nginx Friday, November 4, 2011
  • 18. Ruby App Sinatra Rails Rack Passenger/Thin Jobs Apache/Nginx crond Friday, November 4, 2011
  • 19. Ruby App Sinatra Rails Rack Tasks Passenger/Thin Jobs Resque/ DelayedJob Apache/Nginx crond Friday, November 4, 2011
  • 20. Ruby App Sinatra Rails Rack Tasks Passenger/Thin Jobs Resque/ DelayedJob Apache/Nginx crond Daemons god/monit Friday, November 4, 2011
  • 21. JBoss Tomcat Friday, November 4, 2011
  • 22. JBoss HornetQ Friday, November 4, 2011
  • 23. JBoss Quartz Friday, November 4, 2011
  • 24. JBoss Clustering Friday, November 4, 2011
  • 25. TorqueBox “The power of JBoss with the expressiveness of Ruby” Jim Crossley - MagicRuby Conference Friday, November 4, 2011
  • 27. Instalação TorqueBox do zero Friday, November 4, 2011
  • 28. ➜ jruby -S gem install torquebox torquebox-capistrano-support Friday, November 4, 2011
  • 29. ➜ wget http://torquebox.org/builds/LATEST/torquebox-dist- bin.zip ➜ unzip torquebox-dist-bin.zip ➜ export TORQUEBOX_HOME=$PWD/torquebox-2.x ➜ export JBOSS_HOME=$TORQUEBOX_HOME/jboss ➜ export JRUBY_HOME=$TORQUEBOX_HOME/jruby ➜ export PATH=$JRUBY_HOME/bin:$PATH Friday, November 4, 2011
  • 30. Rails rails new beer -m $TORQUEBOX_HOME/share/rails/template.rb Friday, November 4, 2011
  • 31. Estrutura Diretórios do TorqueBox Friday, November 4, 2011
  • 32. Rake tasks rake torquebox:deploy rake torquebox:undeploy rake torquebox:run Friday, November 4, 2011
  • 33. Deployment Make knobs, not WAR! Friday, November 4, 2011
  • 34. beer-knob.yml application: root: /Users/Bruno/rubyconfbr/beer environment: development Friday, November 4, 2011
  • 37. 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" Friday, November 4, 2011
  • 38. Web Rack, Sinatra, Rails Friday, November 4, 2011
  • 39. Caching class BeersController < ApplicationController caches_action :most_popular, :expires_in => 30.seconds def most_popular @popular_beers = Beer.most_popular(:limit => 25) end end Friday, November 4, 2011
  • 41. Clustering ➜ torquebox run --clustered Friday, November 4, 2011
  • 42. 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 end Friday, November 4, 2011
  • 45. Infinispan Caching Friday, November 4, 2011
  • 46. Invalidation Cache Cache Server1 Server2 Friday, November 4, 2011
  • 47. Invalidation Notificação Cache Cache Server1 Server2 NEW Cache Desatualizado Friday, November 4, 2011
  • 48. ../config/application.rb module Beer class Application < Rails::Application config.cache_store = :torque_box_store end end Friday, November 4, 2011
  • 49. Replicated Cache Server2 Cache Server1 Sync Cache Sync Server2 Cache Server2 Friday, November 4, 2011
  • 50. ../config/application.rb module Beer class Application < Rails::Application config.cache_store = :torque_box_store, {:mode => replicated, :sync =>false} end end Friday, November 4, 2011
  • 51. Scheduling Agendamento de Jobs Friday, November 4, 2011
  • 52. 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 ); watchDog(context); job.run(); } catch (Exception e) { throw new JobExecutionException( e ); } finally { if (ruby != null) { this.runtimePool.returnRuntime( ruby ); } } } Friday, November 4, 2011
  • 53. 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 ); watchDog(context); job.run(); } catch (Exception e) { throw new JobExecutionException( e ); } finally { if (ruby != null) { this.runtimePool.returnRuntime( ruby ); } } } Friday, November 4, 2011
  • 54. ../app/jobs class JobDemo def initialize #Codigo de inicializacao end def run # O que você quer executar end end Friday, November 4, 2011
  • 55. ../config/torquebox.yml jobs: sync_agenda: job: JobDemo cron: '0 0 12 * * ?' end Friday, November 4, 2011
  • 56. Mensageria Java Messaging Service + HornetQ Friday, November 4, 2011
  • 57. O Ministério da Saúde adverte: NOSQL COMO MENSAGERIA PODE TRAZER DANOS A SUA SAÚDE E A DE SEUS FAMILIARES Friday, November 4, 2011
  • 58. Greenfield REST + NoSQL Request/Responsext NoSQL RAILS APP pub/sub SINATRA APP Friday, November 4, 2011
  • 59. Real World Nobody Cares! Request/Responsext NoSQL RAILS APP pub/sub MAINFRAME Friday, November 4, 2011
  • 60. ../config/torquebox.yml /topics/beerTopic /queues/queueBeer: Friday, November 4, 2011
  • 61. Tasks class EmailerTask < TorqueBox::Messaging::Task def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # send welcome email to the user end end Friday, November 4, 2011
  • 62. Tasks class UserController < ApplicationController def register user = User.new(params[:user]) EmailerTask.async(:send_welcome, :address => user.email, :name => user.name) end end Friday, November 4, 2011
  • 63. Processors include TorqueBox::Messaging class PrintHandler < MessageProcessor   def on_message(body)     puts "Processing #{body} of #{message}"   end   def configure(opts)     @color = opts['color']   end end Friday, November 4, 2011
  • 64. 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 ) end Friday, November 4, 2011
  • 66. Future class EmailerTask def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # long running task end end Friday, November 4, 2011
  • 67. Future class EmailerTask include TorqueBox::Messaging::Backgroundable always_background :send_welcome def send_welcome(payload) to = "#{payload[:name]} <#{payload[:address]}>" # long running task end end Friday, November 4, 2011
  • 68. Future future = @emailTask.send_welcome(:send_welcome) future.started? future.complete? future.error? future.result future.result(10000) Friday, November 4, 2011
  • 70. 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 end Friday, November 4, 2011
  • 71. Singleton Services Clustered Server1 Server2 BeerService BeerService Friday, November 4, 2011
  • 72. Singleton Services Clustered Server1 Server2 BeerService BeerService Friday, November 4, 2011
  • 73. Services ➜ torquebox run --clustered ../config/torquebox.yml services: BeerService: singleton: true end Friday, November 4, 2011
  • 74. CDI Injeção de dependências Friday, November 4, 2011
  • 76. Java package br.com.rubyconf; 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.jar Friday, November 4, 2011
  • 77. Ruby class BeerController < ApplicationController include TorqueBox::Injectors def create beer = inject(br.com.rubyconf.Beer ) beer.say “Ruby is for Java” end end Friday, November 4, 2011
  • 78. JNDI class MyService include TorqueBox::Injectors def initialize opts={} @factory = inject("java:comp/env/jdbc/myDB") end end Friday, November 4, 2011
  • 79. Destinations class MyService include TorqueBox::Injectors def initialize opts={} @inbound = inject("/topic/beerpub") @outbound = inject("/queue/beer") end end Friday, November 4, 2011
  • 80. Outras features Autenticação + Websockets + XA (2PC) Friday, November 4, 2011
  • 82. Stomp Box TorqueBox deployment support Friday, November 4, 2011
  • 84. Comunidade irc.freenode.net #torquebox http://torquebox.org http://github.com/torquebox twitter: @torquebox Friday, November 4, 2011
  • 85. Obrigado! @abstractj http://github.com/abstractj Creative  Commons  BY-­SA  3.0 Friday, November 4, 2011