分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

AkkA HTTP service demo

发布时间:2023-09-06 01:31责任编辑:彭小芳关键词:暂无标签
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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved