import akka.actor.{Props, ActorSystem} import akka.event.{LoggingAdapter, Logging} import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.{ExceptionHandler, RouteResult} import akka.http.scaladsl.server.RouteResult.Complete import akka.http.scaladsl.server.directives.{LogEntry, LoggingMagnet, DebuggingDirectives} import akka.stream.ActorMaterializer import akka.http.scaladsl.server.Directives._ import utils.CommonUtil import scala.concurrent.Future import scala.io.StdIn import 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.Date import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.headers.RawHeader import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.Directives._ import common.ExtendedJsonSupport import 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)) } } } }