gpt4 book ai didi

scala - 您将如何在 Scala 中实现缓存方面

转载 作者:行者123 更新时间:2023-12-02 06:59:38 26 4
gpt4 key购买 nike

头脑 Storm :我正在开发一个 Scala 项目,我们在该项目中进行服务调用,并且需要使用 memcache 缓存返回值。我正在研究一个 used decorators 的 Python 项目。注释应缓存其返回值的函数。我正在 Scala 中寻找一种类似的方式来向函数添加缓存方面。

假设我有这个函数 def callingService(arg1: String, arg2: Int): String 我想要

  • 根据函数名和参数计算缓存键
  • 如果缓存不包含 key ,则调用服务
  • 将返回值序列化并存储在缓存中
  • 否则反序列化缓存的值并返回

任何调用 callingService 的代码都不应该知道缓存。 callService 的实现应该只是调用服务 X 并返回一个 String 值,而不是处理缓存的东西。

最佳答案

我更喜欢 Stackable Trait Pattern 和 Cake Pattern:

class Service {
def callingService(arg1: String, arg2: Int): String = "ok"
}

trait Memo[K, V] {
def cache(k: K)(v : => V): V
}

trait ServiceCache extends Service {
self : Memo[(String, Int), String] =>

abstract override def callingService(arg1: String, arg2: Int): String =
cache((arg1, arg2)) { super.callingService(arg1, arg2) }
}

trait MapCache[K, V] extends Memo[K, V] {
private val _cache = new collection.mutable.HashMap[K, V]
def cache(k: K)(v : => V): V = _cache.getOrElseUpdate(k, v)
}

使用示例:

val service = new Service with ServiceCache with MapCache[(String, Int), String]

当然,您可以实现自己的缓存策略并在创建服务时与之混合

关于scala - 您将如何在 Scala 中实现缓存方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com