假设您正在使用以下示例中的缓存: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(...)
并更新缓存。
接下来,您的代码可以遵循以下一种模式:
- 使用已缓存的路由,因为您已经在执行以下操作:
val route = cache(lfuCache,keyerFunction)(...
。
- 或者直接调用
lfuCache.get(key)
或lfuCache.getOrLoad(...)
而不使用高速缓存的dsl指令(不使用cache(lfuCache,...
)。
如果直接将Cache
类用于放置和检索值,请考虑使用更简单的键代替URI
值。
本文链接:https://www.f2er.com/3165872.html