您的位置:首页 > 其它

spray-routing与spray-can例子

2015-09-09 19:46 363 查看
我们利用spray-routing与spray-can监听指定的端口,让后返回指定的类型

记得严格按照spray与scala的版本,具体看官网

name:="demo10"

scalaVersion  := "2.11.6"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

libraryDependencies ++= {
val akkaV = "2.3.9"
val sprayV = "1.3.3"
Seq(
"io.spray"            %%  "spray-can"     % sprayV,
"io.spray"            %%  "spray-routing" % sprayV,
"io.spray"            %%  "spray-testkit" % sprayV  % "test",
"com.typesafe.akka"   %%  "akka-actor"    % akkaV,
"com.typesafe.akka"   %%  "akka-testkit"  % akkaV   % "test",
"org.specs2"          %%  "specs2-core"   % "2.3.11" % "test"
)
}

配置spray service的参数

akka {
loglevel = INFO
}

spray.can.server {
request-timeout = 1s
}


跟定义actor一样,不同的是我们使用被spray重写的Actor.Receive

def runRoute(route: Route)(implicit eh: ExceptionHandler, rh: RejectionHandler, ac: ActorContext,
rs: RoutingSettings, log: LoggingContext): Actor.Receive = {
val sealedExceptionHandler = eh orElse ExceptionHandler.default
val sealedRoute = sealRoute(route)(sealedExceptionHandler, rh)
def runSealedRoute(ctx: RequestContext): Unit =
try sealedRoute(ctx)
catch {
case NonFatal(e) ⇒
val errorRoute = sealedExceptionHandler(e)
errorRoute(ctx)
}

{
case request: HttpRequest ⇒
val ctx = RequestContext(request, ac.sender(), request.uri.path).withDefaultSender(ac.self)
runSealedRoute(ctx)

case ctx: RequestContext ⇒ runSealedRoute(ctx)

case Tcp.Connected(_, _) ⇒
// by default we register ourselves as the handler for a new connection
ac.sender() ! Tcp.Register(ac.self)

case x: Tcp.ConnectionClosed        ⇒ onConnectionClosed(x)

case Timedout(request: HttpRequest) ⇒ runRoute(timeoutRoute)(eh, rh, ac, rs, log)(request)
}
}

我们利用runRoute在指定我们需要返回的内容

class HttpScanAkka extends Actor with MyService {
def actorRefFactory = context
def receive = runRoute(miniRoute)
}

trait MyService extends HttpService {

val miniRoute =
path("") {
get {
respondWithMediaType(`text/html`)  {
complete {
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
}
}
}
}
}

接着我们把相应的actor绑定到指定的port中

[INFO] [09/09/2015 19:33:36.234] [default-akka.actor.default-dispatcher-4] [akka://default/user/IO-HTTP/listener-0] Bound to localhost/127.0.0.1:8080


object ActorTest5 extends App{
implicit val system = ActorSystem()

val httpScanAkkaLis: ActorRef = system.actorOf(Props[HttpScanAkka])

implicit val timeout = Timeout(5.seconds)

IO(Http) ? Http.Bind(httpScanAkkaLis, interface = "localhost", port = 8080)
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: