Akka Actors: Need an example to understand some basics

前端 未结 2 1042
我寻月下人不归
我寻月下人不归 2021-01-31 21:10

I\'m tinkering with Akka and need some advice how to implement something specific i have in mind. I want to have an actor which i can send a DownloadFile(URI, File)

2条回答
  •  佛祖请我去吃肉
    2021-01-31 22:03

    Give this a shot; it creates three - but you could configure it to create as many as you like - downloaders, so that three download requests could be processed concurrenty.

    sealed trait DownloaderMessage
    case class DownloadFile(uri: URI, file: File) extends DownloaderMessage
    
    object Downloader {
      val dispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher("pool").build
    }
    
    class Downloader extends Actor {
      self.lifeCycle = Permanent
      self.dispatcher = Downloader.dispatcher
      def receive = {
        case DownloadFile(uri, file) =>
          // do the download
      }
    }
    
    trait CyclicLoadBalancing extends LoadBalancer { this: Actor =>
      val downloaders: List[ActorRef]
      val seq = new CyclicIterator[ActorRef](downloaders)
    }
    
    trait DownloadManager extends Actor {
      self.lifeCycle = Permanent
      self.faultHandler = OneForOneStrategy(List(classOf[Exception]), 5, 5000)
      val downloaders: List[ActorRef]
      override def preStart = downloaders foreach { self.startLink(_) }
      override def postStop = self.shutdownLinkedActors()
    }
    
    class DownloadService extends DownloadManager with CyclicLoadBalancing {
      val downloaders = List.fill(3)(Actor.actorOf[Downloader])
    }
    

提交回复
热议问题