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


Scala ThreadLocalRandom类代码示例

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


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

示例1: Main

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

import java.util.concurrent.ThreadLocalRandom

object Main {
  val txcount = 100000
  
  def main(args : Array[String]) : Unit = {
    val state = Array.ofDim[LazyVar[Int]](100)
    for(i <- 0 until state.length)
      state(i) = new LazyVar(0)
    
    // note: lazy reads do not improve performance in this model, because they must be locked anyway, so they could be read immediately
    // they do improve performance if they can actually be read lazily
    
    while(true) {
      val begin = System.nanoTime()
      for(i <- (0 to txcount).par) {
        val rnd = ThreadLocalRandom.current()
        
        val tx = new Transaction()
        for(i <- 1 to 10)
          tx.update(state(rnd.nextInt(state.size)), (x : Int) => x + 1)
        tx.commit
      }
      val end = System.nanoTime()
      
      val time = (end - begin) / 1000000000.0
      
      println(txcount / time)
    }
  }
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:34,代码来源:Main.scala

示例2: Util

//设置package包名称以及导入依赖的类
package lazytx.benchmark.tpcc

import java.util.concurrent.ThreadLocalRandom

object Util {
  val nameParts = Array("BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI", "CALLY", "ATION", "EING")
  var names = Array.ofDim[String](1000)
  for(i <- 0 to 999) {
    names(i) = genname(i)
  }
  
  def c(a : Int) = rand(0, ThreadLocalRandom.current.nextInt(a))
  
  def rand(a : Int, b : Int) : Int = ThreadLocalRandom.current().nextInt(b - a + 1) + a
  
  def randa(length : Int) : String = {
    var result = new StringBuilder(length)
    val rnd = ThreadLocalRandom.current
    for(i <- 1 to length) {
      result.append(String.valueOf(('a' + rnd.nextInt(26)).toChar))
    }
    result.toString()
  }
  
  def randOriginal() : String = {
    var r = randa(rand(26, 50))
    if(rand(1, 10) == 1) {
      r
    } else {
      val start = r.length() - 8
      r.substring(0, start) + "ORIGINAL" + r.substring(start + 8, r.length)
    }
  }
  
  def nurand(a : Int, x : Int, y : Int) = (((rand(0, a) | rand(x, y)) + c(a)) % (y - x + 1)) + x
  
  def genname(n : Int) = nameParts(n / 100) + nameParts((n / 10) % 10) + nameParts(n % 10)
  
  def name(n : Int) = names(n)
  
  def permutation(count : Int) = {
    var result = Array.ofDim[Int](count)
    val rnd = ThreadLocalRandom.current
    for(i <- 1 to count) {
      result(i - 1) = i
    }
    for(i <- 0 to count - 1) {
      val temp = result(i)
      val s = i + (rnd.nextInt(count - i)).toInt
      result(i) = result(s)
      result(s) = temp
    }
    result
  }
  
  def new_order_key(w_id : Long, d_id : Long, o_id : Long) =
    (w_id << 40) + (d_id << 32) + o_id
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:59,代码来源:Util.scala

示例3: Base

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

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import java.nio.charset.Charset

abstract class Base {
  protected val DH_P = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563"
  protected val DH_G = "02"
  protected val DH_L = 160

  protected val UTF8 = Charset.forName("UTF8");
  protected val KEYA_IV = "keyA".getBytes(UTF8)
  protected val KEYB_IV = "keyB".getBytes(UTF8)
  protected val REQ1_IV = "req1".getBytes(UTF8)
  protected val REQ2_IV = "req2".getBytes(UTF8)
  protected val REQ3_IV = "req3".getBytes(UTF8)
  protected val VC = Array[Byte](0, 0, 0, 0, 0, 0, 0, 0)

  protected val RC4_STREAM_ALG = "RC4";

  protected val DH_P_BI = new BigInteger(DH_P, 16)
  protected val DH_G_BI = new BigInteger(DH_G, 16)

  protected val DH_SIZE_BYTES = DH_P.length() / 2

  protected val CRYPTO_PLAIN: Byte = Plain.id
  protected val CRYPTO_RC4: Byte = RC4.id

  protected val PADDING_MAX = 512

  private def randomPaddingSize: Int = {
    val random = ThreadLocalRandom.current
    Math.abs(random.nextInt % PADDING_MAX)
  }

  protected def randomPadding(): Array[Byte] = {
    val padding = Array.ofDim[Byte](randomPaddingSize)
    val random = ThreadLocalRandom.current
    random.nextBytes(padding)
    padding
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Base.scala

示例4: SessionUtil

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

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import javax.xml.bind.DatatypeConverter

object SessionUtil {
  def randomString(length: Int) = {
    // http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
    val random = ThreadLocalRandom.current()
    new BigInteger(length * 5, random).toString(32) // because 2^5 = 32
  }

  
  def randomServerSecret() = randomString(128)

  // Do not change this unless you understand the security issues behind timing attacks.
  // This method intentionally runs in constant time if the two strings have the same length.
  // If it didn't, it would be vulnerable to a timing attack.
  def constantTimeEquals(a: String, b: String) = {
    if (a.length != b.length) {
      false
    }
    else {
      var equal = 0
      for (i <- Array.range(0, a.length)) {
        equal |= a(i) ^ b(i)
      }
      equal == 0
    }
  }

  def toHexString(array: Array[Byte]): String = {
    DatatypeConverter.printHexBinary(array)
  }

  def hexStringToByte(hexString: String): Array[Byte] = {
    DatatypeConverter.parseHexBinary(hexString)
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:41,代码来源:SessionUtil.scala

示例5: rnd

//设置package包名称以及导入依赖的类
package scaladays.akka.support

import java.util.concurrent.ThreadLocalRandom

import scala.util.Random

trait MakingUpData {

  private def rnd = ThreadLocalRandom.current()

  private def char = rnd.nextInt(65, 91).toChar

  def shortNameId(): String = s"$char$char$char"

  def shortName(): String = s"${char.toUpper}${char.toLower}${char.toLower}${char.toLower}${char.toLower}"

  def lipsum(): String = Random.shuffle(lipsumWords).take(rnd.nextInt(5, 20)).mkString(" ") + "."

  def int(): Int = rnd.nextInt(0, 101)


  val lipsumWords = List(
    "a", "ac", "accumsan", "ad", "adipiscing",
    "aenean", "aliquam", "aliquet", "amet", "ante", "aptent", "arcu",
    "at", "auctor", "augue", "bibendum", "blandit", "class", "commodo",
    "condimentum", "congue", "consectetur", "consequat", "conubia",
    "convallis", "cras", "cubilia", "cum", "curabitur", "curae",
    "cursus", "dapibus", "diam", "dictum", "dictumst", "dignissim",
    "dis", "dolor", "donec", "dui", "duis", "egestas", "eget",
    "eleifend", "elementum", "elit", "enim", "erat", "eros", "est",
    "et", "etiam", "eu", "euismod", "facilisi", "facilisis", "fames",
    "faucibus", "felis", "fermentum", "feugiat", "fringilla", "fusce",
    "gravida", "habitant", "habitasse", "hac", "hendrerit",
    "himenaeos", "iaculis", "id", "imperdiet", "in", "inceptos",
    "integer", "interdum", "ipsum", "justo", "lacinia", "lacus",
    "laoreet", "lectus", "leo", "libero", "ligula", "litora",
    "lobortis", "lorem", "luctus", "maecenas", "magna", "magnis",
    "malesuada", "massa", "mattis", "mauris", "metus", "mi",
    "molestie", "mollis", "montes", "morbi", "mus", "nam", "nascetur",
    "natoque", "nec", "neque", "netus", "nibh", "nisi", "nisl", "non",
    "nostra", "nulla", "nullam", "nunc", "odio", "orci", "ornare",
    "parturient", "pellentesque", "penatibus", "per", "pharetra",
    "phasellus", "placerat", "platea", "porta", "porttitor", "posuere",
    "potenti", "praesent", "pretium", "primis", "proin", "pulvinar",
    "purus", "quam", "quis", "quisque", "rhoncus", "ridiculus",
    "risus", "rutrum", "sagittis", "sapien", "scelerisque", "sed",
    "sem", "semper", "senectus", "sit", "sociis", "sociosqu",
    "sodales", "sollicitudin", "suscipit", "suspendisse", "taciti",
    "tellus", "tempor", "tempus", "tincidunt", "torquent", "tortor",
    "tristique", "turpis", "ullamcorper", "ultrices", "ultricies",
    "urna", "ut", "varius", "vehicula", "vel", "velit", "venenatis",
    "vestibulum", "vitae", "vivamus", "viverra", "volutpat",
    "vulputate"
    )
} 
开发者ID:ktoso,项目名称:scaladays-berlin-akka-streams,代码行数:56,代码来源:MakingUpData.scala

示例6: BbcId

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

import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

object BbcId {

  import java.util.concurrent.ThreadLocalRandom

  def register(pageToReturnTo: String = "/") = {

    val encodedPageToReturnTo = java.net.URLEncoder.encode(pageToReturnTo, "UTF-8")

    exec(_.set("email", s"[email protected]${ThreadLocalRandom.current.nextInt(Int.MaxValue)}.com"))
    .exec(http("getBbcIdRegister")
    .get("/id/register"))
    .exec(http("postBbcIdRegister")
    .post("/id/register?ptrt=" + encodedPageToReturnTo)
      .formParam("email", "${email}")
      .formParam("confirmpassword", "wwtest")
      .formParam("confirmpassword_confirm", "wwtest")
      .formParam("personalisedupdates", "0")
      .formParam("personalisedupdates", "1")
      .formParam("bbcid_submit_button", "Register")
      .check(status is 200, css("#orb-modules h2") is "Your registration is complete"))
  }

  def signIn(pageToReturnTo: String = "/",
              validation: String = "Welcome to the BBC") = {

    val encodedPageToReturnTo = java.net.URLEncoder.encode(pageToReturnTo, "UTF-8")

    val feeder = csv("bbcid/bbcid_emails.txt").circular

    feed(feeder)
    .exec(http("getBbcIdSignIn")
    .get("/id/signin"))
    .exec(http("postBbcIdSignIn")
    .post("/id/signin?ptrt=" + encodedPageToReturnTo)
      .formParam("unique", "${email}")
      .formParam("password", "loadtest")
      .formParam("rememberme", "1")
      .check(status is 200, substring(validation)))

  }

} 
开发者ID:narlas01,项目名称:Mirrored,代码行数:50,代码来源:BbcId.scala

示例7: ComputerWorld

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

import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

import java.util.concurrent.ThreadLocalRandom

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(10 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:narlas01,项目名称:Mirrored,代码行数:44,代码来源:ComputerWorld.scala

示例8: random

//设置package包名称以及导入依赖的类
package com.github.jeroenr.tepkin.util

import java.util.concurrent.ThreadLocalRandom

trait Randomizer {

  def random: ThreadLocalRandom = ThreadLocalRandom.current()

  def randomString(alphabet: String)(n: Int): String = {
    Stream.continually(random.nextInt(alphabet.size)).map(alphabet).take(n).mkString
  }

  def randomString(n: Int): String = {
    randomString {
      """!"#$%&'()*+-./0123456789:;<=>[email protected][\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
    }(n)
  }
} 
开发者ID:dgouyette,项目名称:tepkin,代码行数:19,代码来源:Randomizer.scala

示例9: ComputerWorld

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

import scala.concurrent.duration._

import java.util.concurrent.ThreadLocalRandom

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(1 minute)
  ).protocols(httpProtocol)) 
} 
开发者ID:devagorilla,项目名称:gitbucket-load-test,代码行数:44,代码来源:ComputerWorld.scala

示例10: ComputerWorld

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

import scala.concurrent.duration._

import java.util.concurrent.ThreadLocalRandom

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.herokuapp.com")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .contentTypeHeader("application/x-www-form-urlencoded")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computers = http("computers") 
    .get("/computers")
    .check(
      status.is(200),
      regex("""\d+ computers found"""),
      css("#add", "href").saveAs("addComputer"))
    
  val addNewComputer = http("addNewComputer")
    .get("${addComputer}")
    .check(substring("Add a computer"))

  val addNewComputerPost = http("addNewComputerPost") 
    .post("/computers")
    .formParam("name", "${homeComputer}") 
    .formParam("introduced", "2015-10-10") 
    .formParam("discontinued", "2017-10-10") 
    .formParam("company", "") 
    .check(substring("${homeComputer}"))
  
  val computerDatabaseScn = scenario("computerDatabaseScn") 
    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(computers)
    .exec(addNewComputer)
    .exec(addNewComputerPost)
    
  setUp(computerDatabaseScn.inject(
    constantUsersPerSec(2) during(1 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:yabols,项目名称:bbcGatling,代码行数:49,代码来源:ComputerWorld.scala

示例11: sample

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

import java.util.concurrent.ThreadLocalRandom


trait Distribution {
  def sample(): Double
  def getMax(): Double
  def getMin(): Double
}

class SingleValueDistribution(value: Double) extends Distribution {
  override def sample(): Double = value
  override def getMax(): Double = value
  override def getMin(): Double = value
}

class TriangleDistribution(min: Double, likely: Double, max: Double)
        extends Distribution {

  assert(max >= likely)
  assert(likely >= min)

  val fc: Double = (likely - min) / (max - min)

  override def sample(): Double = {
    val u = ThreadLocalRandom.current().nextDouble()
    if (u < fc) {
      min + Math.sqrt(u * (max - min) * (likely - min))
    } else {
      max - Math.sqrt((1 - u) * (max - min) * (max - likely))
    }
  }

  override def getMin(): Double = min

  def getLikely(): Double = likely

  override def getMax(): Double = max

} 
开发者ID:phaller,项目名称:reactive-async,代码行数:42,代码来源:Distribution.scala

示例12: ExponentialBackOff

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

import java.util.concurrent.ThreadLocalRandom

import scala.concurrent.duration.{Duration, FiniteDuration}

object ExponentialBackOff {
  def apply(minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double): ExponentialBackOff =
    new ExponentialBackOff(minBackoff, maxBackoff, randomFactor, 1)
}

case class ExponentialBackOff(protected val minBackoff: FiniteDuration,
                              protected val maxBackoff: FiniteDuration,
                              protected val randomFactor: Double,
                              override val currentAttemptNumber: Int = 1) extends AttemptParams {
  require(minBackoff > Duration.Zero, "minBackoff must be > 0")
  require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff")
  require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0")

  override def nextAttemptDelay: FiniteDuration = {
    val rnd = 1.0 + ThreadLocalRandom.current().nextDouble() * randomFactor
    if (currentAttemptNumber >= 30) {
      // Duration overflow protection (> 100 years)
      maxBackoff
    } else {
      maxBackoff.min(minBackoff * math.pow(2, currentAttemptNumber.toDouble)) * rnd match {
        case f: FiniteDuration ? f
        case _ ? maxBackoff
      }
    }
  }

  override def nextAttemptParams: ExponentialBackOff = {
    copy(currentAttemptNumber = currentAttemptNumber + 1)
  }
} 
开发者ID:snap-swap,项目名称:akka-rescheduler,代码行数:37,代码来源:ExponentialBackOff.scala

示例13: Unique

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

import java.util.concurrent.ThreadLocalRandom

object Unique {
  val LettersLower = "abcdefghijklmnopqrstuvwxyz"
  val LettersUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  val Numbers = "0123456789"
  val LettersAndNumbers = s"$LettersLower$Numbers"
  val AllLettersAndNumbers = s"$LettersLower$LettersUpper$Numbers"

  private def r = ThreadLocalRandom.current()

  
  def poolSize(length: Int = 32, characters: String = AllLettersAndNumbers): Long = {
    math.pow(characters.length, length).toLong
  }
} 
开发者ID:outr,项目名称:hyperscala,代码行数:19,代码来源:Unique.scala

示例14: ComputerWorld

//设置package包名称以及导入依赖的类
import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

import java.util.concurrent.ThreadLocalRandom

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .contentTypeHeader("application/x-www-form-urlencoded")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(1 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:aidylewis,项目名称:gatling-sbt.g8,代码行数:43,代码来源:ComputerWorld.scala

示例15: DeviceRequest

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

import java.util.UUID
import java.util.concurrent.ThreadLocalRandom
import scala.concurrent.duration._
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef

import com.sandinh.paho.akka._
import com.sandinh.paho.akka.MqttPubSub._

object DeviceRequest {
  case object Tick
}

class DeviceRequest(mqttPubSub: ActorRef) extends Actor with ActorLogging {
  import DeviceRequest._
  import context.dispatcher

  def scheduler = context.system.scheduler
  def random = ThreadLocalRandom.current
  def nextWorkId(): String = UUID.randomUUID().toString

  override def preStart(): Unit = scheduler.scheduleOnce(5.seconds, self, Tick)

  // override postRestart so we don't call preStart and schedule a new Tick
  override def postRestart(reason: Throwable): Unit = ()

  def receive = {
    case Tick => {
      // Random pick from a list of serializable devices
      val deviceList: List[Device] = List(new Thermostat, new Lamp, new SecurityAlarm)
      val device = deviceList(random.nextInt(0, deviceList.size))
      val work = Work(nextWorkId(), device, "Adjust device")
      log.info("Device Request -> Device Id {} | Device State {}", device.getId, device.getState)

      val payload = MqttConfig.writeToByteArray(work)

      log.info("Device Request -> Publishing MQTT Topic {}: Device Id {} | Device State {}", MqttConfig.topic, work.device.getId, work.device.getState)

      mqttPubSub ! new Publish(MqttConfig.topic, payload)

      context.become(waitAccepted(work, payload), discardOld = false)
    }
  }

  def waitAccepted(work: Work, payload: Array[Byte]): Actor.Receive = {
    case IotAgent.Ok =>
      context.unbecome()
      scheduler.scheduleOnce(random.nextInt(3, 10).seconds, self, Tick)
    case IotAgent.NotOk =>
      log.info("Device Request -> ALERT: Work Id {} from Device Id {} NOT ACCEPTED, retrying ... ", work.workId, work.device.getId)
      scheduler.scheduleOnce(3.seconds, mqttPubSub, new Publish(MqttConfig.topic, payload))
  }
} 
开发者ID:oel,项目名称:akka-iot-mqtt,代码行数:57,代码来源:DeviceRequest.scala


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