scala - 如何使此定期指标收集代码更具功能性(不可变状态)?
问题描述
这是我的代码的大纲
有多个工人演员,我正在从他们httpActorLatencies
那里收集一些延迟统计信息到地图中,其中每个工人演员的延迟被单独跟踪,然后登录接收LogQueueLatency
消息。此时,里面的所有队列httpActorLatencies
也都被清空了。
有没有办法以合理的方式摆脱可变 Map ?
class StatsActor(workerCount: Int) extends Actor {
val httpActorLatencies = scala.collection.mutable.Map[Int, scala.collection.mutable.MutableList[Long]]()
override def preStart(): Unit = {
Range(0, workerCount).foreach(i => httpActorLatencies.put(i, scala.collection.mutable.MutableList()))
}
override def receive = {
case shardLatency: QueuingLatency =>
httpActorLatencies(shardLatency.shardNumber) += shardLatency.latency
case LogQueueLatency =>
outputCollectedStats()
}
private def outputCollectedStats(): Unit = {
output(StatsActor.computePerShardMeanLatencies(httpActorLatencies))
httpActorLatencies.foreach(x => x._2.clear())
}
}
解决方案
一种方法是使用context.become
一个带有它的接收函数Map
,如下所示:
class StatsActor extends Actor {
def newMap() = Map[Int, List[Long]]().withDefault(Nil)
def receive: Receive = countingReceive(newMap())
def countingReceive(httpActorLatencies: Map[Int, List[Long]]): Receive = {
case shardLatency: QueuingLatency =>
val newList = httpActorLatencies(shardLatency.shardNumber) :+ shardLatency.latency
val newMap = httpActorLatencies.updated(shardLatency.shardNumber, newList)
context.become(countingReceive(newMap))
case LogQueueLatency =>
outputCollectedStats(httpActorLatencies)
context.become(receive)
}
private def outputCollectedStats(httpActorLatencies: Map[Int, List[Long]]): Unit = {
...
}
}
这是未经测试的并且可能已损坏,但它应该给出如何完成的想法。
另请注意,我已使用withDefault
来Map
简化逻辑并消除对workerCount
.
推荐阅读
- powershell - 3 Graph API Endpoints - 匹配后将列从一个插入到另一个
- flask - 使用 WebView/Media Source 在 UWP 应用程序中播放 Flask Video Feed
- reactjs - 通过显示具有字段最大值或最小值的文档对搜索结果进行分组
- javascript - 是否可以创建一个链接,在单击时替换下一个访问者的目标 URL 重定向
- reactjs - 提交后React Metarial ui重定向到另一个选项卡?
- django - 如何根据人是否是超级用户来更改 Django 中的管理员颜色?
- sql-server - ASP.NET Core MVC - how to add button to Home view that executes SQL?
- r - 在事先不知道数据框 2 中的列的情况下,使用数据框 2 子集数据框 1
- c++ - 在子请求完成回调和请求正文过滤器中创建子请求
- websocket - 在 JMeter 中没有获得 Websocket 响应