当我们把Akka-http作为数据库数据交换工具时,数据是以Source[ROW,_]形式存放在Entity里的。很多时候除数据之外我们可能需要进行一些附加的信息传递如对数据的具体处理方式等。我们可以通过Akka-http的raw-header来实现附加自定义消息的传递,这项功能可以通过Akka-http提供的raw-header筛选功能来实现。在客户端我们把附加消息放在HttpRequest的raw header里,如下:

  import akka.http.scaladsl.model.headers._
val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
.addHeader(RawHeader("action","insert:county"))

在这里客户端注明上传数据应插入county表。服务端可以像下面这样获取这项信息:

             optionalHeaderValueByName("action") {
case Some(action) =>
entity(asSourceOf[County]) { source =>
val futofNames: Future[List[String]] =
source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
complete(s"Received rows for $action")
}
case None => complete ("No action specified!")
}

Akka-http通过Credential类的Directive提供了authentication和authorization。在客户端可以用下面的方法提供自己的用户身份信息:

  import akka.http.scaladsl.model.headers._
val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
.addHeader(RawHeader("action","insert:county"))
.addCredentials(BasicHttpCredentials("john", "p4ssw0rd"))

服务端对客户端的身份验证处理方法如下:

  import akka.http.scaladsl.server.directives.Credentials
def myUserPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
credentials match {
case p @ Credentials.Provided(id) =>
Future {
// potentially
if (p.verify("p4ssw0rd")) Some(User(id))
else None
}
case _ => Future.successful(None)
}
} case class User(name: String)
val validUsers = Set("john","peter","tiger","susan")
def hasAdminPermissions(user: User): Future[Boolean] = {
implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
Future.successful(validUsers.contains(user.name))
}

下面是Credential-Directive的使用方法:

         authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
authorizeAsync(_ => hasPermissions(user)) {
withoutSizeLimit {
handleExceptions(postExceptionHandler) {
optionalHeaderValueByName("action") {
case Some(action) =>
entity(asSourceOf[County]) { source =>
val futofNames: Future[List[String]] =
source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
complete(s"Received rows for $action sent from $user")
}
case None => complete(s"$user did not specify action for uploaded rows!")
}
}
}
}
}

下面是本次讨论的示范代码:

客户端:

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.http.scaladsl.Http
import scala.util._
import akka._
import akka.http.scaladsl.common._
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.common.EntityStreamingSupport
import akka.http.scaladsl.model._
import spray.json._ trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends MyFormats {
case class County(id: Int, name: String)
implicit val countyFormat = jsonFormat2(County)
} object HttpClientDemo extends App {
import Converters._ implicit val sys = ActorSystem("ClientSys")
implicit val mat = ActorMaterializer()
implicit val ec = sys.dispatcher implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json() import akka.util.ByteString
import akka.http.scaladsl.model.HttpEntity.limitableByteSource val source: Source[County,NotUsed] = Source( to ).map {i => County(i, s"广西壮族自治区地市县编号 #$i")}
def countyToByteString(c: County) = {
ByteString(c.toJson.toString)
}
val flowCountyToByteString : Flow[County,ByteString,NotUsed] = Flow.fromFunction(countyToByteString) val rowBytes = limitableByteSource(source via flowCountyToByteString) import akka.http.scaladsl.model.headers._
val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
.addHeader(RawHeader("action","insert:county"))
.addCredentials(BasicHttpCredentials("john", "p4ssw0rd")) val data = HttpEntity(
ContentTypes.`application/json`,
rowBytes
) def uploadRows(request: HttpRequest, dataEntity: RequestEntity) = {
val futResp = Http(sys).singleRequest(
request.copy(entity = dataEntity)
)
futResp
.andThen {
case Success(r@HttpResponse(StatusCodes.OK, _, entity, _)) =>
entity.dataBytes.map(_.utf8String).runForeach(println)
case Success(r@HttpResponse(code, _, _, _)) =>
println(s"Upload request failed, response code: $code")
r.discardEntityBytes()
case Success(_) => println("Unable to Upload file!")
case Failure(err) => println(s"Upload failed: ${err.getMessage}") }
} uploadRows(request,data) scala.io.StdIn.readLine() sys.terminate() }

服务端:

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.http.scaladsl.Http
import akka._
import akka.http.scaladsl.common._
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import scala.concurrent._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model._ trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends MyFormats {
case class County(id: Int, name: String)
val source: Source[County, NotUsed] = Source( to ).map { i => County(i, s"中国广东省地区编号 #$i") }
implicit val countyFormat = jsonFormat2(County)
} object HttpServerDemo extends App { import Converters._ implicit val httpSys = ActorSystem("httpSystem")
implicit val httpMat = ActorMaterializer()
implicit val httpEC = httpSys.dispatcher implicit val jsonStreamingSupport = EntityStreamingSupport.json()
.withParallelMarshalling(parallelism = , unordered = false) def postExceptionHandler: ExceptionHandler =
ExceptionHandler {
case _: RuntimeException =>
extractRequest { req =>
req.discardEntityBytes()
complete((StatusCodes.InternalServerError.intValue, "Upload Failed!"))
}
} import akka.http.scaladsl.server.directives.Credentials
def userPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
credentials match {
case p @ Credentials.Provided(id) =>
Future {
// potentially
if (p.verify("p4ssw0rd")) Some(User(id))
else None
}
case _ => Future.successful(None)
}
} case class User(name: String)
val validUsers = Set("john","peter","tiger","susan")
def hasPermissions(user: User): Future[Boolean] = {
implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
Future.successful(validUsers.contains(user.name))
} val route =
path("rows") {
get {
complete {
source
}
} ~
post {
authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
authorizeAsync(_ => hasPermissions(user)) {
withoutSizeLimit {
handleExceptions(postExceptionHandler) {
optionalHeaderValueByName("action") {
case Some(action) =>
entity(asSourceOf[County]) { source =>
val futofNames: Future[List[String]] =
source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
complete(s"Received rows for $action sent from $user")
}
case None => complete(s"$user did not specify action for uploaded rows!")
}
}
}
}
}
}
} val (port, host) = (,"localhost") val bindingFuture = Http().bindAndHandle(route,host,port) println(s"Server running at $host $port. Press any key to exit ...") scala.io.StdIn.readLine() bindingFuture.flatMap(_.unbind())
.onComplete(_ => httpSys.terminate()) }

随机推荐

  1. cAdvisor0.24.1+InfluxDB0.13+Grafana4.0.2搭建Docker1.12.3 Swarm集群性能监控平台

    目录 [TOC] 1.基本概念 ​ 既然是对Docker的容器进行监控,我们就不自己单独搭建cAdvisor.InfluxDB.Grarana了,本文中这三个实例,主要以Docker容器方式运行. 本 ...

  2. iOS富文本

    背景:前些天突然想做一个笔记本功能,一开始,觉得挺简单的呀,一个UITextView,网络缓存也不干了,直接本地NSUserDefault存储,然后完事了,美工,弄几张好看的图片,加几个动画,也就这样 ...

  3. Web安全性测试总结

    一.工具扫描 目前web安全扫描器针对 XSS.SQL injection .OPEN redirect .PHP File Include漏洞的检测技术已经比较成熟. 商业软件web安全扫描器:有I ...

  4. AngularJs的UI组件ui-Bootstrap-Tooltip

    完整案例,参考http://www.cnblogs.com/pilixiami/p/5661600.html <!DOCTYPE html> <html ng-app="u ...

  5. myeclipse部署时An internal error occurred 错误的几种情况

    myecplise上将工程部署到应用下时,经常出现 An internal error occurred during: "Add Deployment". java.lang.N ...

  6. Lu核心库系统结构及输出函数

    Lu核心库系统结构及输出函数 Lu来源于Forcal,可以说,没有Forcal就没有Lu,但学习Lu并不需要了解Forcal. Lu是对Forcal的完善和发展,但与Forcal相比,Lu更简洁实用. ...

  7. Git更新代码到本地

    一段时间没用git,发现一些东西记不住了,这里记一点常用的命令. 正规流程 git status(查看本地分支文件信息,确保更新时不产生冲突) 若出现冲突,会有提示的 git checkout – [ ...

  8. 雷林鹏分享:jQuery EasyUI 表单 - 创建树形下拉框

    jQuery EasyUI 表单 - 创建树形下拉框 树形下拉框(ComboTree)是一个带有下列树形结构(Tree)的下拉框(ComboBox).它可以作为一个表单字段进行使用,可以提交给远程服务 ...

  9. Laravel学习之旅(三)

    视图 一.怎么新建视图: 1.视图默认存放路径:resources/views: 2.laravel模板支持原生的PHP,直接可以在resources/views新建一个PHP文件,例如: index ...

  10. [CF1063F]String Journey

    题意:定义长度为$k$的journey为一个字符串序列$t_{1\cdots k}$,对$\forall i\gt1$满足$t_i$是$t_{i-1}$的严格子串,定义字符串$s$上的journey为 ...