gpt4 book ai didi

caching - Clojure 的 `memoize` 函数在缓存慢速 sql 查询和复杂计算方面有用吗?

转载 作者:行者123 更新时间:2023-12-01 22:20:42 25 4
gpt4 key购买 nike

我的项目有一个 mysql 数据库和一个由 Clojure 编写的后端。

数据库某表每天只更新一次,查询最新的我们将使用的信息。

但是:

  1. 数据库很大,网络很慢,所以每次查询都会花点时间。

  2. 我们需要在每次查询后进行复杂的计算。

  3. 我们需要进行多种sql查询,所以保存每条sql查询的结果是不现实的。

  4. 我们需要非常频繁地更改计算函数调试的目的。

对于缓慢的 sql 查询,现在所有事情对我们来说都太慢了。

幸运的是,我们的数据每天只会更新一次,而且我们对数据库的一些查询是非常频繁使用的。

所以我们要缓存经常使用的sql查询和中间结果。

Clojure 的memoize 函数对这类工作有用吗?我担心的是 sql 查询不是纯粹的,所以 memoize 不应该缓存它们的结果。但是有一天,我们的 sql 查询结果必须相同。

那么我可以记住一天的结果并在第二天自动更新结果吗?

感谢您的帮助!

最佳答案

您应该为此使用缓存,例如。 G。 clojure.core.cache.

澄清一下评论:内存有助于纯函数:如果你的函数总是在给定相同输入的情况下返回相同的输出,你可以在计算一次后存储它。

如果输出随时间变化,则需要做失效处理。带有失效的内存(以及其他一些问题,例如记住的东西的大小)称为“缓存”。

如果您使用内存机制进行缓存,您实际上是在其上实现缓存。仅使用缓存库的工作要少得多。

在这种情况下,您需要实现类似“午夜失效”的功能。参见 https://github.com/clojure/core.cache/wiki寻求指导如何做到这一点。

编辑:它可能看起来有点像这样(未经测试,带上你自己的今天):

(defcache MidnightCache [cache dates]
CacheProtocol
(lookup [this key]
(lookup this key nil))
(lookup [this key not-found]
(if (has? this key)
(get cache key)
not-found))
(has? [this key]
(let [d (get dates key)]
(and d
(= d (today)))))
(hit [this key]
this)
(miss [this key new-value]
(MidnightCache. (assoc (dissoc cache key)
key new-value)
(assoc (dissoc dates key)
key (today))))
(evict [this key]
(MidnightCache. (dissoc cache key)
(dissoc dates key)))
(seed [this base]
(MidnightCache. base
(zipmap (keys base)
(iterate identity (today))))))

关于caching - Clojure 的 `memoize` 函数在缓存慢速 sql 查询和复杂计算方面有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40288276/

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