import akka.actor.{Props, ActorSystem}import akka.event.{LoggingAdapter, Logging}import akka.http.scaladsl.Httpimport akka.http.scaladsl.model._import akka.http.scaladsl.server.{ExceptionHandler, RouteResult}import akka.http.scaladsl.server.RouteResult.Completeimport akka.http.scaladsl.server.directives.{LogEntry, LoggingMagnet, DebuggingDirectives}import akka.stream.ActorMaterializerimport akka.http.scaladsl.server.Directives._import utils.CommonUtilimport scala.concurrent.Futureimport scala.io.StdInimport StatusCodes._/** ?* Created by admin on 2017/12/1. ?*/object Boot extends App with AkkaHttpExampleService{ ?implicit val system = ActorSystem("AkkaHttpExampleSystem") ?implicit val materializer = ActorMaterializer() ?// needed for the future flatMap/onComplete in the end ?implicit val executionContext = system.dispatcher ?// ?implicit def myExceptionHandler: ExceptionHandler = ???ExceptionHandler { ?????case e: Exception => ???????extractUri { uri => ?????????val dateTime = CommonUtil.getCurrentDateTime ?????????System.err.println(s"[ERROR] [$dateTime] URL: $uri") ?????????e.printStackTrace() ?????????complete(HttpResponse(InternalServerError, entity = "Error:"+e.toString)) ???????} ???} ?val interface = Config().getString("server.interface") ?val port = Config().getInt("server.port") ?// logs just the request method and response status at info level ?def requestMethodAndResponseStatusAsInfo(req: HttpRequest): RouteResult => Option[LogEntry] = { ???case RouteResult.Complete(res) => Some(LogEntry( ?????"Method:"+req.method.name+ ?????"\nURL:"+req.uri + ?????"\n"+req.headers.head + ?????"\nbody:"+req.entity + ?????"\nstatus:" + res.status+ ?????"\nresult:"+res.entity, ?????Logging.InfoLevel)) ???case _ ????????????????????????=> None // no log entries for rejections ?} ?val clientRouteLogged = logRequestResult(requestMethodAndResponseStatusAsInfo _)(AkkaHttpExampleRoutes) ?val bindingFuture = Http().bindAndHandle(clientRouteLogged, interface, port) ?println(s"Server online at http://"+interface+":"+port+"/\nPress RETURN to stop...") ?StdIn.readLine() // let it run until user presses return ?bindingFuture ???.flatMap(_.unbind()) // trigger unbinding from the port ???.onComplete(_ => system.terminate()) // and shutdown when done}
AkkaHttpExampleService:
import java.util.Dateimport akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupportimport akka.http.scaladsl.model.headers.RawHeaderimport akka.http.scaladsl.model.{ContentTypes, HttpEntity}import akka.http.scaladsl.server.Directives._import common.ExtendedJsonSupportimport hbase.hbaseRoute/** ?* Created by admin on 2017/12/1. ?*/trait AkkaHttpExampleService extends SprayJsonSupport with ExtendedJsonSupport with hbaseRoute{ ?val AkkaHttpExampleRoutes = respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")){ ???pathPrefix("hank"){ ?????(path("hello") & get){ ???????parameters("flag","option") { ?????????(flag,option)=>{ ???????????var w = 1000+(Math.random()*500).toInt ???????????if(option.toInt % 7 ==0){ ?????????????w+=((Math.random()*1000).toInt+1500) ???????????} ???????????if(option=="10000"){ ?????????????Thread.sleep(100) ?????????????complete("aaaaa") ???????????}else{ ?????????????Thread.sleep(w) ?????????????complete(w.toString) ???????????} ?????????} ???????} ?????}~(path("hello") & post){ ??????entity(as[List[Map[String,String]]]){ ????????data=>{ ??????????complete{ ????????????data.map(_.getOrElse("flag","sdfsf")).mkString(",") ??????????} ????????} ??????} ?????}~HBaseRouteReport ???} ?}}
ExtendedJsonSupport:
package common/** ?* Created by admin on 2017/12/1. ?*/import spray.json._trait ExtendedJsonSupport extends DefaultJsonProtocol { ?implicit object AnyJsonFormat extends JsonFormat[Any] { ???def write(x: Any): JsValue = x match { ?????case null => JsNull ?????case n: Int => JsNumber(n) ?????case s: String => JsString(s) ?????case b: Boolean => if (b) JsTrue else JsFalse ?????case l: List[Any] => JsArray(l.toVector.map(v => write(v))) ?????case m: Map[String, Any] => { ???????JsObject(m.map { case (k, v) => (k, write(v)) }) ?????} ???} ???def read(value: JsValue): Any = value match { ?????case JsNull => null ?????case JsNumber(n) => n.intValue() ?????case JsString(s) => s ?????case JsTrue => true ?????case JsFalse => false ?????case JsArray(xs: Vector[JsValue]) => xs.toList.map { x => read(x) } ?????case JsObject(fields: Map[String, JsValue]) => fields.map { case (k, jsv) => (k, read(jsv)) } ???} ?}}
AkkA HTTP service demo
原文地址:http://www.cnblogs.com/hsh0756232/p/8057827.html