加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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,如果这对您来说很重要,那么此代码也可以在浏览器中使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读