如何限制发送给Akka中的IO(Tcp)参与者的消息

时间:2019-03-21 14:21:42

标签: scala io akka actor

我有这样的演员

class TcpClientActor(target: Target) extends Actor with Logger {

  override def preStart(): Unit = {
    self ! TestConnection
  }

  override def receive: Receive = {
    case TestConnection =>
      IO(Tcp) ! Connect(remoteAddress = new InetSocketAddress(target.endpoint, target.port), localAddress = None, options = Nil, timeout = Some(timeout), pullMode = false)

    case failed@CommandFailed(_: Connect) =>
      info(s"Failure: $target.endpoint:$target.port")
      shutdown()

    case Connected(_, _) =>
      info(s"Success: $target.endpoint:$target.port")
      sender() ! Close
      shutdown()

  }

  def shutdown(): Unit = {
    context stop self
  }
}

我正在遍历具有端点的文件以测试并创建这些参与者之一,其中每一行都是类型Target的构造函数参数。我希望能够限制并行TCP连接的数量以初始化为某个设置的数量,是否可以在Akka中使用内置机制来确保通过立即创建一个TcpClientActor不会使系统过载每行输入并启动套接字连接?

1 个答案:

答案 0 :(得分:1)

我将使用Akka流来限制消息

import scala.concurrent.duration._
import akka.NotUsed
import akka.actor.ActorRef
import akka.stream.{ ActorMaterializer, OverflowStrategy, ThrottleMode }
import akka.stream.scaladsl.{ Sink, Source }

object TcpThrottle {
  def throttler(ratePerSecond: Int, burstRate: Option[Int], bufferSize: Int = 1000)(implicit materializer: ActorMaterializer): ActorRef =
    Source.actorRef(bufferSize = bufferSize, OverflowStrategy.dropNew)
      .throttle(ratePerSecond, 1.second, burstRate.getOrElse(ratePerSecond), ThrottleMode.Shaping)
      .to(Sink.actorRef(IO(Tcp), NotUsed)
      .run()
 }

class TcpClientActor(target: Target) extends Actor with Logger {
  val throttler = TcpThrottle.throttler(1, Some(5))

  // otherwise identical

  def receive: Receive = {
    case TestConnection => throttler ! Connect(remoteAddress = new InetSocketAddress(target.endpoint, target.port), localAddress = None, options = Nil, timeout = Some(timeout), pullMode = false)

    // other cases identical
  }
}

改编自The Akka 2.5 migration guide