当前位置: 首页>>代码示例>>Scala>>正文


Scala IndexedSeq类代码示例

本文整理汇总了Scala中scala.collection.immutable.IndexedSeq的典型用法代码示例。如果您正苦于以下问题:Scala IndexedSeq类的具体用法?Scala IndexedSeq怎么用?Scala IndexedSeq使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了IndexedSeq类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: DBAccessWorker

//设置package包名称以及导入依赖的类
package domain

import java.sql.{Connection, ResultSet, Statement}

import scala.collection.immutable.IndexedSeq

case class DBAccessWorker(connection: Connection, sql: String) {

  private def execute(execSql: String) = {
    val stmt: Statement = connection.createStatement
    val rs: ResultSet = stmt.executeQuery(execSql)
    val columnCnt: Int = rs.getMetaData.getColumnCount

    val columns: IndexedSeq[String] = 1 to columnCnt map rs.getMetaData.getColumnName
    val results: Iterator[IndexedSeq[String]] = Iterator.continually(rs).takeWhile(_.next()).map{ rs =>
      columns map rs.getString
    }

    (columns, results)
  }

  def execute(): SqlResults = {
    val (d1, d2) = execute(sql)
    SqlResults(d1, d2)
  }

  def executeStatistics(): Statistics = {
    val (d1, d2) = execute(s"EXPLAIN $sql")
    Statistics(d1, d2)
  }
}

case class SqlResults(columns: IndexedSeq[String], results: Iterator[IndexedSeq[String]])

case class Statistics(columns: IndexedSeq[String], results: Iterator[IndexedSeq[String]]) 
开发者ID:miya5n,项目名称:miyalikejdbc,代码行数:36,代码来源:DBAccessWorker.scala

示例2: BaseStationSource

//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.collector.streams

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Framing, Source, Tcp }
import akka.util.ByteString
import com.darienmt.airplaneadventures.basestation.collector.parsing.MessageParser
import com.darienmt.airplaneadventures.basestation.data.BaseStation.Message

import scala.collection.immutable.IndexedSeq

object BaseStationSource {

  def apply(address: String, port: Int)(implicit actorSystem: ActorSystem): Source[Message, NotUsed] =
    Source(IndexedSeq(ByteString.empty))
      .via(
        Tcp().outgoingConnection(address, port)
          .via(Framing.delimiter(ByteString("\n"), 256, allowTruncation = true))
          .map(_.utf8String)
      )
      .map(MessageParser(_))

} 
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:24,代码来源:BaseStationSource.scala

示例3: VerticalBoxBlurRunner

//设置package包名称以及导入依赖的类
package scalashop

import org.scalameter._
import common._

import scala.collection.immutable.IndexedSeq

object VerticalBoxBlurRunner {

  val standardConfig = config(
    Key.exec.minWarmupRuns -> 5,
    Key.exec.maxWarmupRuns -> 10,
    Key.exec.benchRuns -> 10,
    Key.verbose -> true
  ) withWarmer (new Warmer.Default)

  def main(args: Array[String]): Unit = {
    val radius = 3
    val width = 1920
    val height = 1080
    val src = new Img(width, height)
    val dst = new Img(width, height)
    val seqtime = standardConfig measure {
      VerticalBoxBlur.blur(src, dst, 0, width, radius)
    }
    println(s"sequential blur time: $seqtime ms")

    val numTasks = 32
    val partime = standardConfig measure {
      VerticalBoxBlur.parBlur(src, dst, numTasks, radius)
    }
    println(s"fork/join blur time: $partime ms")
    println(s"speedup: ${seqtime / partime}")
  }

}


  def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
    type stripe = (Int, Int)
    val numColinStripe: Int = math.ceil(src.width / numTasks.toDouble).toInt
    val stripes: IndexedSeq[stripe] = (0 until src.width) map { s =>
      if (s + numColinStripe >= src.width) (s, src.width)
      else (s, s + numColinStripe)
    }
    val tasks = stripes.map(s => (task {blur(src, dst, s._1, s._2, radius)}))
    tasks.foreach(_.join)
  }
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:50,代码来源:VerticalBoxBlur.scala

示例4: Main

//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.rawcollector

import java.net.InetSocketAddress

import akka.Done
import akka.io.Inet.SocketOption
import akka.kafka.ProducerSettings
import akka.kafka.scaladsl.Producer
import akka.stream.scaladsl.{ Framing, Source, Tcp }
import akka.util.ByteString
import com.darienmt.keepers.{ Generator, KeepThisUp, MainCommons }
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.serialization.{ ByteArraySerializer, StringSerializer }

import scala.collection.immutable
import scala.collection.immutable.IndexedSeq
import scala.util.Success
import scala.concurrent.duration._

object Main extends App with MainCommons {

  implicit def asFiniteDuration(d: java.time.Duration): FiniteDuration =
    scala.concurrent.duration.Duration.fromNanos(d.toNanos)

  val bsAddress = config.getString("station.address")
  val bsPort = config.getInt("station.port")
  val connectTimeout: Duration = config.getDuration("station.connectTimeout")
  val idleTimeout: Duration = config.getDuration("station.idleTimeout")

  val kafkaAddress = config.getString("kafka.address")
  val kafkaPort = config.getInt("kafka.port")
  val kafkaTopic = config.getString("kafka.topic")


  val generator: Generator = () => Source(IndexedSeq(ByteString.empty))
    .via(
      Tcp().outgoingConnection(
        remoteAddress = InetSocketAddress.createUnresolved(bsAddress, bsPort),
        connectTimeout = connectTimeout,
        idleTimeout = idleTimeout
      )
        .via(Framing.delimiter(ByteString("\n"), 256))
        .map(_.utf8String)
    )
    .map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
    .runWith(
      Producer.plainSink(
        ProducerSettings(system, new ByteArraySerializer, new StringSerializer)
          .withBootstrapServers(s"${kafkaAddress}:${kafkaPort}")
      )
    )

  val keeper = KeepThisUp(config)
  keeper(generator)
} 
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:56,代码来源:Main.scala

示例5: WorkloadsTests

//设置package包名称以及导入依赖的类
package drt.client.services

import drt.shared.FlightsApi._
import drt.shared._
import utest._

import scala.collection.immutable.{IndexedSeq, Map}
import scala.scalajs.js.Date

object WorkloadsTests extends TestSuite {

  def tests = TestSuite {

    "Given workloads, " - {
      "we need a label per minute, starting at midnight of today" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("T1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "it doesn't matter what terminal we have in workloads we need a label per minute" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "the labels are in 24H format" - {
        val firstTime = Date.parse("2016-11-01T14:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.drop(800).take(5)
        assert(labels  == List(
          "13:20", "13:21", "13:22", "13:23", "13:24"
        ))
      }
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:59,代码来源:WorkloadsTests.scala

示例6: SubTermsComputer

//设置package包名称以及导入依赖的类
package ru.ispras.atr.features.occurrences

import ru.ispras.atr.datamodel.TermCandidate

import scala.collection.immutable.IndexedSeq


object SubTermsComputer {
  def computeShorter2longerTerms(candidates: Iterable[TermCandidate], minSubTermSize: Int) = {
    computeShorter2longerCollocations(candidates.map(_.lemmas), minSubTermSize)
  }

  def computeLonger2shorterTerms(candidates: Iterable[TermCandidate], minSubTermSize: Int = 1) = {
    computeLonger2shorterCollocations(candidates.map(_.lemmas), minSubTermSize)
  }

  def computeShorter2longerCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int) = {
    val candidateAndSubCollocations = computeCollocations2SubCollocations(candidates, minSubTermSize)
    val shorter2longerCollocations = new collection.mutable.HashMap[Seq[String], collection.mutable.Set[Seq[String]]]()
      with collection.mutable.MultiMap[Seq[String], Seq[String]]

    candidateAndSubCollocations.foreach(candAndSubCollocation =>
      candAndSubCollocation._2.foreach(st => {
        shorter2longerCollocations.addBinding(st, candAndSubCollocation._1)
      })
    )
    shorter2longerCollocations.toMap
  }

  def computeLonger2shorterCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int = 1) = {
    val candidateAndSubCollocations = computeCollocations2SubCollocations(candidates, minSubTermSize)
    val longer2shorterCollocations = new collection.mutable.HashMap[Seq[String], collection.mutable.Set[Seq[String]]]()
      with collection.mutable.MultiMap[Seq[String], Seq[String]]

    candidateAndSubCollocations.foreach(candAndSubCollocation =>
      candAndSubCollocation._2.foreach(st => {
        longer2shorterCollocations.addBinding(candAndSubCollocation._1, st)
      })
    )
    longer2shorterCollocations.toMap
  }

  def computeCollocations2SubCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int) = {
    val existedTermCandidateReprs = candidates.par.toSet

    val candidateAndSubTerms: Iterable[(Seq[String], IndexedSeq[Seq[String]])] = candidates.par.map(words => {
      val termSubWords = (minSubTermSize until words.size)
        .flatMap(l => words.sliding(l))
      val subTerms = termSubWords.filter(existedTermCandidateReprs.contains)
      (words, subTerms)
    }).seq
    candidateAndSubTerms
  }
} 
开发者ID:ispras,项目名称:atr4s,代码行数:55,代码来源:SubTermsComputer.scala

示例7: CollectionsTest

//设置package包名称以及导入依赖的类
import scala.collection.immutable.IndexedSeq


class CollectionsTest {
  (Map[Char,Int]() /: "misss"){
    (m,c)=>m+(c->(m.getOrElse(c,0)+1))
  }


  "misss"./:(Map[Char,Int]()){
    (m,c)=>m+(c->(m.getOrElse(c,0)+1))
  }

  (1 to 10).scanLeft(0)  (_+_)

  Stream.from(1).take(5).force

  import collection.mutable.SortedSet
  def indexes(s : String) = {
    (s zipWithIndex)./:(Map[Char,SortedSet[Int]]()){
      (m,c)=>m+(c._1->(m.getOrElse(c._1,SortedSet[Int]())+ c._2))
    }
  }

  indexes("Mississippi")

  def getMappingValues(keys:Array[String], kvmap: Map[String,Int]) = {
    keys flatMap (kvmap get _)
  }

  val keys = Array("Tom","Fred","Harry")
  val kvmap = Map("Tom"->3,"Dick"->4,"Harry"->5)
  getMappingValues(keys,kvmap)

  val lst = List(1,2,3,4,5)
  println((lst :\ List[Int]())(_ :: _))
  lst./:(List[Int]())(_ :+ _)
  println((List[Int]() /: lst)((a,b) => b :: a))
}

object CollectionsTest{

  def main(args: Array[String]) {
    val fruit:List[String] = "orange" :: "apple" :: "pear" :: Nil
    fruit map (_ + " ") foreach (print)
    print("\n")
    fruit.map(_ + "   ").foreach(print)
    print("\n")
    fruit.init.foreach(print)
    print("\n")

    val ij:IndexedSeq[(Int, Int)] = for{
      i <- 1 to 5
      j <- 6 to 10
    } yield (i,j)
    ij.foreach(print)
    print("\n")
  }
} 
开发者ID:starqiu,项目名称:LearningScala,代码行数:60,代码来源:CollectionsTest.scala

示例8: Activity

//设置package包名称以及导入依赖的类
package com.bk

import scala.collection.immutable.IndexedSeq
import util.Random
import org.joda.time.DateTime
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import collection.JavaConverters._

object Activity extends App {
  val utf8:Charset = StandardCharsets.UTF_8
  val now = new DateTime()
  val lnow: Long = now.getMillis

  val r = new Random()

  val range = 1 to 10000
  val things: IndexedSeq[String] = range.map(n => {
    val randMillis = r.nextInt(60 * 1000)
    val fakeTime = lnow + randMillis
    s"${r.nextInt(25)} $fakeTime ${"x" * r.nextInt(50)}"
  })


  val lines:List[String] = things.toList
  // This seems to expect java.util.List - use JavaConverter to write list items to the file.
  Files.write(Paths.get("activity.txt"), lines.asJava, utf8)

  lines.foreach(println(_))
} 
开发者ID:bradkarels,项目名称:Activity-Generator,代码行数:33,代码来源:Act.scala

示例9: AuthUser

//设置package包名称以及导入依赖的类
package com.dbrsn.auth.model

import java.time.LocalDateTime

import enumeratum.Enum
import enumeratum.EnumEntry

import scala.collection.immutable.IndexedSeq

case class AuthUser[Provider, Profile, UserId](
  provider: Provider,
  email: Option[String],
  profile: Option[Profile],
  createdAt: LocalDateTime,
  lastLoginAt: Option[LocalDateTime],
  userId: Option[UserId]
)

case class ProviderAuthInfo[Provider, AuthInfo](
  provider: Provider,
  authInfo: AuthInfo
)

case class User[UserId](
  id: Option[UserId],
  active: Boolean,
  mergedToUserId: Option[UserId]
)

case class UserRole[UserId, Role](
  userId: UserId,
  role: Role
)

sealed trait CommonRole extends EnumEntry

object CommonRole extends Enum[CommonRole] {
  override def values: IndexedSeq[CommonRole] = findValues

  case object User extends CommonRole

  case object Admin extends CommonRole

} 
开发者ID:dborisenko,项目名称:generic-auth,代码行数:45,代码来源:model.scala

示例10: Stats

//设置package包名称以及导入依赖的类
package models

import java.time.{LocalDate, OffsetDateTime}

import cats.kernel.Semigroup
import enumeratum._

import scala.collection.immutable.IndexedSeq

object Stats {

  case class CommStats(interacted: Int, opened: Int, delivered: Int)

  case class StatsElement(timestamp: OffsetDateTime, commStats: CommStats)

  object CommStats {
    implicit val commStatsSemigroup = new Semigroup[CommStats] {
      override def combine(x: CommStats, y: CommStats): CommStats = {
        CommStats(
          x.interacted + y.interacted,
          x.opened + y.opened,
          x.delivered + y.delivered
        )
      }
    }
  }

  sealed trait TimePeriod extends EnumEntry {
    def getEndDate(start: LocalDate): LocalDate
  }

  object TimePeriod extends PlayEnum[TimePeriod] {
    case object Week extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusWeeks(1)
    }
    case object Month extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusMonths(1)
    }
    case object Day extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusDays(1)
    }

    override def values: IndexedSeq[TimePeriod] = findValues
  }

} 
开发者ID:ovotech,项目名称:comms-audit-log,代码行数:47,代码来源:Stats.scala

示例11: RoutersPart1CustomRoundRobinRouterSpecExercise

//设置package包名称以及导入依赖的类
package jug.workshops.reactive.akka.routing.exercises

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import common.StopSystemAfterAll
import org.scalatest.{MustMatchers, WordSpecLike}
import jug.workshops.reactive.akka.routing.exercises.RoutersPart1CustomRoundRobinRouterExercise._

import scala.collection.immutable.{IndexedSeq, Seq}

class RoutersPart1CustomRoundRobinRouterSpecExercise extends TestKit(ActorSystem("customRouter"))
with WordSpecLike with MustMatchers with StopSystemAfterAll with ImplicitSender{


  "Custom Round Robin Router" should {
    "route messages to workers in cycles" in {
      val workerProps=Props[CustomWorker]
      val router=system.actorOf(Props(new CustomRouter(5,workerProps)),"customRouter")

      (1 to 10).foreach{_=>
        router ! RoutedJob("someText")
      }

      val results: Seq[AnyRef] =receiveN(10)

      results
        .groupBy(identity)
        .mapValues(_.size).toSeq  must contain allOf(
        "SOMETEXTcustomRouter:worker:1" -> 2,
        "SOMETEXTcustomRouter:worker:2" -> 2,
        "SOMETEXTcustomRouter:worker:3" -> 2,
        "SOMETEXTcustomRouter:worker:4" -> 2,
        "SOMETEXTcustomRouter:worker:5" -> 2
        )
    }
  }

  "Cycle" should {
    "generate cyclic iterator" in {
      val cycle=Cycle.cycleBetween(0,4)

      val result: IndexedSeq[Int] =(1 to 8).map(_ => cycle.next)

      result mustBe  IndexedSeq(0, 1, 2, 3, 0, 1, 2, 3)

    }
  }

} 
开发者ID:PawelWlodarski,项目名称:workshops-reactive,代码行数:50,代码来源:RoutersPart1CustomRoundRobinRouterSpecExercise.scala

示例12: RoutersPart1CustomRoundRobinRouterSpecAnswer

//设置package包名称以及导入依赖的类
package jug.workshops.reactive.akka.routing.answers

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import common.StopSystemAfterAll
import jug.workshops.reactive.akka.routing.answers.RoutersPart1CustomRoundRobinRouterAnswer.{CustomRouter, CustomWorker, Cycle, RoutedJob}
import org.scalatest.{MustMatchers, WordSpecLike}

import scala.collection.immutable.{IndexedSeq, Seq}

class RoutersPart1CustomRoundRobinRouterSpecAnswer extends TestKit(ActorSystem("customRouter"))
with WordSpecLike with MustMatchers with StopSystemAfterAll with ImplicitSender{


  "Custom Round Robin Router" should {
    "route messages to workers in cycles" in {
      val workerProps=Props[CustomWorker]
      val router=system.actorOf(Props(new CustomRouter(5,workerProps)),"customRouter")

      (1 to 10).foreach{_=>
        router ! RoutedJob("someText")
      }

      val results: Seq[AnyRef] =receiveN(10)

      results
        .groupBy(identity)
        .mapValues(_.size).toSeq  must contain allOf(
        "SOMETEXTcustomRouter:worker:1" -> 2,
        "SOMETEXTcustomRouter:worker:2" -> 2,
        "SOMETEXTcustomRouter:worker:3" -> 2,
        "SOMETEXTcustomRouter:worker:4" -> 2,
        "SOMETEXTcustomRouter:worker:5" -> 2
        )
    }
  }

  "Cycle" should {
    "generate cyclic iterator" in {
      val cycle=Cycle.cycleBetween(0,4)

      val result: IndexedSeq[Int] =(1 to 8).map(_ => cycle.next)

      result mustBe  IndexedSeq(0, 1, 2, 3, 0, 1, 2, 3)

    }
  }

} 
开发者ID:PawelWlodarski,项目名称:workshops-reactive,代码行数:50,代码来源:RoutersPart1CustomRoundRobinRouterSpecAnswer.scala

示例13: DecoratedIndexedSeqPair

//设置package包名称以及导入依赖的类
package com.peterpotts

import scala.collection.immutable.IndexedSeq

package object sun {

  implicit class DecoratedIndexedSeqPair[K, V](pairs: IndexedSeq[(K, V)]) {
    def trim: IndexedSeq[(K, V)] = {
      def loop(pairs: IndexedSeq[(K, V)]): IndexedSeq[(K, V)] =
        pairs match {
          case head +: body +: tail =>
            if (head._2 == body._2)
              loop(head +: tail)
            else
              head +: loop(body +: tail)
          case _ => pairs
        }

      loop(pairs)
    }

    def merge(that: IndexedSeq[(K, V)])(implicit ordering: Ordering[K]): IndexedSeq[(K, V)] = {
      def loop(left: IndexedSeq[(K, V)], right: IndexedSeq[(K, V)]): IndexedSeq[(K, V)] =
        left match {
          case leftHead +: leftTail =>
            right match {
              case rightHead +: rightTail =>
                if (ordering.compare(leftHead._1, rightHead._1) < 0)
                  leftHead +: loop(leftTail, right)
                else
                  rightHead +: loop(left, rightTail)
              case _ => left
            }
          case _ => right
        }

      loop(pairs, that)
    }
  }

} 
开发者ID:peterpotts,项目名称:sun,代码行数:42,代码来源:package.scala

示例14: Viz

//设置package包名称以及导入依赖的类
import java.io.{File, PrintWriter}

import Tex.{Footer, Header, texString}

import scala.collection.immutable.IndexedSeq
import scala.collection.mutable.ArrayBuffer
import scala.io.Source


object Viz {
  def main(args: Array[String]): Unit = {
    if (args.length < 2) {
      println("Usage:\njava -jar srl2tex.jar INPUT_PRED INPUT_GOLD\nwhere INPUT_PRED is the file containing the " +
        "output of SRL in compact CoNLL format and INPUT_GOLD are the gold SRL annotations in CoNLL2012 format.")
      System.exit(1)
    }

    val inputPred = args(0)
    val inputGold = args(1)
    val inputPredLines = Source.fromFile(inputPred).getLines()

    val outputTexFile = "output.tex"
    val outTexFile = new PrintWriter(new File(outputTexFile))

    // gold as reference
    val corpusGold = new Conll2012(inputGold)
    corpusGold.load()

    val corpusPred = new ConllPredicted(inputPred)
    corpusPred.load()

    assert(corpusGold.getNWords == corpusPred.getNWords)
    assert(corpusGold.getNPropsBio == corpusPred.getNPropsBio)


    val words: ArrayBuffer[ArrayBuffer[String]] = corpusGold.getWords
    val propsBio: ArrayBuffer[IndexedSeq[ArrayBuffer[String]]] = corpusGold.getPropsBio
    val propsBioPred: ArrayBuffer[IndexedSeq[ArrayBuffer[String]]] = corpusPred.getPropsBio
    val texStrings: IndexedSeq[String] = {
      //for ((ws, ps) <- words.zip(propsBio) if ps.nonEmpty; single_ps <- ps) yield texString(ws, single_ps)
      for (i <- words.indices; j <- propsBio(i).indices) yield texString(words(i), propsBio(i)(j), propsBioPred(i)(j))
    }
    outTexFile.write(Header)
    texStrings.foreach(outTexFile.write)
    outTexFile.write(Footer)
    outTexFile.close()

  }
} 
开发者ID:clips,项目名称:srl2tex,代码行数:50,代码来源:Viz.scala

示例15: SingleNodeAllocationStrategy

//设置package包名称以及导入依赖的类
package com.evolutiongaming.cluster

import akka.actor.{ActorRef, ActorSystem, Address}
import akka.cluster.sharding.ShardRegion
import akka.cluster.sharding.ShardRegion.ShardId

import scala.collection.immutable.IndexedSeq
import scala.concurrent.{ExecutionContext, Future}

class SingleNodeAllocationStrategy(
  address: => Option[Address],
  val maxSimultaneousRebalance: Int,
  val nodesToDeallocate: () => Set[Address])(implicit system: ActorSystem, ec: ExecutionContext)
  extends ExtendedShardAllocationStrategy {

  protected def doAllocate(requester: ActorRef, shardId: ShardId, current: Map[ActorRef, IndexedSeq[ShardId]]) = {
    val activeNodes = notIgnoredNodes(current)
    def byAddress(address: Address) = activeNodes find { actor => actor.path.address == address }
    def requesterNode = byAddress(requester.path.address)
    val address = this.address
    def masterNode = for {
      a <- address
      n <- byAddress(a)
    } yield n
    def leastShards(current: Map[ActorRef, IndexedSeq[ShardId]]) = {
      val (regionWithLeastShards, _) = current minBy { case (_, v) => v.size }
      regionWithLeastShards
    }
    def leastShardActive = {
      val currentActiveNodes = current filterKeys { ref => activeNodes contains ref }
      if (currentActiveNodes.isEmpty) None
      else Some(leastShards(currentActiveNodes))
    }

    val result = masterNode orElse requesterNode orElse leastShardActive getOrElse leastShards(current)

    Future successful result
  }

  protected def doRebalance(
    current: Map[ActorRef, IndexedSeq[ShardId]],
    rebalanceInProgress: Set[ShardId]): Future[Set[ShardRegion.ShardId]]= {
    val result = for {
      address <- address.toIterable filterNot nodesToDeallocate().contains
      (actor, shards) <- current if actor.path.address != address
      shard <- shards
    } yield shard

    Future successful result.toSet -- rebalanceInProgress
  }
} 
开发者ID:evolution-gaming,项目名称:akka-tools,代码行数:52,代码来源:SingleNodeAllocationStrategy.scala


注:本文中的scala.collection.immutable.IndexedSeq类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。