我正在尝试将http客户端连接到服务器公开的http服务,源应该每1秒发送一次请求,因为我已经创建了以下部分图表:
def httpSourceGraph() = {
Source.fromGraph(GraphDSL.create() { implicit builder =>
val sourceOutLet = builder.add(Source.tick(FiniteDuration(0, TimeUnit.SECONDS), FiniteDuration(1,
TimeUnit.SECONDS),
HttpRequest(uri ="/test", method = HttpMethods.GET))).out
// expose outlet
SourceShape(sourceOutLet)
})
}
def httpConnFlow() = {
Flow.fromGraph(GraphDSL.create() { implicit builder =>
val httpSourceFlow = builder.add(Http(system).outgoingConnection(host = "localhost", port = 8080))
FlowShape(httpSourceFlow.in, httpSourceFlow.out)
})
}
图表由
组成val response= httpSourceGraph.via(httpConnFlow()).runForeach(println)
如果http服务器(localhost:8080 / test)启动并运行,一切正常,每1秒我就能看到从服务器返回的响应。如果服务器出现故障或以后发生故障,我无法做出任何响应。
我认为它应该给我以下错误:
akka.stream.StreamTcpException:Tcp命令[Connect(localhost / 127.0.0.1:8080,None,List(),Some(10秒),true)]失败
这也可以测试一些错误的网址。 (域名stackoverflow1.com和错误的网址" / test")
感谢您的帮助。
-Arun
答案 0 :(得分:2)
我可以提出一种方法来获得您正在寻求的行为。我认为问题的核心是Flow
生成的Http().outgoingConnection
将在遇到失败时终止。一旦发生这种情况,就不再有下游需求从Source
提取请求,整个流程停止。如果您想要一些将继续发出下游元素的内容,无论连接是否丢失,您都可以尝试使用主机连接池而不是单个连接。对于具有单独连接的故障,该池将更具弹性,并且它还可以从get get设置为发送Success
或Failure
下游。使用主机连接池的流的简化版本可以定义如下:
val source =
Source.tick(
1 second,
5 second,
(HttpRequest(uri ="/", method = HttpMethods.GET), 1)
)
val connFlow = Http(system).
newHostConnectionPool[Int](host = "www.aquto.com", port = 80)
val sink = Sink.foreach[(util.Try[HttpResponse], Int)]{
case (util.Success(r), _ ) =>
r.entity.toStrict(10 seconds)
println(s"Success: ${r.status}")
case (util.Failure(ex), _) =>
println(s"Failure: ${ex.getMessage}")
}
source.via(connFlow).to(sink).run
我测试了这一点,在测试过程中拔掉了我的网络连接,这就是我看到的输出:
Success: 200 OK
Success: 200 OK
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Success: 200 OK
Success: 200 OK