运行后台任务以更新缓存

我正在使用Akka-HTTP创建一个Web服务器。收到请求(到达特定路由)时,服务器将调用REST API。对该API的调用相当长。目前,我正在缓存结果,以便以下请求使用缓存。我想要一个后台任务,该任务会定期更新缓存(通过调用API)。当接收到请求时,服务器将使用缓存的结果(而不是必须调用API)。缓存只能通过后台任务进行更新。

我该怎么做?我可以使用Akka的调度模块定期运行任务,但是我不知道一旦任务运行后如何更新缓存。

目前,我有这样的事情:


val roster = Util.get_roster()
var pcache = new SRCache(roster)

val route = cache(lfuCache,keyerFunction)(
  pathSingleSlash {
    get {
      complete(
        HttpEntity(
          ContentTypes.`text/html(UTF-8)`,Views.index(pcache.get).toString))
    }
  }
)

pcache.get调用了API(这很慢),我想用简单地返回缓存内容并添加后台任务来更新缓存的东西来代替API调用。

T87182380 回答:运行后台任务以更新缓存

假设您正在使用以下示例中的缓存:https://doc.akka.io/docs/akka-http/current/common/caching.html

import akka.http.caching.scaladsl.Cache
import akka.http.caching.scaladsl.CachingSettings
import akka.http.caching.LfuCache
import akka.http.scaladsl.server.RequestContext
import akka.http.scaladsl.server.RouteResult
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.server.directives.CachingDirectives._
import scala.concurrent.duration._

// Use the request's URI as the cache's key
val keyerFunction: PartialFunction[RequestContext,Uri] = {
  case r: RequestContext => r.request.uri
}
val defaultCachingSettings = CachingSettings(system)
val lfuCacheSettings =
  defaultCachingSettings.lfuCacheSettings
    .withInitialCapacity(25)
    .withMaxCapacity(50)
    .withTimeToLive(20.seconds)
    .withTimeToIdle(10.seconds)
val cachingSettings =
  defaultCachingSettings.withLfuCacheSettings(lfuCacheSettings)
val lfuCache: Cache[Uri,RouteResult] = LfuCache(cachingSettings)

// Create the route
val route = cache(lfuCache,keyerFunction)(innerRoute)

您的后台任务应安排为更新lfuCache。您可以使用以下缓存类的接口:https://doc.akka.io/api/akka-http/10.1.10/akka/http/caching/scaladsl/Cache.html

感兴趣的方法:

 abstract def get(key: K): Option[Future[V]]
 // Retrieves the future instance that is currently in the cache for the given key.

 abstract def getOrLoad(key: K,loadValue: (K) ⇒ Future[V]): Future[V]
 // Returns either the cached Future for the given key,// or applies the given value loading function on the key,producing a Future[V].

 abstract def put(key: K,mayBeValue: Future[V])
                 (implicit ex: ExecutionContext): Future[V]
 // Cache the given future if not cached previously.

这是您可以使用的Scheduler界面:

https://doc.akka.io/docs/akka/current/scheduler.html

val cancellable =
  system.scheduler.schedule(0 milliseconds,5 seconds,...)

您的调度程序将每n秒调用lfuCache.put(...)并更新缓存。

接下来,您的代码可以遵循以下一种模式:

  1. 使用已缓存的路由,因为您已经在执行以下操作: val route = cache(lfuCache,keyerFunction)(...
  2. 或者直接调用lfuCache.get(key)lfuCache.getOrLoad(...)而不使用高速缓存的dsl指令(不使用cache(lfuCache,...)。

如果直接将Cache类用于放置和检索值,请考虑使用更简单的键代替URI值。

本文链接:https://www.f2er.com/3165872.html

大家都在问