AkkA HTTP Service Demo

Source: Internet
Author: User

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") implic It val Materializer = Actormaterializer ()//needed for the future flatmap/oncomplete in the end implicit Val executionc Ontext = system.dispatcher//implicit def Myexceptionhandler:exceptionhandler = exceptionhandler {case E:exc Eption = 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 (). GE Tstring ("Server.interface") val port = Config (). GetInt ("Server.port")//logs just the request method and response Statu S at info level def requestmethodandresponsestatusasinfo (req:httprequest): Routeresult = Option[logentry] = {CAs E routeresult.complete (res) = Some (LogEntry ("Method:" +req.method.name+ "\nurl:" +req.uri + "\ n" +req.hea Ders.head + "\nbody:" +req.entity + "\nstatus:" + res.status+ "\nresult:" +res.entity, Logging.infolevel ) Case _ + None//No log entries for rejections} val clientroutelogged = Logrequestres Ult (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 (_ = Syst Em.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") {(Pat H ("Hello") & get) {parameters ("flag", "option") {(flag,option) =>{var w = 1000+ (Math.ran            Dom () *500). ToInt if (option.toint% 7 ==0) {w+= ((Math.random () *1000). toint+1500)} if (option== "10000") {Thread.Sleep (+) Complete ("AAAAA")}else{Th      Read.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 JsonF      Ormat[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] = Jsarr Ay (l.tovector.map (v = write (v))) case m:map[string, any] + = {Jsobject (M.map {case (k, v) + = (k, W  Rite (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 Jsar Ray (Xs:vector[jsvalue]) = xs.toList.map {x = Read (x)} case Jsobject (fields:map[string, jsvalue]) = = Fi Elds.map {case (k, jsv) = (k, read (JSV))}}}}

  

AkkA HTTP Service Demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.