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


Scala Agent类代码示例

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


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

示例1: AuthenticationDetails

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

import akka.agent.Agent
import okhttp3.{Request, Response}

import scala.util.Try

package object salesforce {

  case class AuthenticationDetails(access_token: String, instance_url: String)
  case class ErrorResponse(error: String)

  case class SalesforceError(message: String, statusCode: Option[Int])
  case class SalesforceAuthenticationConfig(url: String,
                                            clientId: String,
                                            clientSecret: String,
                                            username: String,
                                            password: String,
                                            client: Request => Try[Response],
                                            authDetailsCache: Agent[Option[AuthenticationDetails]])

} 
开发者ID:ovotech,项目名称:comms-profiles,代码行数:23,代码来源:package.scala

示例2: getObservable

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.util

import akka.agent.Agent
import monix.execution.{Ack, Cancelable, Scheduler}
import monix.reactive._
import monix.reactive.observables.GroupedObservable
import monix.reactive.observers.Subscriber
import monix.reactive.subjects.PublishSubject
import scala.concurrent.{ExecutionContext, Future}

trait ObservablesPartitioner[K, V] {
  def getObservable(key: K): Observable[V]
}

object CachedObservablesPartitioner {
  def fromUngroupedObservable[K, InputV, OutputV](
    observable:      Observable[InputV],
    cacheSizePerKey: Int,
    keySelector:     InputV => K,
    mappingFunction: InputV => OutputV
  )(implicit scheduler: Scheduler): (CachedObservablesPartitioner[K, InputV, OutputV], Cancelable) = {
    val partitioner = new CachedObservablesPartitioner[K, InputV, OutputV](cacheSizePerKey, mappingFunction)
    val cancelable = observable.groupBy(keySelector).subscribe(partitioner)
    (partitioner, cancelable)
  }
}

class CachedObservablesPartitioner[K, InputV, OutputV](
  cacheSizePerKey: Int, mappingFunction: InputV => OutputV
)(implicit ec: ExecutionContext)
  extends Observer[GroupedObservable[K, InputV]] with ObservablesPartitioner[K, OutputV] {

  private val observablesByKey = Agent[Map[K, Observable[OutputV]]](Map.empty)
  private val incomingKeys = PublishSubject[K]()

  def onComplete(): Unit = {
    incomingKeys.onComplete()
  }

  def onError(e: Throwable): Unit = {
    System.err.println(e) // TODO: Better logging?
    incomingKeys.onError(e)
  }

  
  def getObservable(key: K): Observable[OutputV] = {
    observablesByKey.get.getOrElse(
      key,
      incomingKeys.findF(_ == key).flatMap(_ => getObservable(key))
    )
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:53,代码来源:ObservablesPartitioner.scala

示例3: get

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder

import akka.agent.Agent
import java.util.Date
import monix.execution.{Ack, Cancelable, Scheduler}
import monix.reactive._
import monix.reactive.subjects.ConcurrentSubject
import scala.concurrent.{ExecutionContext, Future}
import walfie.gbf.raidfinder.domain._

trait KnownBossesMap {
  def get(): Map[BossName, RaidBoss]
  def newBossObservable(): Observable[RaidBoss]

  
class KnownBossesObserver(
  initialBosses: Seq[RaidBoss]
)(implicit scheduler: Scheduler) extends Observer[RaidInfo] with KnownBossesMap {
  private val agent = Agent[Map[BossName, RaidBoss]](
    initialBosses.map(boss => boss.name -> boss)(scala.collection.breakOut)
  )

  // TODO: Write test for this
  private val subject = ConcurrentSubject.publish[RaidBoss]
  val newBossObservable: Observable[RaidBoss] = subject

  def onComplete(): Unit = ()
  def onError(e: Throwable): Unit = ()
  def onNext(elem: RaidInfo): Future[Ack] = {
    val name = elem.tweet.bossName
    val raidBoss = elem.boss
    if (!agent.get.isDefinedAt(name)) {
      subject.onNext(raidBoss)
    }
    agent.alter(_.updated(name, raidBoss)).flatMap(_ => Ack.Continue)
  }

  def get(): Map[BossName, RaidBoss] = agent.get()
  def purgeOldBosses(
    minDate:        Date,
    levelThreshold: Option[Int]
  ): Future[Map[BossName, RaidBoss]] = {
    agent.alter(_.filter {
      case (name, boss) => boss.lastSeen.after(minDate) || levelThreshold.exists(boss.level >= _)
    })
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:48,代码来源:KnownBossesMap.scala

示例4: translate

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server

import akka.agent.Agent
import com.pastebin.Pj9d8jt5.ImagePHash
import java.awt.image.BufferedImage
import java.net.URL
import javax.imageio.ImageIO
import monix.execution.Scheduler
import monix.reactive._
import monix.reactive.subjects.ConcurrentSubject
import scala.concurrent.{ExecutionContext, Future}
import walfie.gbf.raidfinder.domain._
import walfie.gbf.raidfinder.util.BlockingIO

trait BossNameTranslator {
  import BossNameTranslator.Translation

  def translate(bossName: BossName): Option[BossName]
  def update(latestBosses: Map[BossName, RaidBoss]): Future[Unit]
  def observable(): Observable[Translation]
}

object BossNameTranslator {
  case class Translation(from: BossName, to: BossName)
}


  private def croppedImageFromUrl(url: URL): BufferedImage = {
    // TODO: Use a real HTTP client to get the image
    val image = ImageIO.read(url.openStream())
    image.getSubimage(0, 0, image.getWidth(), image.getHeight() * 3 / 4);
  }

  // This assumes there are only two languages (which is true currently)
  private def findTranslation(newData: TranslationData): Option[BossName] = {
    translationDataAgent.get.values.find { existingData =>
      newData.hash == existingData.hash &&
        newData.language != existingData.language &&
        newData.level == existingData.level
    }.map(_.name)
  }
}

object ImageBasedBossNameTranslator {
  case class TranslationData(name: BossName, level: Int, language: Language, hash: ImageHash)

  case class ImageHash(value: Long) extends AnyVal
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:49,代码来源:BossNameTranslator.scala

示例5: updateAgent

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

import akka.agent.Agent

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.stm.{Ref, atomic}
import scala.concurrent.duration._

object updateAgent extends App {
  implicit val ec =  ExecutionContext.global

  val numberUpdates = Agent(0)
  val count = Ref(5)

  Future {
    for (i <- 0 until 10) {
      println("count() inc ---->>>")
      atomic { implicit txn =>
        count() = count() + 1
      }
      Thread.sleep(50)
    }
  }
  var nrRuns = 0
  val myNumber = atomic { implicit txn => {
    nrRuns += 1
    numberUpdates send (_ + 1)
    count()
    Thread.sleep(100)
    count()
  }}

  println("nrRuns", nrRuns)
  println("myNumber", myNumber)
  Await.ready(numberUpdates.future(), 1 seconds)
  println("numberUpdates", numberUpdates.get)
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:38,代码来源:updateAgent.scala

示例6: Transaction

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

import scala.concurrent.ExecutionContext.Implicits.global
import akka.agent.Agent

import scala.concurrent.Await
import scala.concurrent.stm._
import scala.concurrent.duration._

object Transaction extends App {
  def transfer(from: Agent[Int], to: Agent[Int], amount: Int, toThrow: Boolean): Boolean = {
    // safe & coordinated
    atomic { implicit tnx => {
      if (from.get < amount) false
      else {
        from send (_ - amount)
        if(toThrow) throw new Exception("holy crap")
        to send (_ + amount)
        true
      }
    }}
  }

  def doTransfer(toThrow: Boolean): Unit = {
    val from = Agent(100)
    val to = Agent(20)
    var ok = false
    try {
      ok = transfer(from, to, 50, toThrow)
    } catch {
      case _: Throwable =>
    } finally {
      val f = Await.result(from.future, 1 seconds)
      val t = Await.result(to.future, 1 seconds)
      println(ok, f, t)
    }
  }

  doTransfer(false)

  Thread.sleep(1000)

  doTransfer(true)
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:45,代码来源:Transaction.scala

示例7: AgentExample2

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

import akka.actor.ActorSystem
import akka.agent.Agent

object AgentExample2 extends App {
  implicit val system = ActorSystem("actor-system")
  import system.dispatcher

  val agent1 = Agent(2)

  // monadic
  val agent2 = agent1 map (_ + 1)
  println(agent2.get)

  // monad
  val agent3 = agent2 flatMap(x => Agent(x + 3))
  println(agent3.get)

  system shutdown
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:22,代码来源:AgentExample2.scala

示例8: readRatesFromStdIn

//设置package包名称以及导入依赖的类
package eu.svez.backpressuredemo

import akka.actor.ActorSystem
import akka.agent.Agent
import akka.stream.ActorMaterializer
import kamon.Kamon

import scala.util.Try

trait StreamDemo extends App {

  implicit val system = ActorSystem("stream-demo")
  implicit val executionContext = system.dispatcher
  implicit val materializer = ActorMaterializer()

  Kamon.start()

  val sourceRate = Agent(1)
  val sinkRate = Agent(1)

  scala.sys.addShutdownHook {
    Kamon.shutdown()
    system.terminate()
  }

  def readRatesFromStdIn() = {
    Iterator.continually(io.StdIn.readLine()).foreach {
      case ln if ln.startsWith("source=") =>
        Try(sourceRate.send(ln.replace("source=", "").toInt)).recover {
          case e => println(s"Error: ${e.getMessage}")
        }
      case ln if ln.startsWith("sink=") =>
        Try(sinkRate.send(ln.replace("sink=", "").toInt)).recover {
          case e => println(s"Error: ${e.getMessage}")
        }
      case _ => println("I don't understand")
    }
  }
} 
开发者ID:svezfaz,项目名称:akka-backpressure-scala-central-talk,代码行数:40,代码来源:StreamDemo.scala

示例9: newId

//设置package包名称以及导入依赖的类
package edu.umbc.swe.ol1.cs447.core

import java.security.SecureRandom
import java.util.Base64
import javax.inject.{Inject, Singleton}

import akka.agent.Agent
import com.google.common.hash.{BloomFilter, Funnels}
import models.Posts
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits._
import slick.driver.JdbcProfile

import scala.concurrent.{Future, Promise}


  def newId: Future[String] = {
    for {
      agent <- bloomFilterAgentFuture
      p = Promise[String]()
      _ = agent.send(bloomFilter => {
        val idBytes = genNewId(bloomFilter)
        p.success(Base64.getUrlEncoder.encodeToString(idBytes))
        bloomFilter.put(idBytes)
        bloomFilter
      })
      id <- p.future
    } yield id
  }

  private def genNewId(bloomFilter: BloomFilter[Array[Byte]]): Array[Byte] = {
    Stream continually {
      val bytes = Array.ofDim[Byte](Posts.postIdLengthBytes)
      rand.nextBytes(bytes)
      bytes
    } dropWhile bloomFilter.mightContain
  }.head
} 
开发者ID:umbc-cmcs447-grp,项目名称:rest-api,代码行数:39,代码来源:IdManager.scala

示例10: ServerActor

//设置package包名称以及导入依赖的类
package io.iohk.ethereum.network

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.agent.Agent
import akka.io.Tcp.{Bind, Bound, CommandFailed, Connected}
import akka.io.{IO, Tcp}
import io.iohk.ethereum.utils.{NodeStatus, ServerStatus}
import org.spongycastle.util.encoders.Hex

class ServerActor(nodeStatusHolder: Agent[NodeStatus], peerManager: ActorRef) extends Actor with ActorLogging {

  import ServerActor._
  import context.system

  override def receive: Receive = {
    case StartServer(address) =>
      IO(Tcp) ! Bind(self, address)
      context become waitingForBindingResult
  }

  def waitingForBindingResult: Receive = {
    case Bound(localAddress) =>
      val nodeStatus = nodeStatusHolder()
      log.info("Listening on {}", localAddress)
      log.info("Node address: enode://{}@{}:{}",
        Hex.toHexString(nodeStatus.nodeId),
        localAddress.getAddress.getHostAddress,
        localAddress.getPort)
      nodeStatusHolder.send(_.copy(serverStatus = ServerStatus.Listening(localAddress)))
      context become listening

    case CommandFailed(b: Bind) =>
      log.warning("Binding to {} failed", b.localAddress)
      context stop self
  }

  def listening: Receive = {
    case Connected(remoteAddress, localAddress) =>
      val connection = sender()
      peerManager ! PeerManagerActor.HandlePeerConnection(connection, remoteAddress)
  }
}

object ServerActor {
  def props(nodeStatusHolder: Agent[NodeStatus], peerManager: ActorRef): Props =
    Props(new ServerActor(nodeStatusHolder, peerManager))

  case class StartServer(address: InetSocketAddress)
} 
开发者ID:input-output-hk,项目名称:etc-client,代码行数:52,代码来源:ServerActor.scala

示例11: EtcHandshaker

//设置package包名称以及导入依赖的类
package io.iohk.ethereum.network.handshaker

import akka.agent.Agent
import io.iohk.ethereum.db.storage.AppStateStorage
import io.iohk.ethereum.domain.Blockchain
import io.iohk.ethereum.network.ForkResolver
import io.iohk.ethereum.network.PeerManagerActor.PeerConfiguration
import io.iohk.ethereum.network.EtcPeerManagerActor.PeerInfo
import io.iohk.ethereum.utils.NodeStatus

case class EtcHandshaker private (handshakerState: HandshakerState[PeerInfo],
                                  handshakerConfiguration: EtcHandshakerConfiguration) extends Handshaker[PeerInfo] {

  protected def copy(handshakerState: HandshakerState[PeerInfo]): Handshaker[PeerInfo] = {
    EtcHandshaker(handshakerState, handshakerConfiguration)
  }

}

object EtcHandshaker {

  def apply(handshakerConfiguration: EtcHandshakerConfiguration): EtcHandshaker = {
    val initialState = EtcHelloExchangeState(handshakerConfiguration)
    EtcHandshaker(initialState, handshakerConfiguration)
  }

}

trait EtcHandshakerConfiguration {
  val nodeStatusHolder: Agent[NodeStatus]
  val blockchain: Blockchain
  val appStateStorage: AppStateStorage
  val peerConfiguration: PeerConfiguration
  val forkResolverOpt: Option[ForkResolver]
} 
开发者ID:input-output-hk,项目名称:etc-client,代码行数:36,代码来源:EtcHandshaker.scala

示例12: NetServiceSpec

//设置package包名称以及导入依赖的类
package io.iohk.ethereum.jsonrpc

import java.net.InetSocketAddress

import akka.actor.ActorSystem
import akka.agent.Agent
import akka.testkit.TestProbe
import io.iohk.ethereum.{NormalPatience, crypto}
import io.iohk.ethereum.jsonrpc.NetService._
import io.iohk.ethereum.network.{Peer, PeerActor, PeerManagerActor}
import io.iohk.ethereum.nodebuilder.SecureRandomBuilder
import io.iohk.ethereum.utils.{NodeStatus, ServerStatus}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

class NetServiceSpec extends FlatSpec with Matchers with ScalaFutures with NormalPatience with SecureRandomBuilder {

  "NetService" should "return handshaked peer count" in new TestSetup {
    val resF = netService.peerCount(PeerCountRequest())

    peerManager.expectMsg(PeerManagerActor.GetPeers)
    peerManager.reply(PeerManagerActor.Peers(Map(
      Peer(new InetSocketAddress(1), testRef, false) -> PeerActor.Status.Handshaked,
      Peer(new InetSocketAddress(2), testRef, false) -> PeerActor.Status.Handshaked,
      Peer(new InetSocketAddress(3), testRef, false) -> PeerActor.Status.Connecting)))

    resF.futureValue shouldBe Right(PeerCountResponse(2))
  }

  it should "return listening response" in new TestSetup {
    netService.listening(ListeningRequest()).futureValue shouldBe Right(ListeningResponse(true))
  }

  it should "return version response" in new TestSetup {
    netService.version(VersionRequest()).futureValue shouldBe Right(VersionResponse("1"))
  }

  trait TestSetup {
    implicit val system = ActorSystem("Testsystem")

    val testRef = TestProbe().ref

    val peerManager = TestProbe()

    val nodeStatus = NodeStatus(crypto.generateKeyPair(secureRandom), ServerStatus.Listening(new InetSocketAddress(9000)),
      discoveryStatus = ServerStatus.NotListening)
    val netService = new NetService(Agent(nodeStatus), peerManager.ref, NetServiceConfig(5.seconds))
  }

} 
开发者ID:input-output-hk,项目名称:etc-client,代码行数:54,代码来源:NetServiceSpec.scala

示例13: JobStatus

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.platform.reindexer.models

import akka.agent.Agent
import uk.ac.wellcome.utils.GlobalExecutionContext.context

object JobStatus extends Enumeration {
  type JobStatus = Value

  val Init = Value("initialised")
  val Working = Value("working")
  val Success = Value("success")
  val Failure = Value("failure")
}

case class ReindexStatus(state: JobStatus.Value,
                         recordsProcessed: Int = 0,
                         batch: Int = 0) {
  def toMap =
    Map("state" -> state.toString,
        "recordsProcessed" -> s"$recordsProcessed",
        "batch" -> s"$batch")

}
object ReindexStatus {
  private val initState = ReindexStatus(JobStatus.Init)
  private val agent: Agent[ReindexStatus] = Agent[ReindexStatus](initState)

  def currentStatus: ReindexStatus = agent.get()

  def init(): Unit = agent.send(ReindexStatus(JobStatus.Init))

  def progress(units: Int, batch: Int = 0): Unit = {
    val currentCount = currentStatus.recordsProcessed + units
    val currentBatch = currentStatus.batch + batch

    agent.send(ReindexStatus(JobStatus.Working, currentCount, currentBatch))
  }

  def succeed(): Unit =
    agent.send(
      ReindexStatus(JobStatus.Success,
                    currentStatus.recordsProcessed,
                    currentStatus.batch))

  def fail(): Unit =
    agent.send(
      ReindexStatus(JobStatus.Failure,
                    currentStatus.recordsProcessed,
                    currentStatus.batch))
} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:51,代码来源:JobStatus.scala

示例14: addImage

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

import java.net.URL
import javax.inject.{ Inject, Singleton }

import akka.agent.Agent
import com.google.inject.ImplementedBy
import models.DropboxResponses.{ SaveStatus, Saved }
import play.api.Configuration
import play.api.libs.ws.WSClient
import utils.DropboxUtil

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Success

@ImplementedBy(classOf[VoteRepoSimple])
trait VoteRepo {
  
  def addImage(imageUrl: URL): Future[SaveStatus]
}

@Singleton
final class VoteRepoSimple @Inject() (val ws: WSClient,
                                      val conf: Configuration,
                                      implicit val ec: ExecutionContext) extends VoteRepo with DropboxUtil {
  private val agent = Agent(Map.empty[String, Long]) // Using Akka agent for thread safety

  def getReport: Future[Map[String, Long]] = {
    def addDiff(map: Map[String, Long], diff: Set[String]): Map[String, Long] =
      diff.foldLeft(map) { (newMap, imageName) => newMap + (imageName -> 0) } // add images that are not currently in the map
    for {
      allFiles <- listFiles
      curMap <- agent.future
      newMap <- agent.alter(map => addDiff(map, allFiles diff curMap.keySet))
    } yield newMap
  }

  def vote(imageName: String): Future[Option[Long]] = {
    def alterMap(map: Map[String, Long]): Map[String, Long] = map.get(imageName)
      .map(count => map + (imageName -> (count + 1)))
      .getOrElse(map + (imageName -> 1))
    listFiles.map(_.contains(imageName)).flatMap {
      case true => agent.alter(map => alterMap(map)).map(_.get(imageName))
      case false => Future.successful(None)
    }
  }

  def addImage(imageUrl: URL): Future[SaveStatus] = save(imageUrl) andThen {
    case Success(Saved(imageName)) => agent send (_ + (imageName -> 0))
  }
} 
开发者ID:kezhu,项目名称:imagevoter,代码行数:52,代码来源:VoteRepo.scala

示例15: BookStatistics

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

import akka.agent.Agent
import akka.actor.ActorSystem
import concurrent.Await
import concurrent.duration._
import akka.util.Timeout
//import concurrent.ExecutionContext.Implicits.global


case class BookStatistics(val nameBook: String, nrSold: Int)
case class StateBookStatistics(val sequence: Long,
                            books: Map[String, BookStatistics])


class BookStatisticsMgr(system: ActorSystem) {
  implicit val ex = system.dispatcher //todo: change chapter 2.2 =>2.3
  val stateAgent = Agent(new StateBookStatistics(0, Map())) //todo: change chapter 2.2 =>2.3

  def addBooksSold(book: String, nrSold: Int): Unit = {
    stateAgent send (oldState => {
      val bookStat = oldState.books.get(book) match {
        case Some(bookState) =>
          bookState.copy(nrSold = bookState.nrSold + nrSold)
        case None => new BookStatistics(book, nrSold)
      }
      oldState.copy(oldState.sequence + 1,
        oldState.books + (book -> bookStat))
    })
  }

  def addBooksSoldAndReturnNewState(book: String,
                                    nrSold: Int): StateBookStatistics = {
    val future = stateAgent alter (oldState => {
      val bookStat = oldState.books.get(book) match {
        case Some(bookState) =>
          bookState.copy(nrSold = bookState.nrSold + nrSold)
        case None => new BookStatistics(book, nrSold)
      }
      oldState.copy(oldState.sequence + 1,
        oldState.books + (book -> bookStat))
    })
    Await.result(future, 1 second)
  }

  def getStateBookStatistics(): StateBookStatistics = {
    stateAgent.get()
  }
} 
开发者ID:gilbutITbook,项目名称:006877,代码行数:50,代码来源:Agent.scala


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