Scala

Alternating between Spray-servlet and Spray-can

On a server you may want to deploy your application as a war. How to build a war with spray-servlet. Locally it’s easiest to run without an application server.

We include both the spray-servlet and spray-can dependencies:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
name := "sprayApiExample"
 
version := "1.0"
 
scalaVersion := "2.11.6"
 
libraryDependencies ++= {
  val akkaV = "2.3.9"
  val sprayV = "1.3.3"
  Seq(
    "io.spray"            %%  "spray-can"     % sprayV,
    "io.spray"            %%  "spray-servlet" % sprayV,
    "io.spray"            %%  "spray-routing" % sprayV,
    "io.spray"            %%  "spray-json"    % "1.3.1", //has not been updated yet
    "com.typesafe.akka"   %%  "akka-actor"    % akkaV
  )
}
 
//This adds tomcat dependencies, you can also use jetty()
tomcat()

We make a trait with all the common functionality. We extend both SprayApiServlet and SprayApiCan from it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import spray.servlet.WebBoot
import scala.concurrent.duration._
 
trait SprayApi {
  implicit val system = ActorSystem("SprayApiApp")
  val apiActor = system.actorOf(Props[ApiActor], "apiActor")
}
 
//for use with spray-servlet
class SprayApiServlet extends WebBoot with SprayApi {
  override val serviceActor = apiActor
}
 
//for use with spray-can
object SprayApiCan extends App with SprayApi {
  implicit val timeout = Timeout(5.seconds)
  IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)
}
  • You can see the whole example here.
Reference: Alternating between Spray-servlet and Spray-can from our JCG partner Tammo Sminia at the JDriven blog.

Arthur Arts

Arthur Arts is an experienced Enterprise Java software engineer and hands-on Agile Coach and Scrum Master. He has a strong focus on agile engineering principles and practices and loves to share his knowledge and learn from others. He has his own company Coded Value, is a passionate photographer and writes for agilearts.nl.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button