SlideShare a Scribd company logo
AKKA HTTP
A.K.A. SPRAY 2.0
Présenté par Jean Detoeuf / @thebignet
JEAN DETOEUF
DÉVELOPPEUR
Passionné de nouvelles technologies
#jvm #docker #craftmanship #rpi #diy
AVERTISSEMENT
Je ne suis pas un expert en Scala
Soyez sympas ^^
PROJET EN COURS DE MATURATION
version lors de cette présentation2.0.1
mélange entre Spray et Akka
J'ai eu l'idée de cette présentation à la version 1.0, il était temps !
AKKA STREAMS
Présenté au SLUG par en février 2015Frédéric Masion
Source ~> Flow ~> Sink
Source décrit une source de données
Flow représente une transformation de ces données
Sink une opération terminale
AKKA STREAMS
Source ~> Flow1 ~> Flow2a ~> Sink
~> Flow2b
Fan-out / Fan-in
AKKA HTTP
Constuit sur Akka Streams
Internet est un tuyau
rempli de chatons
AKKA HTTP
Flow[HttpRequest, HttpResponse]
AKKA HTTP
Client et serveur
Mettre des acteurs sur HTTP
MODULES
akka-http-spray-json
akka-http-xml
akka-http-testkit
akka-http
akka-http-core
C'EST BON, MONTRE-MOI LE CODE
Les exemples sont pour la plupart tirés de la documentation
d'Akka
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
MARSHALLING/UNMARSHALLING
MARSHALLING/UNMARSHALLING
Comment passer d'un flux HTTP à Scala et inversement ?
MARSHALLING
Marshallers prédéfinis
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
akka.http.scaladsl.model.MessageEntity
T <: akka.http.scaladsl.model.Multipart
T si ToEntityMarshaller[T] est présent
MARSHALLING
Résolution implicite
Si le type ToEntityMarshaller[T] est défini, il est utilisé
UNMARSHALLING
Unmarshallers prédéfinis
Byte
Short
Int
Long
Float
Double
Boolean
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
ROUTAGE
LOW-LEVEL
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)`
,
"Hello world!"))
case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
HttpResponse(entity = "PONG!")
case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
sys.error("BOOM!")
case _: HttpRequest =>
HttpResponse(404, entity = "Unknown resource!")
}
Http().bindAndHandleSync(requestHandler, "localhost", 8080)
HIGH-LEVEL
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val route =
get {
pathSingleSlash {
complete {
<html>
<body>Hello world!</body>
</html>
}
} ~
path("ping") {
complete("PONG!")
} ~
path("crash") {
sys.error("BOOM!")
}
}
// `route` will be implicitly converted to `Flow` using `RouteResult
.route2HandlerFlow`
Http().bindAndHandle(route, "localhost", 8080)
DIRECTIVES
DIRECTIVES
Intercepte la requête
Filtrage de la requête
Transformation de la requête ou réponse
Extraire des informations
EXEMPLE
val route =
path("order" / IntNumber) { id =>
(get | put) {
extractMethod { m =>
complete(s"Received ${m.name} request for order $id")
}
}
}
EXEMPLE 2
val orderGetOrPutWithMethod =
path("order" / IntNumber) & (get | put) & extractMethod
val route = orderGetOrPutWithMethod { (id, m) =>
complete(s"Received ${m.name} request for order $id")
}
et
PATHMATCHER
val matcher: PathMatcher1[Option[Int]] =
"foo" / "bar" / "X" ~ IntNumber.? / ("edit" | "create")
Intercepte les chemins suivants :
foo/bar/X42/edit
foo/bar/X/create
EXTRACTION CASE CLASS
case class Color(red: Int, green: Int, blue: Int)
val route = path("color") {
parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color)
{
color =>
// utiliser color
}
}
VALIDATION CASE CLASS
case class Color(name: String, red: Int, green: Int, blue: Int) {
require(!name.isEmpty, "color name must not be empty")
require(0 <= red && red <= 255, "red color component must be betwe
en 0 and 255")
require(0 <= green && green <= 255, "green color component must be
between 0 and 255")
require(0 <= blue && blue <= 255, "blue color component must be be
tween 0 and 255")
}
ValidationRejection si require ne passe pas
Par défaut : 400 Bad Request
TESTS
Pour la route suivante
val smallRoute =
get {
pathSingleSlash {
complete {
"Hello World !"
}
} ~
path("ping") {
complete("PONG !")
}
}
Test
"Hello World ! non renvoyé sur /" in {
Get() ~> smallRoute ~> check {
status === StatusCodes.OK
responseAs[String] shouldEqual "Hello World !"
}
}
Pour la même route ...
val smallRoute =
get {
pathSingleSlash {
complete {
"Hello World !"
}
} ~
path("ping") {
complete("PONG !")
}
}
Test
"GET sur chemin inconnu non pris en compte" in {
Get("/pouet") ~> smallRoute ~> check {
handled shouldBe false
}
}
VARIABLES UTILISABLES DANS LES
TESTS
entityAs
handled
header
response
status
entre autres ...
CLIENT
val responseFuture: Future[HttpResponse] =
Http().singleRequest(HttpRequest(uri = "http://akka.io"))
QUESTIONS ?
MERCI POUR VOTRE ÉCOUTE
Cette présentation :
@thebignet
thebignet
thebignet
talk-akka-http

More Related Content

ODP
Akka http
Knoldus Inc.
 
ODP
An Introduction to Akka http
Knoldus Inc.
 
PDF
scalaphx-akka-http
Terry Drozdowski
 
PDF
Practical Akka HTTP - introduction
Łukasz Sowa
 
PDF
Building scalable rest service using Akka HTTP
datamantra
 
PDF
Akka Http , Routes, Streams with Scala
Jerry Kuru
 
ODP
Http programming in play
Knoldus Inc.
 
PDF
Display earthquakes with Akka-http
Pierangelo Cecchetto
 
Akka http
Knoldus Inc.
 
An Introduction to Akka http
Knoldus Inc.
 
scalaphx-akka-http
Terry Drozdowski
 
Practical Akka HTTP - introduction
Łukasz Sowa
 
Building scalable rest service using Akka HTTP
datamantra
 
Akka Http , Routes, Streams with Scala
Jerry Kuru
 
Http programming in play
Knoldus Inc.
 
Display earthquakes with Akka-http
Pierangelo Cecchetto
 

What's hot (20)

PDF
Akka Streams and HTTP
Roland Kuhn
 
PDF
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
PPTX
Apache Apex - BufferServer
Pradeep Dalvi
 
PDF
VJUG24 - Reactive Integrations with Akka Streams
Johan Andrén
 
PDF
Scala usergroup stockholm - reactive integrations with akka streams
Johan Andrén
 
PPTX
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
PDF
System Integration with Akka and Apache Camel
krasserm
 
PDF
Service discovery like a pro (presented at reversimX)
Eran Harel
 
PDF
Asynchronous stream processing with Akka Streams
Johan Andrén
 
PDF
Introduction tomcat7 servlet3
JavaEE Trainers
 
PDF
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Lightbend
 
PDF
Play Framework
Harinath Krishnamoorthy
 
PDF
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
PDF
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
ZIP
Above the clouds: introducing Akka
nartamonov
 
PPTX
Exploring Twitter's Finagle technology stack for microservices
💡 Tomasz Kogut
 
PDF
Reactive Streams / Akka Streams - GeeCON Prague 2014
Konrad Malawski
 
PPTX
Stream processing from single node to a cluster
Gal Marder
 
PDF
Reactive integrations with Akka Streams
Konrad Malawski
 
PDF
Catalyst MVC
Sheeju Alex
 
Akka Streams and HTTP
Roland Kuhn
 
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
Apache Apex - BufferServer
Pradeep Dalvi
 
VJUG24 - Reactive Integrations with Akka Streams
Johan Andrén
 
Scala usergroup stockholm - reactive integrations with akka streams
Johan Andrén
 
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
System Integration with Akka and Apache Camel
krasserm
 
Service discovery like a pro (presented at reversimX)
Eran Harel
 
Asynchronous stream processing with Akka Streams
Johan Andrén
 
Introduction tomcat7 servlet3
JavaEE Trainers
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Lightbend
 
Play Framework
Harinath Krishnamoorthy
 
Reactive Stream Processing with Akka Streams
Konrad Malawski
 
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
Above the clouds: introducing Akka
nartamonov
 
Exploring Twitter's Finagle technology stack for microservices
💡 Tomasz Kogut
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Konrad Malawski
 
Stream processing from single node to a cluster
Gal Marder
 
Reactive integrations with Akka Streams
Konrad Malawski
 
Catalyst MVC
Sheeju Alex
 
Ad

Viewers also liked (20)

PPTX
Building a Reactive RESTful API with Akka Http & Slick
Zalando Technology
 
PPTX
Akka-http
Iosif Itkin
 
PPTX
Akka HTTP
TanUkkii
 
PDF
Akka in Production - ScalaDays 2015
Evan Chan
 
PDF
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
PDF
[Start] Playing
佑介 九岡
 
PDF
Playing with Scala
Tamer Abdul-Radi
 
PDF
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
it-people
 
ODP
Play Template Engine Based On Scala
Knoldus Inc.
 
PDF
Designing Reactive Systems with Akka
Thomas Lockney
 
PDF
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
Matt Raible
 
PDF
Your First Scala Web Application using Play 2.1
Matthew Barlocker
 
PDF
Custom deployments with sbt-native-packager
GaryCoady
 
PDF
Unsucking Error Handling with Futures
GaryCoady
 
PDF
Auto-scaling your API: Insights and Tips from the Zalando Team
Zalando Technology
 
PDF
Ship your Scala code often and easy with Docker
Marcus Lönnberg
 
PDF
Play framework And Google Cloud Platform GCP.
Eng Chrispinus Onyancha
 
PPTX
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
PDF
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Manuel Bernhardt
 
PPTX
Введение в Akka
Zheka Kozlov
 
Building a Reactive RESTful API with Akka Http & Slick
Zalando Technology
 
Akka-http
Iosif Itkin
 
Akka HTTP
TanUkkii
 
Akka in Production - ScalaDays 2015
Evan Chan
 
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
[Start] Playing
佑介 九岡
 
Playing with Scala
Tamer Abdul-Radi
 
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
it-people
 
Play Template Engine Based On Scala
Knoldus Inc.
 
Designing Reactive Systems with Akka
Thomas Lockney
 
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
Matt Raible
 
Your First Scala Web Application using Play 2.1
Matthew Barlocker
 
Custom deployments with sbt-native-packager
GaryCoady
 
Unsucking Error Handling with Futures
GaryCoady
 
Auto-scaling your API: Insights and Tips from the Zalando Team
Zalando Technology
 
Ship your Scala code often and easy with Docker
Marcus Lönnberg
 
Play framework And Google Cloud Platform GCP.
Eng Chrispinus Onyancha
 
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Manuel Bernhardt
 
Введение в Akka
Zheka Kozlov
 
Ad

Similar to Akka http 2 (20)

PPTX
Chaincode Development 區塊鏈鏈碼開發
HO-HSUN LIN
 
PDF
Rack Middleware
LittleBIGRuby
 
PDF
Server Side Swift: Vapor
Paweł Kowalczuk
 
KEY
Aimaf
Saad RGUIG
 
PPTX
Tools for Making Machine Learning more Reactive
Jeff Smith
 
DOCX
VPN Access Runbook
Taha Shakeel
 
PDF
Lego: A brick system build by scala
lunfu zhong
 
PDF
Back to the futures, actors and pipes: using Akka for large-scale data migration
Manuel Bernhardt
 
PDF
Easy Enterprise Integration Patterns with Apache Camel, ActiveMQ and ServiceMix
elliando dias
 
KEY
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
PDF
XQuery Rocks
William Candillon
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
DevClub_lv
 
PDF
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PDF
JavaCro 2014 Scala and Java EE 7 Development Experiences
Peter Pilgrim
 
PDF
Presto anatomy
Dongmin Yu
 
PDF
Rest with-spray
Nimrod Argov
 
PDF
[245] presto 내부구조 파헤치기
NAVER D2
 
PDF
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
PDF
Riding Apache Camel
Apache Event Beijing
 
Chaincode Development 區塊鏈鏈碼開發
HO-HSUN LIN
 
Rack Middleware
LittleBIGRuby
 
Server Side Swift: Vapor
Paweł Kowalczuk
 
Aimaf
Saad RGUIG
 
Tools for Making Machine Learning more Reactive
Jeff Smith
 
VPN Access Runbook
Taha Shakeel
 
Lego: A brick system build by scala
lunfu zhong
 
Back to the futures, actors and pipes: using Akka for large-scale data migration
Manuel Bernhardt
 
Easy Enterprise Integration Patterns with Apache Camel, ActiveMQ and ServiceMix
elliando dias
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
XQuery Rocks
William Candillon
 
Orchestrating things in Angular application
Peter Abraham
 
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
DevClub_lv
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
Peter Pilgrim
 
Presto anatomy
Dongmin Yu
 
Rest with-spray
Nimrod Argov
 
[245] presto 내부구조 파헤치기
NAVER D2
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
Riding Apache Camel
Apache Event Beijing
 

Recently uploaded (20)

PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
Immersive experiences: what Pharo users do!
ESUG
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 

Akka http 2

  • 1. AKKA HTTP A.K.A. SPRAY 2.0 Présenté par Jean Detoeuf / @thebignet
  • 2. JEAN DETOEUF DÉVELOPPEUR Passionné de nouvelles technologies #jvm #docker #craftmanship #rpi #diy
  • 3. AVERTISSEMENT Je ne suis pas un expert en Scala Soyez sympas ^^
  • 4. PROJET EN COURS DE MATURATION version lors de cette présentation2.0.1 mélange entre Spray et Akka J'ai eu l'idée de cette présentation à la version 1.0, il était temps !
  • 5. AKKA STREAMS Présenté au SLUG par en février 2015Frédéric Masion Source ~> Flow ~> Sink Source décrit une source de données Flow représente une transformation de ces données Sink une opération terminale
  • 6. AKKA STREAMS Source ~> Flow1 ~> Flow2a ~> Sink ~> Flow2b Fan-out / Fan-in
  • 7. AKKA HTTP Constuit sur Akka Streams Internet est un tuyau rempli de chatons
  • 9. AKKA HTTP Client et serveur Mettre des acteurs sur HTTP
  • 11. C'EST BON, MONTRE-MOI LE CODE Les exemples sont pour la plupart tirés de la documentation d'Akka
  • 12. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 13. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 14. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 15. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 17. MARSHALLING/UNMARSHALLING Comment passer d'un flux HTTP à Scala et inversement ?
  • 19. MARSHALLING Résolution implicite Si le type ToEntityMarshaller[T] est défini, il est utilisé
  • 22. LOW-LEVEL import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model._ import akka.stream.ActorMaterializer implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() val requestHandler: HttpRequest => HttpResponse = { case HttpRequest(GET, Uri.Path("/"), _, _, _) => HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)` , "Hello world!")) case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => HttpResponse(entity = "PONG!") case HttpRequest(GET, Uri.Path("/crash"), _, _, _) => sys.error("BOOM!") case _: HttpRequest => HttpResponse(404, entity = "Unknown resource!") } Http().bindAndHandleSync(requestHandler, "localhost", 8080)
  • 23. HIGH-LEVEL import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() val route = get { pathSingleSlash { complete { <html> <body>Hello world!</body> </html> } } ~ path("ping") { complete("PONG!") } ~ path("crash") { sys.error("BOOM!") } }
  • 24. // `route` will be implicitly converted to `Flow` using `RouteResult .route2HandlerFlow` Http().bindAndHandle(route, "localhost", 8080)
  • 26. DIRECTIVES Intercepte la requête Filtrage de la requête Transformation de la requête ou réponse Extraire des informations
  • 27. EXEMPLE val route = path("order" / IntNumber) { id => (get | put) { extractMethod { m => complete(s"Received ${m.name} request for order $id") } } }
  • 28. EXEMPLE 2 val orderGetOrPutWithMethod = path("order" / IntNumber) & (get | put) & extractMethod val route = orderGetOrPutWithMethod { (id, m) => complete(s"Received ${m.name} request for order $id") }
  • 29. et PATHMATCHER val matcher: PathMatcher1[Option[Int]] = "foo" / "bar" / "X" ~ IntNumber.? / ("edit" | "create") Intercepte les chemins suivants : foo/bar/X42/edit foo/bar/X/create
  • 30. EXTRACTION CASE CLASS case class Color(red: Int, green: Int, blue: Int) val route = path("color") { parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color) { color => // utiliser color } }
  • 31. VALIDATION CASE CLASS case class Color(name: String, red: Int, green: Int, blue: Int) { require(!name.isEmpty, "color name must not be empty") require(0 <= red && red <= 255, "red color component must be betwe en 0 and 255") require(0 <= green && green <= 255, "green color component must be between 0 and 255") require(0 <= blue && blue <= 255, "blue color component must be be tween 0 and 255") } ValidationRejection si require ne passe pas Par défaut : 400 Bad Request
  • 32. TESTS
  • 33. Pour la route suivante val smallRoute = get { pathSingleSlash { complete { "Hello World !" } } ~ path("ping") { complete("PONG !") } } Test "Hello World ! non renvoyé sur /" in { Get() ~> smallRoute ~> check { status === StatusCodes.OK responseAs[String] shouldEqual "Hello World !" } }
  • 34. Pour la même route ... val smallRoute = get { pathSingleSlash { complete { "Hello World !" } } ~ path("ping") { complete("PONG !") } } Test "GET sur chemin inconnu non pris en compte" in { Get("/pouet") ~> smallRoute ~> check { handled shouldBe false } }
  • 35. VARIABLES UTILISABLES DANS LES TESTS entityAs handled header response status entre autres ...
  • 36. CLIENT val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
  • 38. MERCI POUR VOTRE ÉCOUTE Cette présentation : @thebignet thebignet thebignet talk-akka-http