【问题标题】:Scheduled Mysql query akka http定时Mysql查询akka http
【发布时间】:2016-05-27 03:41:09
【问题描述】:

我是洞 scala/akka 生态系统的新手。
我有一个 akka-http 路由定义如下:

object RestServiceApp extends CassandraConnector with Directives with JsonSupport {
  def main(args: Array[String]) {
    val config = ConfigFactory.load()
    implicit val actorSystem = ActorSystem("system", config)
    implicit val actorMaterializer = ActorMaterializer()

    var myFilterList = Seq(3L,32L,55L)

    val route: Route = {
      get {
        path("foo") {
          complete( foo().filter(element => myFilterList.contains(element) )
        }
    }
}

foo() 是一个返回元素的函数

我过滤这些元素并返回列表

我想:

  1. 每 M 分钟更新一次 myFilterList
  2. 为此,我必须进行 Mysql 查询

我不关心查询的性能,我关心的是在加载新的 myFilterList 时能够继续响应 http 请求。

我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: mysql scala akka akka-http


    【解决方案1】:

    你可以尝试做一个简单的缓存:

    object MyRefreshableList {
      private val updateInterval: Int = 600000 // 600000 millis == 10 minutes; you could use Java 8 Date/Time API or Joda Time methods here
      private var lastUpdateTime: Long = System.currentTimeMillis()
      private var cachedList: List[Long] = getList
    
      def value: List[Long] = cachedList // You would use that during your filtering
    
      // You would use that before your filtering
      def tryToRefresh() = {
        val currentTime = System.currentTimeMillis()
        if (currentTime > lastUpdateTime + updateInterval) {
          lastUpdateTime = currentTime
          refresh()
        }
      }
    
      private def refresh(): Unit = {
        cachedList = getList
      }
    
      private def getList: List[Long] = ??? // Make an actual SQL query here
    }
    

    您的代码的使用示例:

    val route: Route = {
      get {
        path("foo") {
          complete {
            MyRefreshableList.tryToRefresh()
            foo().filter(element => MyRefreshableList.value.contains(element)
          }
        }
      }
    }
    

    如果您有许多需要刷新的集合,您可以从该代码中提取 Refreshable 特征。

    【讨论】:

    • 嗨 Pawel,感谢您的回答!,我发布了另一个我认为有点不同的解决方案。请评论您的想法。再次感谢!
    【解决方案2】:

    我在末尾添加了一些代码,每M分钟查询一次mysql数据库并更新de Set

    val M = 30
    actorSystem.scheduler.schedule(50 milliseconds, M minutes) {
          val myNewFilterList = makeMysqlQuery()
          myFilterList = myNewFilterList 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2017-01-30
      • 1970-01-01
      相关资源
      最近更新 更多