How to implement a REST Web Service using Akka?

旧时模样 提交于 2019-11-29 22:18:19

The important thing to realize about Akka is that it's not an all-or-nothing environment. You can, to a large degree, mix and match different libraries to compose the system that makes sense for you. For instance, I have written apps that use Dropwizard fronting a backend which uses Akka, without issue. I have also done the same with Clothesline (implemented in Clojure, but with a Scala wrapper). And later this week, I hope to experiment with using Unfiltered's websocket implementation to sit in front of Akka and a RabbitMQ pipe for feeding near real-time data to the client browsers -- I specifically mention this example because the Unfiltered websocket impl sits on top of Netty rather than a servlet container).

Update: Since having written this answer a few years back, I've begun using Spray exclusively for RESTful development with Akka. While pretty much any JVM REST library can be used, Spray fits very naturally into Akka's actor-based model and the library has clearly reached a level of maturity where it can easily be the default choice. The upcoming integration of Spray into Akka as the new akka-http module is a clear indication of this.

If you want the CODE to do it, then here it is. It took me a bit to really figure out what's going on, because there are a TON of examples, and it's not clear what they are all doing or how to put it all together. Turns out it was more simple than I thought:

package com.nthalk.akkatest

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.camel.Consumer
import akka.camel.Message
import akka.camel.CamelServiceManager

class MyActor extends Actor with Consumer {
  def endpointUri = "jetty:http://localhost:8877/"
  def receive = {
    case msg: Message => { self.reply("State Rest Service: Achieved") }
    case _ => { self.reply("Really, no message?") }
  }
}

object App extends scala.App {
  actorOf[MyActor].start
  CamelServiceManager.startCamelService
}

And my build.sbt looks like:

organization := "com.nthalk"

name := "akkatest"

version := "0.1.0"

resolvers += 
  "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies ++= Seq(
  "org.apache.camel" % "camel-jetty" % "2.9.0",
  "se.scalablesolutions.akka" % "akka-camel" % "1.3.1"
  )

Hope this helps!

For completeness, it seems useful to have a Scalatra example (since the question asked about Scalatra). Here's some example code from the Scalatra Akka Guide:

package com.example.app

import akka.actor.{ActorRef, Actor, Props, ActorSystem}
import akka.dispatch.ExecutionContext
import akka.util.Timeout
import org.scalatra.FutureSupport
import org.scalatra.{Accepted, ScalatraServlet}

class MyActorApp(system:ActorSystem, myActor:ActorRef) extends ScalatraServlet with     FutureSupport {

  protected implicit def executor: ExecutionContext = system.dispatcher

  import _root_.akka.pattern.ask
  implicit val timeout = Timeout(10)

  get("/async") {
    new AsyncResult { def is = myActor ? "Do stuff and give me an answer" }
  }

  get("/fire-forget") {
    myActor ! "Hey, you know what?"
    Accepted()
  }
}

class MyActor extends Actor {
  def receive = {
    case "Do stuff and give me an answer" => sender ! "The answer is 42"
    case "Hey, you know what?" => println("Yeah I know... oh boy do I know")
  }

}

HTTP servlets and the many containers out there is a tried and trusted technology. Akka offers you the choice of its own embedded servlet container, or you can use it with your own.

You can, of course, roll your own web server with Netty, and there's an interesting write-up about this on the web.

Windor C

using akka-http (people also call it spray-2.0) which is based on akka-streams.

I don't know why you are suspicious of using a Servlet container as the base -- it does not really limit your choice in any possible way, it just handles basic HTTP server plumbing. As such, most java service frameworks use servlet API as the basic foundation even if they don't expose that level.

I think DropWizard is a great choice for all kinds of JVM rest services, including ones that use Akka for actual lifting. Besides the obvious reason of its goodness (based on collection of libraries proven to be "JVM's best"), I like it because it helps in areas that many other libs/frameworks leave out: production of metrics, declarative validation; all the while keeping things simple, explicit and understandable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!