定期发送请求

时间:2018-06-06 16:53:21

标签: scala akka-http

您好我正在尝试学习akka-http并为休息api创建一个简单的客户端。我想知道如何定期向休息服务器发送请求。

我有我的简单客户:

object RestClientApp extends App {
  // set up ActorSystem and other dependencies here
  //#main-class
  //#server-bootstrapping
  implicit val system: ActorSystem = ActorSystem()
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  //#server-bootstrapping

  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher

  val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io"))

  responseFuture
    .onComplete {
      case Success(res) => println(res)
      case Failure(_) => sys.error("something wrong")
    }
}

如何每隔x个时间单位发送一个请求并处理响应?

2 个答案:

答案 0 :(得分:1)

自然拟合Akka Streams,构建Akka HTTP。下面的示例使用重复Source每五秒向给定的URI发出一个HTTP请求。物化流打印响应。

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source

import scala.concurrent.duration._

object RestClient {
  def main(args: Array[String]): Unit = {
    implicit val materializer = ActorMaterializer()

    Source
      .repeat(HttpRequest(uri = "http://akka.io"))
      .throttle(1, 5.seconds)
      .mapAsync(1)(Http().singleRequest(_))
      .runForeach(println)
  }
}

答案 1 :(得分:1)

您可以将RestClient定义为actor,并使用actorSystem.schedule来安排actor。

  final def schedule(
    initialDelay: FiniteDuration,
    interval:     FiniteDuration,
    receiver:     ActorRef,
    message:      Any)(implicit
    executor: ExecutionContext,
                       sender: ActorRef = Actor.noSender): Cancellable =

示例,

import akka.actor.{Actor, ActorSystem, Props}

class RestClientActor extends Actor {
  import RestClientActor._
  import scala.util.Success
  import scala.util.Failure
  import akka.http.scaladsl.Http
  import akka.http.scaladsl.model.HttpRequest

  implicit val actorSystem: ActorSystem = context.system
  import context.dispatcher

  override def receive: Receive = {
    case InitiateRequest =>
      Http().singleRequest(HttpRequest(uri = "http://jsonplaceholder.typicode.com/posts")).onComplete {
        case Success(s) => println(s._3)
        case Failure(f) => println(f.getMessage)
      }
  }
}

object RestClientActor {
  case object InitiateRequest
}

object RestClientApp {

  def main(args: Array[String]): Unit = {

    import akka.actor.ActorSystem
    import scala.concurrent.duration._
    import RestClientActor._
    import scala.concurrent.ExecutionContextExecutor

    implicit val system: ActorSystem = ActorSystem()
    implicit val executionContext: ExecutionContextExecutor = system.dispatcher

    val actor = system.actorOf(Props[RestClientActor], "RestClientActor")

    system.scheduler.schedule(1 seconds, 3 seconds, actor, InitiateRequest)

  }
}