SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
Asynchronous Web Apps with Play 2.0
           Oscar Renalias
What we’ll do today

Take a look at Play’s asynchronous
capabilities

Real world usage scenarios
About me

Oscar Renalias
  oscarrenalias
  github.com/oscarrenalias
  oscar.renalias@accenture.com
  oscar@renalias.net
#wjaxplayasync
?

Stateless
Asynchronous
Reactive
RESTful
Scalability

  Why
Async??   Performance


          Responsiveness
Traditional Request Processing Model

              Thread pool
  Requests
Play’s Model

             Thread pool
                                Blocking IO



                           Asynchronous response
Requests
Haven’t we done this before?
Other attempts
App-server specific, e.g. Jetty
continuations
NIO/Netty
Servlet 3.0
Vert.x
Node.js
BlueEyes
Play’s asynchronous capabilities



Asynchronous requests
Non-blocking reactive IO
Asynchronous Requests



Futures
Promises
Planning for the Future


A Future is a read-only placeholder for
a value that may be available at a later
                 stage
Futures and Promises
val f:Promise[Something] = Akka.future {
  longOperation()
}

val f2:Promise[SomethingElse] =
  f.map(s=>handleContents(s))

f2.value.fold(
  ex=> handleError(ex),
  value=> handleOk(value)
)
Asynchronous Results

val promiseOfPIValue: Promise[Double] =
    computePIAsynchronously()

val promiseOfResult: Promise[Result] =
    promiseOfPIValue.map { pi =>
         Ok("PI value computed: " + pi)
}


Promise[Something]   Promise[Result]   Browser
Making our actions asynchronous
     with asynchronous responses
object MyController extends Controller {
  def simpleAsyncAction = Action {
    val p:Promise[Result] = Akka.future {
     val someResult = longOperation()
       Ok(someResult)
     }
    AsyncResult(p)
  }
}
def orders = Action {
    Async {
      Akka.future {
        SalesOrder.findAll
      } orTimeout(Ok(Json.toJson(JsonError("Timeout"))), 5,
SECONDS) map { orders =>
        orders.fold(
          orders => Ok(Json.toJson(orders)),
          error => Ok(Json.toJson(JsonError("Error")))
        )
      }
    }
  }



AsyncResult gets very tedious very soon. Can
               we do better?
Asynchronous responses in the real
                world
 def WithFuture[T](seconds:Int)(f: => T)(implicit jsonHelper:Writes[T]) = {
    Async {
      Akka.future {
        f
      } orTimeout(Ok(Json.toJson(JsonError(”..."))), seconds, SECONDS) map
{ result =>
        result.fold(
          data => Ok(Json.toJson(data)),
          error => Ok(Json.toJson(JsonError("Error")))
        )
      }
    }
  }

  def prettyOrders = Action {
    WithFuture(1) {
      SalesOrder.findAll
    }
  }
Demo: Promises, Futures and
  asynchronous responses
Asynchronous web services


Async {
   WS.url("http://.../").get().map { resp =>
     Ok(someJsonContent(response))
   }
}
Demo: Asynchronous web services
IO WHAT??
Reactive IO



“Don’t call us, we’ll
     call you”
Reactive IO


Enumerator = producer

Iteratee = consumer
Enumerators: the theory

  trait Enumerator[E] {
    def apply[A](i: Iteratee[E, A]):
  Promise[Iteratee[E, A]]
  }



Enumerator(Iteratee)   Promise[AnotherIteratee]
Enumerators produce data
val stringEnumerator = Enumerator("one", "two",
"three", "four")

  val updateGenerator = Enumerator.fromCallback
{ () => Promise.timeout(Some(Update.random),
5000 milliseconds)
}

val e = Enumerator.imperative(...)
e.push(“data”)
e.push(“more data”)
Behind the scenes with Iteratees
 def fold[B](
  done: (A, Input[E]) => Promise[B],
  cont: (Input[E] => Iteratee[E,A]) => Promise[B],
  error: (String, Input[E]) => Promise[B]
 ): Promise[B]




• Done: there is no more input
• Cont: more input incoming
• Error: there was an error with the input
Simplified Iteratees

Iteratee.foreach
Iteratee.fold
Iteratee.consume
Enumeratees
 Enumerator


 Enumeratee


 Enumeratee



  Iteratee
Useful Enumeratees


Enumeratee.map
Enumeratee.filter
Enumeratee.drop
Enumeratee.take
Composability
val dataGenerator = Enumerator.fromCallback { () =>
   Promise.timeout(Some(new
   java.util.Random().nextInt(100)),
   5000 milliseconds)
}

val toStr = Enumeratee.map[Int] { x => x.toString }

val toConsole = Iteratee.foreach[String](println(_))

dataGenerator &> toStr |>> toConsole
Reactive IO and HTTP responses



Ok.feed(iteratee)
Ok.stream(iteratee)
Ok.stream(enumerator)
Reactive IO in the real world



Streaming APIs
File streaming
Server-generated events
Reactive data
WebSockets
Streaming Files


  Enumerator.fromFile

           Or
Ok.sendFile(new File(…))
Streaming APIs



Data source (Enumerator)
   Enumeratee Client
WebSockets
 def websocketTime = WebSocket.async[String] { request =>
    Akka.future {
      val timeEnumerator = Enumerator.fromCallback { () =>
        Promise.timeout(Some((new Date).toString()), 5000
milliseconds)
      }

          val in = Iteratee.foreach[String] { message =>
              println(message)
           }

          (in, timeEnumerator)
      }
  }
Demo: Reactive IO
A glimpse of the future: Reactive
                Mongo


val cursor = collection.find(query)
val futureListOfArticles: Future[List[Article]] =
cursor.toList
futureListOfArticles.onSuccess { articles =>
  for(article <- articles)
    println("found article: " + article)
}
All work and no            makes Jack a
     dull boy (but there’s still hope)
Grails 2.0 + Servlet 3.0

def index() {
    def ctx = startAsync()
    ctx.start {
        new Book(title:"The Stand").save()
        render template:"books", model:[books:Book.list()]
        ctx.complete()
    }
}
All work and no            makes Jack a
     dull boy (but there’s still hope)
Vert.x
public class ServerExample extends Verticle {

  public void start() {
    vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
      public void handle(HttpServerRequest req) {
        System.out.println("Got request: " + req.uri);
        System.out.println("Headers are: ");
        for (String key : req.headers().keySet()) {
          System.out.println(key + ":" + req.headers().get(key));
        }
        req.response.headers().put("Content-Type", "text/html; charset=UTF-8");
        req.response.end("<html><body><h1>Hello from
vert.x!</h1></body></html>");
      }
    }).listen(8080);
  }
}
Github repo or it didn’t happen



https://github.com/oscarrenalias/wjax
        -2012-play-async-apps
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akkanartamonov
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus Inc.
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.liKaran Parikh
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Haim Yadid
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Jiayun Zhou
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And GroovyKen Kousen
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)Stephen Chin
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsSadayuki Furuhashi
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShellDale Lane
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadWASdev Community
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet CampPuppet
 

Was ist angesagt? (20)

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 

Andere mochten auch

Automotive: Gaining the required edge
Automotive: Gaining the required edgeAutomotive: Gaining the required edge
Automotive: Gaining the required edgePawan Kawan
 
OpenSlava 2013 - Dynamic Languages
OpenSlava 2013 - Dynamic LanguagesOpenSlava 2013 - Dynamic Languages
OpenSlava 2013 - Dynamic LanguagesOscar Renalias
 
Containerize everything - Wildcardconf 2015
Containerize everything - Wildcardconf 2015Containerize everything - Wildcardconf 2015
Containerize everything - Wildcardconf 2015Oscar Renalias
 
Richard Smeltz Linkedin Presentation Rev A
Richard Smeltz   Linkedin Presentation Rev ARichard Smeltz   Linkedin Presentation Rev A
Richard Smeltz Linkedin Presentation Rev ARichard Smeltz
 
Richard smeltz linkedin presentation
Richard smeltz   linkedin presentationRichard smeltz   linkedin presentation
Richard smeltz linkedin presentationRichard Smeltz
 
Derivative market in nepal
Derivative market in nepalDerivative market in nepal
Derivative market in nepalPawan Kawan
 
Introduction to Iteratees (Scala)
Introduction to Iteratees (Scala)Introduction to Iteratees (Scala)
Introduction to Iteratees (Scala)Alexander Lehmann
 
Role and function of nepal rastra bank
Role and function of nepal rastra bankRole and function of nepal rastra bank
Role and function of nepal rastra bankPawan Kawan
 

Andere mochten auch (9)

Automotive: Gaining the required edge
Automotive: Gaining the required edgeAutomotive: Gaining the required edge
Automotive: Gaining the required edge
 
OpenSlava 2013 - Dynamic Languages
OpenSlava 2013 - Dynamic LanguagesOpenSlava 2013 - Dynamic Languages
OpenSlava 2013 - Dynamic Languages
 
Containerize everything - Wildcardconf 2015
Containerize everything - Wildcardconf 2015Containerize everything - Wildcardconf 2015
Containerize everything - Wildcardconf 2015
 
Richard Smeltz Linkedin Presentation Rev A
Richard Smeltz   Linkedin Presentation Rev ARichard Smeltz   Linkedin Presentation Rev A
Richard Smeltz Linkedin Presentation Rev A
 
Globalization
GlobalizationGlobalization
Globalization
 
Richard smeltz linkedin presentation
Richard smeltz   linkedin presentationRichard smeltz   linkedin presentation
Richard smeltz linkedin presentation
 
Derivative market in nepal
Derivative market in nepalDerivative market in nepal
Derivative market in nepal
 
Introduction to Iteratees (Scala)
Introduction to Iteratees (Scala)Introduction to Iteratees (Scala)
Introduction to Iteratees (Scala)
 
Role and function of nepal rastra bank
Role and function of nepal rastra bankRole and function of nepal rastra bank
Role and function of nepal rastra bank
 

Ähnlich wie Asynchronous Web Apps with Play 2.0

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...GeeksLab Odessa
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Principles of the Play framework
Principles of the Play frameworkPrinciples of the Play framework
Principles of the Play frameworkBernhard Huemer
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 

Ähnlich wie Asynchronous Web Apps with Play 2.0 (20)

Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Principles of the Play framework
Principles of the Play frameworkPrinciples of the Play framework
Principles of the Play framework
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-es
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 

Mehr von Oscar Renalias

Enterprise Open Source
Enterprise Open SourceEnterprise Open Source
Enterprise Open SourceOscar Renalias
 
DockerCon EU 2017 - Containers are not just for microservices
DockerCon EU 2017 - Containers are not just for microservicesDockerCon EU 2017 - Containers are not just for microservices
DockerCon EU 2017 - Containers are not just for microservicesOscar Renalias
 
Containers aren’t just for microservices – Containerizing Legacy Workloads
Containers aren’t just for microservices – Containerizing Legacy WorkloadsContainers aren’t just for microservices – Containerizing Legacy Workloads
Containers aren’t just for microservices – Containerizing Legacy WorkloadsOscar Renalias
 
50 production deployments a day, at least
50 production deployments a day, at least50 production deployments a day, at least
50 production deployments a day, at leastOscar Renalias
 
DockerCon 2016 - Structured Container Delivery
DockerCon 2016 - Structured Container DeliveryDockerCon 2016 - Structured Container Delivery
DockerCon 2016 - Structured Container DeliveryOscar Renalias
 
Next-generation JavaScript - OpenSlava 2014
Next-generation JavaScript - OpenSlava 2014Next-generation JavaScript - OpenSlava 2014
Next-generation JavaScript - OpenSlava 2014Oscar Renalias
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Oscar Renalias
 
ScalaCheck Cookbook v1.0
ScalaCheck Cookbook v1.0ScalaCheck Cookbook v1.0
ScalaCheck Cookbook v1.0Oscar Renalias
 
Unlocking value in your (big) data
Unlocking value in your (big) dataUnlocking value in your (big) data
Unlocking value in your (big) dataOscar Renalias
 

Mehr von Oscar Renalias (9)

Enterprise Open Source
Enterprise Open SourceEnterprise Open Source
Enterprise Open Source
 
DockerCon EU 2017 - Containers are not just for microservices
DockerCon EU 2017 - Containers are not just for microservicesDockerCon EU 2017 - Containers are not just for microservices
DockerCon EU 2017 - Containers are not just for microservices
 
Containers aren’t just for microservices – Containerizing Legacy Workloads
Containers aren’t just for microservices – Containerizing Legacy WorkloadsContainers aren’t just for microservices – Containerizing Legacy Workloads
Containers aren’t just for microservices – Containerizing Legacy Workloads
 
50 production deployments a day, at least
50 production deployments a day, at least50 production deployments a day, at least
50 production deployments a day, at least
 
DockerCon 2016 - Structured Container Delivery
DockerCon 2016 - Structured Container DeliveryDockerCon 2016 - Structured Container Delivery
DockerCon 2016 - Structured Container Delivery
 
Next-generation JavaScript - OpenSlava 2014
Next-generation JavaScript - OpenSlava 2014Next-generation JavaScript - OpenSlava 2014
Next-generation JavaScript - OpenSlava 2014
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
 
ScalaCheck Cookbook v1.0
ScalaCheck Cookbook v1.0ScalaCheck Cookbook v1.0
ScalaCheck Cookbook v1.0
 
Unlocking value in your (big) data
Unlocking value in your (big) dataUnlocking value in your (big) data
Unlocking value in your (big) data
 

Asynchronous Web Apps with Play 2.0

  • 1. Asynchronous Web Apps with Play 2.0 Oscar Renalias
  • 2. What we’ll do today Take a look at Play’s asynchronous capabilities Real world usage scenarios
  • 3. About me Oscar Renalias oscarrenalias github.com/oscarrenalias oscar.renalias@accenture.com oscar@renalias.net
  • 6. Scalability Why Async?? Performance Responsiveness
  • 7. Traditional Request Processing Model Thread pool Requests
  • 8. Play’s Model Thread pool Blocking IO Asynchronous response Requests
  • 9. Haven’t we done this before?
  • 10. Other attempts App-server specific, e.g. Jetty continuations NIO/Netty Servlet 3.0 Vert.x Node.js BlueEyes
  • 11. Play’s asynchronous capabilities Asynchronous requests Non-blocking reactive IO
  • 13. Planning for the Future A Future is a read-only placeholder for a value that may be available at a later stage
  • 14. Futures and Promises val f:Promise[Something] = Akka.future { longOperation() } val f2:Promise[SomethingElse] = f.map(s=>handleContents(s)) f2.value.fold( ex=> handleError(ex), value=> handleOk(value) )
  • 15. Asynchronous Results val promiseOfPIValue: Promise[Double] = computePIAsynchronously() val promiseOfResult: Promise[Result] = promiseOfPIValue.map { pi => Ok("PI value computed: " + pi) } Promise[Something] Promise[Result] Browser
  • 16. Making our actions asynchronous with asynchronous responses object MyController extends Controller { def simpleAsyncAction = Action { val p:Promise[Result] = Akka.future { val someResult = longOperation() Ok(someResult) } AsyncResult(p) } }
  • 17. def orders = Action { Async { Akka.future { SalesOrder.findAll } orTimeout(Ok(Json.toJson(JsonError("Timeout"))), 5, SECONDS) map { orders => orders.fold( orders => Ok(Json.toJson(orders)), error => Ok(Json.toJson(JsonError("Error"))) ) } } } AsyncResult gets very tedious very soon. Can we do better?
  • 18. Asynchronous responses in the real world def WithFuture[T](seconds:Int)(f: => T)(implicit jsonHelper:Writes[T]) = { Async { Akka.future { f } orTimeout(Ok(Json.toJson(JsonError(”..."))), seconds, SECONDS) map { result => result.fold( data => Ok(Json.toJson(data)), error => Ok(Json.toJson(JsonError("Error"))) ) } } } def prettyOrders = Action { WithFuture(1) { SalesOrder.findAll } }
  • 19. Demo: Promises, Futures and asynchronous responses
  • 20. Asynchronous web services Async { WS.url("http://.../").get().map { resp => Ok(someJsonContent(response)) } }
  • 23. Reactive IO “Don’t call us, we’ll call you”
  • 24. Reactive IO Enumerator = producer Iteratee = consumer
  • 25. Enumerators: the theory trait Enumerator[E] { def apply[A](i: Iteratee[E, A]): Promise[Iteratee[E, A]] } Enumerator(Iteratee) Promise[AnotherIteratee]
  • 26. Enumerators produce data val stringEnumerator = Enumerator("one", "two", "three", "four") val updateGenerator = Enumerator.fromCallback { () => Promise.timeout(Some(Update.random), 5000 milliseconds) } val e = Enumerator.imperative(...) e.push(“data”) e.push(“more data”)
  • 27. Behind the scenes with Iteratees def fold[B]( done: (A, Input[E]) => Promise[B], cont: (Input[E] => Iteratee[E,A]) => Promise[B], error: (String, Input[E]) => Promise[B] ): Promise[B] • Done: there is no more input • Cont: more input incoming • Error: there was an error with the input
  • 29. Enumeratees Enumerator Enumeratee Enumeratee Iteratee
  • 31. Composability val dataGenerator = Enumerator.fromCallback { () => Promise.timeout(Some(new java.util.Random().nextInt(100)), 5000 milliseconds) } val toStr = Enumeratee.map[Int] { x => x.toString } val toConsole = Iteratee.foreach[String](println(_)) dataGenerator &> toStr |>> toConsole
  • 32. Reactive IO and HTTP responses Ok.feed(iteratee) Ok.stream(iteratee) Ok.stream(enumerator)
  • 33. Reactive IO in the real world Streaming APIs File streaming Server-generated events Reactive data WebSockets
  • 34. Streaming Files Enumerator.fromFile Or Ok.sendFile(new File(…))
  • 35. Streaming APIs Data source (Enumerator) Enumeratee Client
  • 36. WebSockets def websocketTime = WebSocket.async[String] { request => Akka.future { val timeEnumerator = Enumerator.fromCallback { () => Promise.timeout(Some((new Date).toString()), 5000 milliseconds) } val in = Iteratee.foreach[String] { message => println(message) } (in, timeEnumerator) } }
  • 38. A glimpse of the future: Reactive Mongo val cursor = collection.find(query) val futureListOfArticles: Future[List[Article]] = cursor.toList futureListOfArticles.onSuccess { articles => for(article <- articles) println("found article: " + article) }
  • 39. All work and no makes Jack a dull boy (but there’s still hope) Grails 2.0 + Servlet 3.0 def index() { def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } }
  • 40. All work and no makes Jack a dull boy (but there’s still hope) Vert.x public class ServerExample extends Verticle { public void start() { vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() { public void handle(HttpServerRequest req) { System.out.println("Got request: " + req.uri); System.out.println("Headers are: "); for (String key : req.headers().keySet()) { System.out.println(key + ":" + req.headers().get(key)); } req.response.headers().put("Content-Type", "text/html; charset=UTF-8"); req.response.end("<html><body><h1>Hello from vert.x!</h1></body></html>"); } }).listen(8080); } }
  • 41. Github repo or it didn’t happen https://github.com/oscarrenalias/wjax -2012-play-async-apps
  • 42.
  • 43.