我正在尝试创建一个提供OAuth2令牌的源,并且还负责刷新过期的令牌。 目前我的代码看起来有点像这样
case class Token(expires: Instant = Instant.now().plus(100, ChronoUnit.MILLIS)){
def expired = Instant.now().isAfter(expires)
}
Source
.repeat()
.mapAsync(1){ _ =>
println(" -> token req")
// this fakes an async token request to the token service
Future{
Thread.sleep(500)
println(" <- token resp")
Token()
}
}
.mapAsync(1){ token =>
println(" -> req with token auth")
if(token.expired){
println("!!! Received expired token")
}
// this is the actual call that needs the token
println("making call")
Future{
Thread.sleep(2000)
println(" <- req resp")
"OK"
}
}
.take(2)
.runWith(Sink.ignore)
.recover{case e => ()}
.flatMap{ _ =>
system.terminate()
}
此代码的输出如下所示
root -> token req
root <- token resp
root -> token req
root -> req with token auth
root making call
root <- token resp
root -> token req
root <- token resp
root -> token req
root <- token resp
root -> token req
root <- req resp
root -> req with token auth
root !!! Received expired token
root making call
root <- token resp
root -> token req
root <- token resp
root -> token req
root <- token resp
root <- req resp
root -> req with token auth
root !!! Received expired token
root making call
root ... finished with exit code 0
很明显,这个mapAsync(1)在不期望时会产生需求(预取?)
有两个问题:
那么如何创建一个像这个函数一样的真正拉流?
def tokenSource: () => Future[Token]
答案 0 :(得分:3)
如果你故意试图避免预取和排队,那么我认为scala.collection.immutable.Stream
或Iterator是比akka Stream更好的解决方案。
下面是一个示例实现,可以避免您在问题中列举的陷阱。 (注意:我使用ActorSystem
通过dispatcher
创建ExecutionContext,以防止应用程序在sleep
调用有时间完成之前退出。我正在利用事实上,ActorSystem不会因为main函数到达表达式定义的末尾而关闭。)
import scala.collection.immutable.Stream
import scala.concurrent.Future
object ScalaStreamTest extends App {
case class Token(expires: Long = System.currentTimeMillis() + 100){
def expired = System.currentTimeMillis() > expires
}
val actorSystem = akka.actor.ActorSystem()
import actorSystem.dispatcher
def createToken = Future {
Thread.sleep(500)
println(" <- token resp")
Token()
}
def checkExpiration(token : Future[Token]) = token map { t =>
println(" -> req with token auth")
if(t.expired){println("!!! Received expired token")}
t
}
def makeCall(token : Future[Token]) = token flatMap { t =>
println("making call")
Future {
Thread.sleep(2000)
println(" <- req resp")
"OK"
}
}
val stream = Stream.continually(createToken)
.map(checkExpiration)
.map(makeCall)
.take(2)
.force
}//end object ScalaStreamTest
force
调用是必要的,因为Stream是惰性的,因此在强制之前的所有方法调用(即:连续,映射和采取)也是惰性的。除非调用reducer或通过force明确告知Stream,否则不会对惰性Stream进行计算。
答案 1 :(得分:0)
Akka Streams总是预取以保持管道饱和。
为了获得你想要的东西,我建议你创建一个Source [Token],当旧的Tokens过期而不是请求时,它会发出新的Tokens。然后使用令牌源压缩您的数据源并使用其结果。