AkkA HTTP service demo

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)) }
    }
  }
}

  

转载于:https://www.cnblogs.com/hsh0756232/p/8057827.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值