SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
akka-http
ScalaPHX June 2016
Terry Drozdowski
Agenda
• Introductions
• What is akka?
• akka-streams basics
• Introduction to akka-http
• Q & A
Resources
• Code: https://github.com/ScalaPHX/akka-http-examples
• akka-actor docs (Scala) - http://doc.akka.io/docs/akka/
2.4.7/scala/index-actors.html
• akka-stream docs (Scala) - http://doc.akka.io/docs/akka/
2.4.7/scala/stream/index.html
• akka-http docs (Scala) - http://doc.akka.io/docs/akka/
2.4.7/scala/http/index.html
• ScalaTest - http://scalatest.org
What is Akka?
• Toolkit for building ‘reactive’ applications
• At its core a JVM implementation of ‘actor pattern’
• Grown to include:
• IO/Networking
• Streams
• http
• agents
• Written in Scala, supports Java (Java 8 support ‘experimental' in some cases)
• http://akka.io
Actor Model
• Created by
Ericsson for
Erlang (OTP)
• Hierarchical,
highly resilient,
message passing
• Millions of actors
in one system
(300 bytes each)
akka-streams
• A ‘reactive’ data streaming API
• Built on akka-actors
• Gives you methods to deal with back-pressure
• Key terms
• Stream - active process that involves moving & transforming data
• Element - processing unit of a stream
• Back-pressure - flow control; notify consumers/producers of current ability
• Graph - stream processing topology
• Processing Stage - building blocks that build up a graph: i.e. map, filter, etc.
Akka Streams Model
• Source - processing stage with
exactly one output
• Sink - processing stage with
exactly one input
• Flow - processing stage with
exactly one input and output
• Runnable Graph - a flow with
both ends attached to a Source
and a Sink which can be run()
• Learn more! http://doc.akka.io/
docs/akka/2.4.7/scala/stream/
stream-flows-and-basics.html
akka-http
• Full server and client side implementation of HTTP on top of akka-actor & akka-stream
• Not a web framework!
• General toolkit for providing and consuming HTTP services
• Provides:
• a high level and low level API
• Routing DSL
• web socket support (for client & server side!!)
• an awesome testkit!
• Provided for Scala & Java 8
• Formerly known as Spray
Akka HTTP Model
Concept Description
Http
Provides helpers to create the streams for processing server responses or client requests (http or
https supported)
HttpRequest
HTTP request. Requires at least an URI to instantiate and will default to method GET; can choose
alternate HttpMethod and attach Headers and a request entity
HttpResponse
Contains information related to the HTTP response, including content types, headers, status code
and response entity if applicable.
HttpEntity
Represents the body of the request or response as a Source[ByteString, Any]; commonly un-
marshalled to the desired type; Stream is processed asynchronously!
Headers
Strongly typed instances of all known HTTP 1.1 headers; Custom headers can be added by
extending appropriate API; no simple string headers! (error prone)
ContentTypes
Strongly typed instances of all commonly used ContentTypes; as with headers, custom
ContentTypes can be registered with the system; no simple string values
MediaTypes
Strongly typed instances of all commonly used MediaTypes; custom MediaTypes can be registered
with the system; no simple string values
Un-Marshalling
Key to turning your request/response entities to/from bytes for transport by the system. Out of the
box support for basics (i.e. String); modules add support for others (i.e. JSON)
RequestContext Wraps the HttpRequest and provides other helpers for working with requests
Low-Level Server Example
There is a better way…
• Routing DSL to the rescue…
• (Example)
Akka HTTP - Routes
• Server side code simplified with Routes
• A route is an alias for a function that turns a RequestContext into a
RouteResult
• type Route = RequestContext => Future[RouteResult]
• A route can do the following when it receives a request:
• complete the request
• reject the request (I don’t handle this request)
• fail the request (an actual error has occurred)
• do any type of asynchronous processing and return a Future[RouteResult]
Akka HTTP - The Routing
Tree
• Routes can be composed to build a tree
• Three basic operations
• transformation - delegates to an inner
route, but changes some property of the
request or response before it hands it off
• filtering - only processes routes
satisfying some criteria; rejects all others
• chaining - tries a second route if the first
was rejected
• ~ is the chaining operator
• put most specific cases up front, general
cases in the back (i.e. route 3 is a ‘catch all’
route)
Akka HTTP - Directives
• Directive is a building block for a route
• akka-http provides a number of pre-defined directives
• Custom directives can be built by composing existing directives with operators or by
extending the API
• form: name(args) { extractions => // inner route }
Operator Purpose Example
~ chain val route = a {} ~ b{} ~ c{}
| or val getOrPut = get | put
& and val getFoo = path(“foo”) & get
Akka HTTP - Commonly
Used Directives
Directive Description
path(pm : PathMatcher)
Matches the given path give the pattern in the
PathMatcher
get, put, post, delete, head, patch Common HTTP Methods
complete Completes a request; does not handle Futures
onComplete, onSuccess Completes a request and handles Futures
extract*
Extract various parts of the HttpResponse..
i.e. extractClientIP, extractHost, etc.
reject Rejects a route with a specific Rejection
entity
the HTTP Request entity; will un-marshall it to the given
type.
authenticate*
Numerous directives to support various types of HTTP
authentication, ie. OAuth2, Basic.
parameters Extract values for vary query parameters
Akka HTTP Examples
• Simple Routing DSL Example
• HTTP Microservice Example
• Simple Client Side GET
• Simple Client Side POST
Akka HTTP RouteTestkit
• If you build with the Routing DSL, use the test kit
to validate that it works as expected!
• ScalaTest based
• Makes use of the RequestBuilder to quickly build
up tests for your routes
• Example…
Akka HTTP - Much More!
• There’s a lot more…
• Custom Marshalling/Un-marshalling
• Case class extractions & validation
• Custom Headers (i.e X-CUSTOM…)
• Custom ContentTypes/MediaTypes
• Custom Rejection Handlers
• HTTPS
• WebSockets (client and server)
• Stand-Alone HTTP Layer Usage (Bidi)

Weitere ähnliche Inhalte

Was ist angesagt?

System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
krasserm
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka Streams
Konrad Malawski
 

Was ist angesagt? (20)

Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
 
VJUG24 - Reactive Integrations with Akka Streams
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka Streams
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Interactive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark StreamingInteractive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark Streaming
 
Scalatra 2.2
Scalatra 2.2Scalatra 2.2
Scalatra 2.2
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
Dive into spark2
Dive into spark2Dive into spark2
Dive into spark2
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka Streams
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
 
Sbt, idea and eclipse
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipse
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in Scala
 
What’s expected in Spring 5
What’s expected in Spring 5What’s expected in Spring 5
What’s expected in Spring 5
 

Andere mochten auch

Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinar
patriknw
 

Andere mochten auch (20)

Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
 
Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinar
 
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
Codemotion   akka persistence, cqrs%2 fes y otras siglas del montónCodemotion   akka persistence, cqrs%2 fes y otras siglas del montón
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akka
 
Akka Persistence | Event Sourcing
Akka Persistence | Event SourcingAkka Persistence | Event Sourcing
Akka Persistence | Event Sourcing
 
Akka Streams
Akka StreamsAkka Streams
Akka Streams
 
Event Sourcing using Akka on AWS
Event Sourcing using Akka on AWSEvent Sourcing using Akka on AWS
Event Sourcing using Akka on AWS
 
Akka-http
Akka-httpAkka-http
Akka-http
 
CQRS+ESをAkka Persistenceを使って実装してみる。
CQRS+ESをAkka Persistenceを使って実装してみる。CQRS+ESをAkka Persistenceを使って実装してみる。
CQRS+ESをAkka Persistenceを使って実装してみる。
 
JavaOne: A tour of (advanced) akka features in 60 minutes [con1706]
JavaOne: A tour of (advanced) akka features in 60 minutes [con1706]JavaOne: A tour of (advanced) akka features in 60 minutes [con1706]
JavaOne: A tour of (advanced) akka features in 60 minutes [con1706]
 
DDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceDDDing Tools = Akka Persistence
DDDing Tools = Akka Persistence
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
 
Akka Persistence and Eventuate
Akka Persistence and EventuateAkka Persistence and Eventuate
Akka Persistence and Eventuate
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014
 
spray: REST on Akka (Scala Days)
spray: REST on Akka (Scala Days)spray: REST on Akka (Scala Days)
spray: REST on Akka (Scala Days)
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
CQRS + ES with Scala and Akka
CQRS + ES with Scala and AkkaCQRS + ES with Scala and Akka
CQRS + ES with Scala and Akka
 
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
 
Resilient Applications with Akka Persistence - Scaladays 2014
Resilient Applications with Akka Persistence - Scaladays 2014Resilient Applications with Akka Persistence - Scaladays 2014
Resilient Applications with Akka Persistence - Scaladays 2014
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 

Ähnlich wie scalaphx-akka-http

Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
Michael Hackstein
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
Jeelani Shaik
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 

Ähnlich wie scalaphx-akka-http (20)

Building REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaBuilding REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with Scala
 
Scala45 spray test
Scala45 spray testScala45 spray test
Scala45 spray test
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Servlets
ServletsServlets
Servlets
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStack
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 

scalaphx-akka-http

  • 2. Agenda • Introductions • What is akka? • akka-streams basics • Introduction to akka-http • Q & A
  • 3. Resources • Code: https://github.com/ScalaPHX/akka-http-examples • akka-actor docs (Scala) - http://doc.akka.io/docs/akka/ 2.4.7/scala/index-actors.html • akka-stream docs (Scala) - http://doc.akka.io/docs/akka/ 2.4.7/scala/stream/index.html • akka-http docs (Scala) - http://doc.akka.io/docs/akka/ 2.4.7/scala/http/index.html • ScalaTest - http://scalatest.org
  • 4. What is Akka? • Toolkit for building ‘reactive’ applications • At its core a JVM implementation of ‘actor pattern’ • Grown to include: • IO/Networking • Streams • http • agents • Written in Scala, supports Java (Java 8 support ‘experimental' in some cases) • http://akka.io
  • 5. Actor Model • Created by Ericsson for Erlang (OTP) • Hierarchical, highly resilient, message passing • Millions of actors in one system (300 bytes each)
  • 6. akka-streams • A ‘reactive’ data streaming API • Built on akka-actors • Gives you methods to deal with back-pressure • Key terms • Stream - active process that involves moving & transforming data • Element - processing unit of a stream • Back-pressure - flow control; notify consumers/producers of current ability • Graph - stream processing topology • Processing Stage - building blocks that build up a graph: i.e. map, filter, etc.
  • 7. Akka Streams Model • Source - processing stage with exactly one output • Sink - processing stage with exactly one input • Flow - processing stage with exactly one input and output • Runnable Graph - a flow with both ends attached to a Source and a Sink which can be run() • Learn more! http://doc.akka.io/ docs/akka/2.4.7/scala/stream/ stream-flows-and-basics.html
  • 8. akka-http • Full server and client side implementation of HTTP on top of akka-actor & akka-stream • Not a web framework! • General toolkit for providing and consuming HTTP services • Provides: • a high level and low level API • Routing DSL • web socket support (for client & server side!!) • an awesome testkit! • Provided for Scala & Java 8 • Formerly known as Spray
  • 9. Akka HTTP Model Concept Description Http Provides helpers to create the streams for processing server responses or client requests (http or https supported) HttpRequest HTTP request. Requires at least an URI to instantiate and will default to method GET; can choose alternate HttpMethod and attach Headers and a request entity HttpResponse Contains information related to the HTTP response, including content types, headers, status code and response entity if applicable. HttpEntity Represents the body of the request or response as a Source[ByteString, Any]; commonly un- marshalled to the desired type; Stream is processed asynchronously! Headers Strongly typed instances of all known HTTP 1.1 headers; Custom headers can be added by extending appropriate API; no simple string headers! (error prone) ContentTypes Strongly typed instances of all commonly used ContentTypes; as with headers, custom ContentTypes can be registered with the system; no simple string values MediaTypes Strongly typed instances of all commonly used MediaTypes; custom MediaTypes can be registered with the system; no simple string values Un-Marshalling Key to turning your request/response entities to/from bytes for transport by the system. Out of the box support for basics (i.e. String); modules add support for others (i.e. JSON) RequestContext Wraps the HttpRequest and provides other helpers for working with requests
  • 11. There is a better way… • Routing DSL to the rescue… • (Example)
  • 12. Akka HTTP - Routes • Server side code simplified with Routes • A route is an alias for a function that turns a RequestContext into a RouteResult • type Route = RequestContext => Future[RouteResult] • A route can do the following when it receives a request: • complete the request • reject the request (I don’t handle this request) • fail the request (an actual error has occurred) • do any type of asynchronous processing and return a Future[RouteResult]
  • 13. Akka HTTP - The Routing Tree • Routes can be composed to build a tree • Three basic operations • transformation - delegates to an inner route, but changes some property of the request or response before it hands it off • filtering - only processes routes satisfying some criteria; rejects all others • chaining - tries a second route if the first was rejected • ~ is the chaining operator • put most specific cases up front, general cases in the back (i.e. route 3 is a ‘catch all’ route)
  • 14. Akka HTTP - Directives • Directive is a building block for a route • akka-http provides a number of pre-defined directives • Custom directives can be built by composing existing directives with operators or by extending the API • form: name(args) { extractions => // inner route } Operator Purpose Example ~ chain val route = a {} ~ b{} ~ c{} | or val getOrPut = get | put & and val getFoo = path(“foo”) & get
  • 15. Akka HTTP - Commonly Used Directives Directive Description path(pm : PathMatcher) Matches the given path give the pattern in the PathMatcher get, put, post, delete, head, patch Common HTTP Methods complete Completes a request; does not handle Futures onComplete, onSuccess Completes a request and handles Futures extract* Extract various parts of the HttpResponse.. i.e. extractClientIP, extractHost, etc. reject Rejects a route with a specific Rejection entity the HTTP Request entity; will un-marshall it to the given type. authenticate* Numerous directives to support various types of HTTP authentication, ie. OAuth2, Basic. parameters Extract values for vary query parameters
  • 16. Akka HTTP Examples • Simple Routing DSL Example • HTTP Microservice Example • Simple Client Side GET • Simple Client Side POST
  • 17. Akka HTTP RouteTestkit • If you build with the Routing DSL, use the test kit to validate that it works as expected! • ScalaTest based • Makes use of the RequestBuilder to quickly build up tests for your routes • Example…
  • 18. Akka HTTP - Much More! • There’s a lot more… • Custom Marshalling/Un-marshalling • Case class extractions & validation • Custom Headers (i.e X-CUSTOM…) • Custom ContentTypes/MediaTypes • Custom Rejection Handlers • HTTPS • WebSockets (client and server) • Stand-Alone HTTP Layer Usage (Bidi)