scala – 节流或去抖方法调用
发布时间:2020-12-16 18:13:05 所属栏目:安全 来源:网络整理
导读:假设我有一个方法允许更新DB中的某些日期: def updateLastConsultationDate(userId: String): Unit = ??? 如何轻松地对该方法进行节流/去抖动,以使每个用户每小时运行不超过一次. 我想要最简单的解决方案,而不是基于任何事件总线,actor lib或持久层.我想要
假设我有一个方法允许更新DB中的某些日期:
def updateLastConsultationDate(userId: String): Unit = ??? 如何轻松地对该方法进行节流/去抖动,以使每个用户每小时运行不超过一次. 我想要最简单的解决方案,而不是基于任何事件总线,actor lib或持久层.我想要一个内存解决方案(我知道风险). 我已经看到了基于Akka Throttler的Scala限制解决方案,但这真的让我觉得开始使用actor只是为了限制方法调用.有没有一个非常简单的方法来做到这一点? 编辑:因为它似乎不够清楚,这是我想要的visual representation,用JS实现.正如您所看到的,限制可能不仅仅是过滤后续调用,还可以推迟调用(在js / lodash / underscore中也称为尾随事件).我正在寻找的解决方案不能仅基于纯同步代码. 解决方法
对于基于
ReactiveX的解决方案来说,这听起来非常棒.在Scala上,Monix是我最喜欢的一个.这是
Ammonite REPL会话,说明了它:
import $ivy.`io.monix::monix:2.1.0` // I'm using Ammonite's magic imports,it's equivalent to adding "io.monix" %% "monix" % "2.1.0" into your libraryImports in SBT import scala.concurrent.duration.DurationInt import monix.reactive.subjects.ConcurrentSubject import monix.reactive.Consumer import monix.execution.Scheduler.Implicits.global import monix.eval.Task class DbUpdater { val publish = ConcurrentSubject.publish[String] val throttled = publish.throttleFirst(1 hour) val cancelHandle = throttled.consumeWith( Consumer.foreach(userId => println(s"update your database with $userId here"))) .runAsync def updateLastConsultationDate(userId: String): Unit = { publish.onNext(userId) } def stop(): Unit = cancelHandle.cancel() } 是的,并且对于Scala.js,如果这对您来说很重要,那么此代码也可以在浏览器中使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angular6 – 错误:rxjs / operator / map没有导出成员’ma
- 如何在QWERTZ键盘上键入CTRL](为了使用Vim跳转到标签)?
- Angular 2 Change Detection - 1
- bash – 在自制软件安装脚本中旁路提示(按返回)
- bootstrap入门【组件之按钮组,下拉菜单,嵌套】
- angularjs passy masonry – TypeError:element.masonry不
- angularjs ngModel未在选择输入中选择选项
- 将Angular 2应用转变为移动应用
- cxf传输对象
- angular2 – CUSTOM_ELEMENTS_SCHEMA添加到NgModule.schema