akka-http 文档提供了一个查询 http 服务的示例:
http://doc.akka.io/docs/akka-http/current/scala/http/client-side/request-level.html
我如何告诉 akka-http 自动遵循重定向,而不是接收代码 == 302 的 HttpResponse?
akka 2.5.3、akka-http 10.0.9
import akka.actor.{ Actor, ActorLogging }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.{ ActorMaterializer, ActorMaterializerSettings }
import akka.util.ByteString
class Myself extends Actor
with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))
val http = Http(context.system)
override def preStart() = {
http.singleRequest(HttpRequest(uri = "http://akka.io"))
.pipeTo(self)
}
def receive = {
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body =>
log.info("Got …Run Code Online (Sandbox Code Playgroud) 如何修复 Akka HTTP 中增加最大方法长度的问题。我在网络套接字连接服务中遇到以下问题。
\n\nIllegal request, responding with status \'400 Bad Request\': Unsupported\n HTTP method: HTTP method too long (started with \'\xef\xbf\xbc\xef\xbe\x92\xef\xbe\xbfvN\'). Increase \n`akka.http.server.parsing.max-method-length` to support HTTP methods with more characters.\nRun Code Online (Sandbox Code Playgroud)\n\n我已在application.conf中添加了akka.http.server.parsing.max-method-length。\n添加max-method-length后也遇到了同样的问题,我的 .conf 文件是:
\n\n app {\n interface = "0.0.0.0"\n port = 7000\n}\n\n# Cors allowed origin configuration\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ncors {\n allowed-origin = "http://127.0.0.1"\n}\n\n\nakka {\n http {\n server.parsing.illegal-header-warnings = off\n client.parsing.illegal-header-warnings = off\n }\n}\nakka.http.server.parsing.max-method-length =500\nRun Code Online (Sandbox Code Playgroud)\n 所以,我有这门课:
case class Something[T](data: Option[T] = None)
Run Code Online (Sandbox Code Playgroud)
我按照https://github.com/spray/spray-json和https://doc.akka.io/docs/akka-http/current/common/json-support.html 中的说明注册它。像这样:
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
trait InternalJsonFormat extends SprayJsonSupport with DefaultJsonProtocol {
import spray.json._
implicit def somethingFormat[A :JsonFormat] = jsonFormat1(Something.apply[A])
}
Run Code Online (Sandbox Code Playgroud)
最后我complete从 akka http 指令中使用。像这样:
import akka.http.scaladsl.server.Directives._
object ResponseIt extends InternalJsonFormat {
def apply[T](rawData: T) = {
val theResponse = Something(data = Some(rawData))
complete(theResponse)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在complete(theResponse). 它说
Type mismatch, expected: ToResponseMarshallable, actual: Something[T]
Run Code Online (Sandbox Code Playgroud)
================================================== ==========
我尝试编辑最后的代码以进行调试,如下所示:
object ResponseIt extends InternalJsonFormat {
import spray.json._ …Run Code Online (Sandbox Code Playgroud) 我有 URI 列表,我想请求每个 URI,中间有 1 秒的延迟。我怎样才能做到这一点?
val uris: List[String] = List()
// How to make these URIs resolve 1 second apart?
val responses: List[Future[Response]] = uris.map(httpRequest(_))
Run Code Online (Sandbox Code Playgroud) 我有一系列看起来像的路径;
path("slides" / Segment) { segment =>
getFromDirectory(s"${cfg.slidesDir}/$segment")
} ~
path("foo" / Segment) { segment =>
getFromDirectory(s"${cfg.mypyPursDir}/$segment")
} ~
path("foo" / "images" / Segment) { segment =>
getFromDirectory(s"${cfg.mypyPursImageDir}/$segment")
}
Run Code Online (Sandbox Code Playgroud)
在某些运行时条件下,其中一些可能不处于活动状态(例如生产系统与开发系统)。如何实现这一条件?例如,我可以想象如果存在一条没有执行任何操作的“虚拟路径”,则使用 if-else 对其进行编码。
我使用此示例代码客户端连接到我的 websocket 服务,但目前它只是连接然后关闭。
我怎样才能保持这个连接打开并且永远不会关闭它?
一旦建立连接,我希望它保持打开状态,直到我关闭应用程序。
package docs.http.scaladsl
import akka.actor.ActorSystem
import akka.Done
import akka.http.scaladsl.Http
import akka.stream.scaladsl._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws._
import scala.concurrent.Future
object WebSocketClientFlow {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
import system.dispatcher
// Future[Done] is the materialized value of Sink.foreach,
// emitted when the stream completes
val incoming: Sink[Message, Future[Done]] =
Sink.foreach[Message] {
case message: TextMessage.Strict =>
println(message.text)
case _ =>
// ignore other message types
}
// send this as a message over the …Run Code Online (Sandbox Code Playgroud) 我只是想使用 akka 在 scala 项目中实现一个小示例 REST 端点。代码如下
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import scala.io.StdIn
import scala.concurrent.ExecutionContextExecutor
object ViewAPI :
@main def run(): Unit = {
implicit val system = ActorSystem(Behaviors.empty, "my-system")
implicit val executionContext = system.executionContext
val route =
path("hello") {
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
}
}
val bindingFuture = Http().newServerAt("localhost", 9001).bind(route)
}
Run Code Online (Sandbox Code Playgroud)
我的 sbt 文件如下所示:
libraryDependencies += ("com.typesafe.akka" %% "akka-http" % "10.2.9").cross(CrossVersion.for3Use2_13)
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.6.19"
libraryDependencies += "com.typesafe.akka" …Run Code Online (Sandbox Code Playgroud) 我正在为应用程序使用akka http 2.0.3,并希望使用Web套接字。我希望能够将消息从服务器推送到客户端,而不必先接收消息。因此,我正在查看UpgradeToWebsocket特性,看起来使用'handleMessagesWithSinkSource'是正确的选择。现在,为了推送消息,我希望有一个actor连接到传递到'handleMessagesWithSinkSource'方法的源。但是,当使用'Source.actorRef'方法时,似乎仅在流运行时才生成actor,这将在'handleMessagesWithSinkSource'方法中。
因此,我的问题是,如何将消息(最好是通过演员)推送到网络套接字通道?
我正在尝试使用流而不是纯粹的actor来处理http请求,我带来了以下代码:
trait ImagesRoute {
val log = LoggerFactory.getLogger(this.getClass)
implicit def actorRefFactory: ActorRefFactory
implicit def materializer: ActorMaterializer
val source =
Source
.actorRef[Image](Int.MaxValue, OverflowStrategy.fail)
.via(Flow[Image].mapAsync(1)(ImageRepository.add))
.toMat(Sink.asPublisher(true))(Keep.both)
val route = {
pathPrefix("images") {
pathEnd {
post {
entity(as[Image]) { image =>
val (ref, publisher) = source.run()
val addFuture = Source.fromPublisher(publisher)
val future = addFuture.runWith(Sink.head[Option[Image]])
ref ! image
onComplete(future.mapTo[Option[Image]]) {
case Success(img) =>
complete(Created, img)
case Failure(e) =>
log.error("Error adding image resource", e)
complete(InternalServerError, e.getMessage)
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是正确的方法,或者即使这是一个很好的方法,或者如果我应该使用actor与路径交互,使用ask模式然后在actor内部,流式传输所有内容.
有任何想法吗?
我正在尝试为我们的akka http应用程序使用客户端连接池。但是,一旦达到最大连接数,请求似乎就会挂起。我将问题归结为以下几点:
import java.lang.Thread.UncaughtExceptionHandler
import java.net.ServerSocket
import akka.actor.ActorSystem
import akka.http.scaladsl.settings.ConnectionPoolSettings
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import akka.http.scaladsl.client.RequestBuilding._
import scala.annotation.tailrec
import scala.util.{Success, Try}
object AkkaProblem extends App {
val server = new ServerSocket(0)
val serverPort = server.getLocalPort
object responder extends Runnable with UncaughtExceptionHandler {
val cr = '\r'
val httpResponse =
s"""HTTP/1.1 404 Not Found$cr
|Content-Type: application/json;charset=UTF-8$cr
|Date: Mon, 26 Sep 2016 06:30:13 GMT$cr
|Connection: keep-alive$cr
|Transfer-Encoding: chunked$cr
|$cr
|12$cr
|{"Hello": "World"}$cr
|0$cr …Run Code Online (Sandbox Code Playgroud) akka-http ×10
scala ×8
akka ×7
akka-stream ×5
websocket ×2
generics ×1
scala-3 ×1
spray-json ×1